Rollup merge of #119869 - oli-obk:track_errors2, r=matthewjasper

replace `track_errors` usages with bubbling up `ErrorGuaranteed`

more of the same as https://github.com/rust-lang/rust/pull/117449 (removing `track_errors`)
This commit is contained in:
Matthias Krüger 2024-01-18 20:56:20 +01:00 committed by GitHub
commit fa52edaa51
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 342 additions and 192 deletions

View file

@ -1446,7 +1446,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
}
let candidates: Vec<_> = tcx
.inherent_impls(adt_did)
.inherent_impls(adt_did)?
.iter()
.filter_map(|&impl_| Some((impl_, self.lookup_assoc_ty_unchecked(name, block, impl_)?)))
.collect();

View file

@ -13,32 +13,41 @@ use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::ty::fast_reject::{simplify_type, SimplifiedType, TreatParams};
use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt};
use rustc_span::symbol::sym;
use rustc_span::ErrorGuaranteed;
use crate::errors;
/// On-demand query: yields a map containing all types mapped to their inherent impls.
pub fn crate_inherent_impls(tcx: TyCtxt<'_>, (): ()) -> CrateInherentImpls {
pub fn crate_inherent_impls(
tcx: TyCtxt<'_>,
(): (),
) -> Result<&'_ CrateInherentImpls, ErrorGuaranteed> {
let mut collect = InherentCollect { tcx, impls_map: Default::default() };
let mut res = Ok(());
for id in tcx.hir().items() {
collect.check_item(id);
res = res.and(collect.check_item(id));
}
collect.impls_map
res?;
Ok(tcx.arena.alloc(collect.impls_map))
}
pub fn crate_incoherent_impls(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] {
let crate_map = tcx.crate_inherent_impls(());
tcx.arena.alloc_from_iter(
pub fn crate_incoherent_impls(
tcx: TyCtxt<'_>,
simp: SimplifiedType,
) -> Result<&[DefId], ErrorGuaranteed> {
let crate_map = tcx.crate_inherent_impls(())?;
Ok(tcx.arena.alloc_from_iter(
crate_map.incoherent_impls.get(&simp).unwrap_or(&Vec::new()).iter().map(|d| d.to_def_id()),
)
))
}
/// On-demand query: yields a vector of the inherent impls for a specific type.
pub fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> &[DefId] {
let crate_map = tcx.crate_inherent_impls(());
match crate_map.inherent_impls.get(&ty_def_id) {
pub fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> Result<&[DefId], ErrorGuaranteed> {
let crate_map = tcx.crate_inherent_impls(())?;
Ok(match crate_map.inherent_impls.get(&ty_def_id) {
Some(v) => &v[..],
None => &[],
}
})
}
struct InherentCollect<'tcx> {
@ -47,14 +56,19 @@ struct InherentCollect<'tcx> {
}
impl<'tcx> InherentCollect<'tcx> {
fn check_def_id(&mut self, impl_def_id: LocalDefId, self_ty: Ty<'tcx>, ty_def_id: DefId) {
fn check_def_id(
&mut self,
impl_def_id: LocalDefId,
self_ty: Ty<'tcx>,
ty_def_id: DefId,
) -> Result<(), ErrorGuaranteed> {
if let Some(ty_def_id) = ty_def_id.as_local() {
// Add the implementation to the mapping from implementation to base
// type def ID, if there is a base type for this implementation and
// the implementation does not have any associated traits.
let vec = self.impls_map.inherent_impls.entry(ty_def_id).or_default();
vec.push(impl_def_id.to_def_id());
return;
return Ok(());
}
if self.tcx.features().rustc_attrs {
@ -62,18 +76,16 @@ impl<'tcx> InherentCollect<'tcx> {
if !self.tcx.has_attr(ty_def_id, sym::rustc_has_incoherent_inherent_impls) {
let impl_span = self.tcx.def_span(impl_def_id);
self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span });
return;
return Err(self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span }));
}
for &impl_item in items {
if !self.tcx.has_attr(impl_item, sym::rustc_allow_incoherent_impl) {
let impl_span = self.tcx.def_span(impl_def_id);
self.tcx.dcx().emit_err(errors::InherentTyOutsideRelevant {
return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideRelevant {
span: impl_span,
help_span: self.tcx.def_span(impl_item),
});
return;
}));
}
}
@ -82,24 +94,28 @@ impl<'tcx> InherentCollect<'tcx> {
} else {
bug!("unexpected self type: {:?}", self_ty);
}
Ok(())
} else {
let impl_span = self.tcx.def_span(impl_def_id);
self.tcx.dcx().emit_err(errors::InherentTyOutsideNew { span: impl_span });
Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideNew { span: impl_span }))
}
}
fn check_primitive_impl(&mut self, impl_def_id: LocalDefId, ty: Ty<'tcx>) {
fn check_primitive_impl(
&mut self,
impl_def_id: LocalDefId,
ty: Ty<'tcx>,
) -> Result<(), ErrorGuaranteed> {
let items = self.tcx.associated_item_def_ids(impl_def_id);
if !self.tcx.hir().rustc_coherence_is_core() {
if self.tcx.features().rustc_attrs {
for &impl_item in items {
if !self.tcx.has_attr(impl_item, sym::rustc_allow_incoherent_impl) {
let span = self.tcx.def_span(impl_def_id);
self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive {
return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive {
span,
help_span: self.tcx.def_span(impl_item),
});
return;
}));
}
}
} else {
@ -108,8 +124,7 @@ impl<'tcx> InherentCollect<'tcx> {
if let ty::Ref(_, subty, _) = ty.kind() {
note = Some(errors::InherentPrimitiveTyNote { subty: *subty });
}
self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note });
return;
return Err(self.tcx.dcx().emit_err(errors::InherentPrimitiveTy { span, note }));
}
}
@ -118,11 +133,12 @@ impl<'tcx> InherentCollect<'tcx> {
} else {
bug!("unexpected primitive type: {:?}", ty);
}
Ok(())
}
fn check_item(&mut self, id: hir::ItemId) {
fn check_item(&mut self, id: hir::ItemId) -> Result<(), ErrorGuaranteed> {
if !matches!(self.tcx.def_kind(id.owner_id), DefKind::Impl { of_trait: false }) {
return;
return Ok(());
}
let id = id.owner_id.def_id;
@ -132,10 +148,10 @@ impl<'tcx> InherentCollect<'tcx> {
ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()),
ty::Foreign(did) => self.check_def_id(id, self_ty, did),
ty::Dynamic(data, ..) if data.principal_def_id().is_some() => {
self.check_def_id(id, self_ty, data.principal_def_id().unwrap());
self.check_def_id(id, self_ty, data.principal_def_id().unwrap())
}
ty::Dynamic(..) => {
self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span });
Err(self.tcx.dcx().emit_err(errors::InherentDyn { span: item_span }))
}
ty::Bool
| ty::Char
@ -151,7 +167,7 @@ impl<'tcx> InherentCollect<'tcx> {
| ty::FnPtr(_)
| ty::Tuple(..) => self.check_primitive_impl(id, self_ty),
ty::Alias(..) | ty::Param(_) => {
self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span });
Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span }))
}
ty::FnDef(..)
| ty::Closure(..)
@ -162,7 +178,8 @@ impl<'tcx> InherentCollect<'tcx> {
| ty::Infer(_) => {
bug!("unexpected impl self type of impl: {:?} {:?}", id, self_ty);
}
ty::Error(_) => {}
// We could bail out here, but that will silence other useful errors.
ty::Error(_) => Ok(()),
}
}
}

View file

@ -6,16 +6,18 @@ use rustc_hir::def_id::DefId;
use rustc_index::IndexVec;
use rustc_middle::traits::specialization_graph::OverlapMode;
use rustc_middle::ty::{self, TyCtxt};
use rustc_span::Symbol;
use rustc_span::{ErrorGuaranteed, Symbol};
use rustc_trait_selection::traits::{self, SkipLeakCheck};
use smallvec::SmallVec;
use std::collections::hash_map::Entry;
pub fn crate_inherent_impls_overlap_check(tcx: TyCtxt<'_>, (): ()) {
pub fn crate_inherent_impls_overlap_check(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
let mut inherent_overlap_checker = InherentOverlapChecker { tcx };
let mut res = Ok(());
for id in tcx.hir().items() {
inherent_overlap_checker.check_item(id);
res = res.and(inherent_overlap_checker.check_item(id));
}
res
}
struct InherentOverlapChecker<'tcx> {
@ -58,10 +60,11 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
== item2.ident(self.tcx).normalize_to_macros_2_0()
}
fn check_for_duplicate_items_in_impl(&self, impl_: DefId) {
fn check_for_duplicate_items_in_impl(&self, impl_: DefId) -> Result<(), ErrorGuaranteed> {
let impl_items = self.tcx.associated_items(impl_);
let mut seen_items = FxHashMap::default();
let mut res = Ok(());
for impl_item in impl_items.in_definition_order() {
let span = self.tcx.def_span(impl_item.def_id);
let ident = impl_item.ident(self.tcx);
@ -70,7 +73,7 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
match seen_items.entry(norm_ident) {
Entry::Occupied(entry) => {
let former = entry.get();
struct_span_code_err!(
res = Err(struct_span_code_err!(
self.tcx.dcx(),
span,
E0592,
@ -79,13 +82,14 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
)
.with_span_label(span, format!("duplicate definitions for `{ident}`"))
.with_span_label(*former, format!("other definition for `{ident}`"))
.emit();
.emit());
}
Entry::Vacant(entry) => {
entry.insert(span);
}
}
}
res
}
fn check_for_common_items_in_impls(
@ -93,10 +97,11 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
impl1: DefId,
impl2: DefId,
overlap: traits::OverlapResult<'_>,
) {
) -> Result<(), ErrorGuaranteed> {
let impl_items1 = self.tcx.associated_items(impl1);
let impl_items2 = self.tcx.associated_items(impl2);
let mut res = Ok(());
for &item1 in impl_items1.in_definition_order() {
let collision = impl_items2
.filter_by_name_unhygienic(item1.name)
@ -128,9 +133,10 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
traits::add_placeholder_note(&mut err);
}
err.emit();
res = Err(err.emit());
}
}
res
}
fn check_for_overlapping_inherent_impls(
@ -138,7 +144,7 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
overlap_mode: OverlapMode,
impl1_def_id: DefId,
impl2_def_id: DefId,
) {
) -> Result<(), ErrorGuaranteed> {
let maybe_overlap = traits::overlapping_impls(
self.tcx,
impl1_def_id,
@ -150,17 +156,19 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
);
if let Some(overlap) = maybe_overlap {
self.check_for_common_items_in_impls(impl1_def_id, impl2_def_id, overlap);
self.check_for_common_items_in_impls(impl1_def_id, impl2_def_id, overlap)
} else {
Ok(())
}
}
fn check_item(&mut self, id: hir::ItemId) {
fn check_item(&mut self, id: hir::ItemId) -> Result<(), ErrorGuaranteed> {
let def_kind = self.tcx.def_kind(id.owner_id);
if !matches!(def_kind, DefKind::Enum | DefKind::Struct | DefKind::Trait | DefKind::Union) {
return;
return Ok(());
}
let impls = self.tcx.inherent_impls(id.owner_id);
let impls = self.tcx.inherent_impls(id.owner_id)?;
let overlap_mode = OverlapMode::get(self.tcx, id.owner_id.to_def_id());
@ -173,17 +181,18 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
// otherwise switch to an allocating algorithm with
// faster asymptotic runtime.
const ALLOCATING_ALGO_THRESHOLD: usize = 500;
let mut res = Ok(());
if impls.len() < ALLOCATING_ALGO_THRESHOLD {
for (i, &(&impl1_def_id, impl_items1)) in impls_items.iter().enumerate() {
self.check_for_duplicate_items_in_impl(impl1_def_id);
res = res.and(self.check_for_duplicate_items_in_impl(impl1_def_id));
for &(&impl2_def_id, impl_items2) in &impls_items[(i + 1)..] {
if self.impls_have_common_items(impl_items1, impl_items2) {
self.check_for_overlapping_inherent_impls(
res = res.and(self.check_for_overlapping_inherent_impls(
overlap_mode,
impl1_def_id,
impl2_def_id,
);
));
}
}
}
@ -315,20 +324,21 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
impl_blocks.sort_unstable();
for (i, &impl1_items_idx) in impl_blocks.iter().enumerate() {
let &(&impl1_def_id, impl_items1) = &impls_items[impl1_items_idx];
self.check_for_duplicate_items_in_impl(impl1_def_id);
res = res.and(self.check_for_duplicate_items_in_impl(impl1_def_id));
for &impl2_items_idx in impl_blocks[(i + 1)..].iter() {
let &(&impl2_def_id, impl_items2) = &impls_items[impl2_items_idx];
if self.impls_have_common_items(impl_items1, impl_items2) {
self.check_for_overlapping_inherent_impls(
res = res.and(self.check_for_overlapping_inherent_impls(
overlap_mode,
impl1_def_id,
impl2_def_id,
);
));
}
}
}
}
}
res
}
}

View file

@ -5,20 +5,22 @@ use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{self as hir, def, Expr, ImplItem, Item, Node, TraitItem};
use rustc_middle::hir::nested_filter;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::{sym, DUMMY_SP};
use rustc_span::{sym, ErrorGuaranteed, DUMMY_SP};
use crate::errors::{TaitForwardCompat, TypeOf, UnconstrainedOpaqueType};
pub fn test_opaque_hidden_types(tcx: TyCtxt<'_>) {
pub fn test_opaque_hidden_types(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
let mut res = Ok(());
if tcx.has_attr(CRATE_DEF_ID, sym::rustc_hidden_type_of_opaques) {
for id in tcx.hir().items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::OpaqueTy) {
let type_of = tcx.type_of(id.owner_id).instantiate_identity();
tcx.dcx().emit_err(TypeOf { span: tcx.def_span(id.owner_id), type_of });
res = Err(tcx.dcx().emit_err(TypeOf { span: tcx.def_span(id.owner_id), type_of }));
}
}
}
res
}
/// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions

View file

@ -17,7 +17,7 @@ use rustc_hir::def::DefKind;
use rustc_hir::def_id::{LocalDefId, LocalModDefId};
use rustc_middle::query::Providers;
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
use rustc_span::{Span, Symbol};
use rustc_span::{ErrorGuaranteed, Span, Symbol};
mod min_specialization;
@ -51,24 +51,29 @@ mod min_specialization;
/// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
/// // ^ 'a is unused and appears in assoc type, error
/// ```
fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) -> Result<(), ErrorGuaranteed> {
let min_specialization = tcx.features().min_specialization;
let module = tcx.hir_module_items(module_def_id);
let mut res = Ok(());
for id in module.items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::Impl { .. }) {
enforce_impl_params_are_constrained(tcx, id.owner_id.def_id);
res = res.and(enforce_impl_params_are_constrained(tcx, id.owner_id.def_id));
if min_specialization {
check_min_specialization(tcx, id.owner_id.def_id);
res = res.and(check_min_specialization(tcx, id.owner_id.def_id));
}
}
}
res
}
pub fn provide(providers: &mut Providers) {
*providers = Providers { check_mod_impl_wf, ..*providers };
}
fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
fn enforce_impl_params_are_constrained(
tcx: TyCtxt<'_>,
impl_def_id: LocalDefId,
) -> Result<(), ErrorGuaranteed> {
// Every lifetime used in an associated type must be constrained.
let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity();
if impl_self_ty.references_error() {
@ -80,7 +85,10 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)
"potentially unconstrained type parameters weren't evaluated: {impl_self_ty:?}",
),
);
return;
// This is super fishy, but our current `rustc_hir_analysis::check_crate` pipeline depends on
// `type_of` having been called much earlier, and thus this value being read from cache.
// Compilation must continue in order for other important diagnostics to keep showing up.
return Ok(());
}
let impl_generics = tcx.generics_of(impl_def_id);
let impl_predicates = tcx.predicates_of(impl_def_id);
@ -113,13 +121,19 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)
})
.collect();
let mut res = Ok(());
for param in &impl_generics.params {
match param.kind {
// Disallow ANY unconstrained type parameters.
ty::GenericParamDefKind::Type { .. } => {
let param_ty = ty::ParamTy::for_def(param);
if !input_parameters.contains(&cgp::Parameter::from(param_ty)) {
report_unused_parameter(tcx, tcx.def_span(param.def_id), "type", param_ty.name);
res = Err(report_unused_parameter(
tcx,
tcx.def_span(param.def_id),
"type",
param_ty.name,
));
}
}
ty::GenericParamDefKind::Lifetime => {
@ -127,27 +141,28 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)
if lifetimes_in_associated_types.contains(&param_lt) && // (*)
!input_parameters.contains(&param_lt)
{
report_unused_parameter(
res = Err(report_unused_parameter(
tcx,
tcx.def_span(param.def_id),
"lifetime",
param.name,
);
));
}
}
ty::GenericParamDefKind::Const { .. } => {
let param_ct = ty::ParamConst::for_def(param);
if !input_parameters.contains(&cgp::Parameter::from(param_ct)) {
report_unused_parameter(
res = Err(report_unused_parameter(
tcx,
tcx.def_span(param.def_id),
"const",
param_ct.name,
);
));
}
}
}
}
res
// (*) This is a horrible concession to reality. I think it'd be
// better to just ban unconstrained lifetimes outright, but in
@ -169,7 +184,12 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)
// used elsewhere are not projected back out.
}
fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol) {
fn report_unused_parameter(
tcx: TyCtxt<'_>,
span: Span,
kind: &str,
name: Symbol,
) -> ErrorGuaranteed {
let mut err = struct_span_code_err!(
tcx.dcx(),
span,
@ -188,5 +208,5 @@ fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol
"proving the result of expressions other than the parameter are unique is not supported",
);
}
err.emit();
err.emit()
}

View file

@ -82,10 +82,14 @@ use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, translate_args_with_cause, wf, ObligationCtxt};
pub(super) fn check_min_specialization(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
pub(super) fn check_min_specialization(
tcx: TyCtxt<'_>,
impl_def_id: LocalDefId,
) -> Result<(), ErrorGuaranteed> {
if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
check_always_applicable(tcx, impl_def_id, node);
check_always_applicable(tcx, impl_def_id, node)?;
}
Ok(())
}
fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Option<Node> {
@ -109,42 +113,58 @@ fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Opti
/// Check that `impl1` is a sound specialization
#[instrument(level = "debug", skip(tcx))]
fn check_always_applicable(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node) {
fn check_always_applicable(
tcx: TyCtxt<'_>,
impl1_def_id: LocalDefId,
impl2_node: Node,
) -> Result<(), ErrorGuaranteed> {
let span = tcx.def_span(impl1_def_id);
check_has_items(tcx, impl1_def_id, impl2_node, span);
let mut res = check_has_items(tcx, impl1_def_id, impl2_node, span);
if let Ok((impl1_args, impl2_args)) = get_impl_args(tcx, impl1_def_id, impl2_node) {
let impl2_def_id = impl2_node.def_id();
debug!(?impl2_def_id, ?impl2_args);
let (impl1_args, impl2_args) = get_impl_args(tcx, impl1_def_id, impl2_node)?;
let impl2_def_id = impl2_node.def_id();
debug!(?impl2_def_id, ?impl2_args);
let parent_args = if impl2_node.is_from_trait() {
impl2_args.to_vec()
} else {
unconstrained_parent_impl_args(tcx, impl2_def_id, impl2_args)
};
let parent_args = if impl2_node.is_from_trait() {
impl2_args.to_vec()
} else {
unconstrained_parent_impl_args(tcx, impl2_def_id, impl2_args)
};
check_constness(tcx, impl1_def_id, impl2_node, span);
check_static_lifetimes(tcx, &parent_args, span);
check_duplicate_params(tcx, impl1_args, &parent_args, span);
check_predicates(tcx, impl1_def_id, impl1_args, impl2_node, impl2_args, span);
}
res = res.and(check_constness(tcx, impl1_def_id, impl2_node, span));
res = res.and(check_static_lifetimes(tcx, &parent_args, span));
res = res.and(check_duplicate_params(tcx, impl1_args, &parent_args, span));
res = res.and(check_predicates(tcx, impl1_def_id, impl1_args, impl2_node, impl2_args, span));
res
}
fn check_has_items(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, span: Span) {
fn check_has_items(
tcx: TyCtxt<'_>,
impl1_def_id: LocalDefId,
impl2_node: Node,
span: Span,
) -> Result<(), ErrorGuaranteed> {
if let Node::Impl(impl2_id) = impl2_node
&& tcx.associated_item_def_ids(impl1_def_id).is_empty()
{
let base_impl_span = tcx.def_span(impl2_id);
tcx.dcx().emit_err(errors::EmptySpecialization { span, base_impl_span });
return Err(tcx.dcx().emit_err(errors::EmptySpecialization { span, base_impl_span }));
}
Ok(())
}
/// Check that the specializing impl `impl1` is at least as const as the base
/// impl `impl2`
fn check_constness(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, span: Span) {
fn check_constness(
tcx: TyCtxt<'_>,
impl1_def_id: LocalDefId,
impl2_node: Node,
span: Span,
) -> Result<(), ErrorGuaranteed> {
if impl2_node.is_from_trait() {
// This isn't a specialization
return;
return Ok(());
}
let impl1_constness = tcx.constness(impl1_def_id.to_def_id());
@ -152,9 +172,10 @@ fn check_constness(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node,
if let hir::Constness::Const = impl2_constness {
if let hir::Constness::NotConst = impl1_constness {
tcx.dcx().emit_err(errors::ConstSpecialize { span });
return Err(tcx.dcx().emit_err(errors::ConstSpecialize { span }));
}
}
Ok(())
}
/// Given a specializing impl `impl1`, and the base impl `impl2`, returns two
@ -290,15 +311,17 @@ fn check_duplicate_params<'tcx>(
impl1_args: GenericArgsRef<'tcx>,
parent_args: &Vec<GenericArg<'tcx>>,
span: Span,
) {
) -> Result<(), ErrorGuaranteed> {
let mut base_params = cgp::parameters_for(parent_args, true);
base_params.sort_by_key(|param| param.0);
if let (_, [duplicate, ..]) = base_params.partition_dedup() {
let param = impl1_args[duplicate.0 as usize];
tcx.dcx()
return Err(tcx
.dcx()
.struct_span_err(span, format!("specializing impl repeats parameter `{param}`"))
.emit();
.emit());
}
Ok(())
}
/// Check that `'static` lifetimes are not introduced by the specializing impl.
@ -313,10 +336,11 @@ fn check_static_lifetimes<'tcx>(
tcx: TyCtxt<'tcx>,
parent_args: &Vec<GenericArg<'tcx>>,
span: Span,
) {
) -> Result<(), ErrorGuaranteed> {
if tcx.any_free_region_meets(parent_args, |r| r.is_static()) {
tcx.dcx().emit_err(errors::StaticSpecialize { span });
return Err(tcx.dcx().emit_err(errors::StaticSpecialize { span }));
}
Ok(())
}
/// Check whether predicates on the specializing impl (`impl1`) are allowed.
@ -337,7 +361,7 @@ fn check_predicates<'tcx>(
impl2_node: Node,
impl2_args: GenericArgsRef<'tcx>,
span: Span,
) {
) -> Result<(), ErrorGuaranteed> {
let impl1_predicates: Vec<_> = traits::elaborate(
tcx,
tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_args).into_iter(),
@ -399,14 +423,16 @@ fn check_predicates<'tcx>(
}
impl2_predicates.extend(traits::elaborate(tcx, always_applicable_traits));
let mut res = Ok(());
for (clause, span) in impl1_predicates {
if !impl2_predicates
.iter()
.any(|pred2| trait_predicates_eq(tcx, clause.as_predicate(), *pred2, span))
{
check_specialization_on(tcx, clause, span)
res = res.and(check_specialization_on(tcx, clause, span))
}
}
res
}
/// Checks if some predicate on the specializing impl (`predicate1`) is the same
@ -443,19 +469,26 @@ fn trait_predicates_eq<'tcx>(
}
#[instrument(level = "debug", skip(tcx))]
fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, clause: ty::Clause<'tcx>, span: Span) {
fn check_specialization_on<'tcx>(
tcx: TyCtxt<'tcx>,
clause: ty::Clause<'tcx>,
span: Span,
) -> Result<(), ErrorGuaranteed> {
match clause.kind().skip_binder() {
// Global predicates are either always true or always false, so we
// are fine to specialize on.
_ if clause.is_global() => (),
_ if clause.is_global() => Ok(()),
// We allow specializing on explicitly marked traits with no associated
// items.
ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
if !matches!(
if matches!(
trait_specialization_kind(tcx, clause),
Some(TraitSpecializationKind::Marker)
) {
tcx.dcx()
Ok(())
} else {
Err(tcx
.dcx()
.struct_span_err(
span,
format!(
@ -463,17 +496,16 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, clause: ty::Clause<'tcx>, sp
tcx.def_path_str(trait_ref.def_id),
),
)
.emit();
.emit())
}
}
ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
tcx.dcx()
.struct_span_err(
span,
format!("cannot specialize on associated type `{projection_ty} == {term}`",),
)
.emit();
}
ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => Err(tcx
.dcx()
.struct_span_err(
span,
format!("cannot specialize on associated type `{projection_ty} == {term}`",),
)
.emit()),
ty::ClauseKind::ConstArgHasType(..) => {
// FIXME(min_specialization), FIXME(const_generics):
// It probably isn't right to allow _every_ `ConstArgHasType` but I am somewhat unsure
@ -483,12 +515,12 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, clause: ty::Clause<'tcx>, sp
// While we do not support constructs like `<T, const N: T>` there is probably no risk of
// soundness bugs, but when we support generic const parameter types this will need to be
// revisited.
Ok(())
}
_ => {
tcx.dcx()
.struct_span_err(span, format!("cannot specialize on predicate `{clause}`"))
.emit();
}
_ => Err(tcx
.dcx()
.struct_span_err(span, format!("cannot specialize on predicate `{clause}`"))
.emit()),
}
}

View file

@ -166,33 +166,29 @@ pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
tcx.hir().for_each_module(|module| tcx.ensure().collect_mod_item_types(module))
});
// FIXME(matthewjasper) We shouldn't need to use `track_errors` anywhere in this function
// or the compiler in general.
if tcx.features().rustc_attrs {
tcx.sess.track_errors(|| {
tcx.sess.time("outlives_testing", || outlives::test::test_inferred_outlives(tcx));
})?;
tcx.sess.time("outlives_testing", || outlives::test::test_inferred_outlives(tcx))?;
}
tcx.sess.track_errors(|| {
tcx.sess.time("coherence_checking", || {
// Check impls constrain their parameters
tcx.hir().for_each_module(|module| tcx.ensure().check_mod_impl_wf(module));
tcx.sess.time("coherence_checking", || {
// Check impls constrain their parameters
let res =
tcx.hir().try_par_for_each_module(|module| tcx.ensure().check_mod_impl_wf(module));
// FIXME(matthewjasper) We shouldn't need to use `track_errors` anywhere in this function
// or the compiler in general.
res.and(tcx.sess.track_errors(|| {
for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
tcx.ensure().coherent_trait(trait_def_id);
}
// these queries are executed for side-effects (error reporting):
tcx.ensure().crate_inherent_impls(());
tcx.ensure().crate_inherent_impls_overlap_check(());
});
}))
// these queries are executed for side-effects (error reporting):
.and(tcx.ensure().crate_inherent_impls(()))
.and(tcx.ensure().crate_inherent_impls_overlap_check(()))
})?;
if tcx.features().rustc_attrs {
tcx.sess.track_errors(|| {
tcx.sess.time("variance_testing", || variance::test::test_variance(tcx));
})?;
tcx.sess.time("variance_testing", || variance::test::test_variance(tcx))?;
}
tcx.sess.time("wf_checking", || {
@ -200,7 +196,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
})?;
if tcx.features().rustc_attrs {
tcx.sess.track_errors(|| collect::test_opaque_hidden_types(tcx))?;
collect::test_opaque_hidden_types(tcx)?;
}
// Freeze definitions as we don't add new ones at this point. This improves performance by

View file

@ -1,7 +1,8 @@
use rustc_middle::ty::{self, TyCtxt};
use rustc_span::symbol::sym;
use rustc_span::{symbol::sym, ErrorGuaranteed};
pub fn test_inferred_outlives(tcx: TyCtxt<'_>) {
pub fn test_inferred_outlives(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
let mut res = Ok(());
for id in tcx.hir().items() {
// For unit testing: check for a special "rustc_outlives"
// attribute and report an error with various results if found.
@ -22,7 +23,8 @@ pub fn test_inferred_outlives(tcx: TyCtxt<'_>) {
for p in pred {
err.note(p);
}
err.emit();
res = Err(err.emit());
}
}
res
}

View file

@ -2,19 +2,21 @@ use rustc_hir::def::DefKind;
use rustc_hir::def_id::CRATE_DEF_ID;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::sym;
use rustc_span::ErrorGuaranteed;
use crate::errors;
pub fn test_variance(tcx: TyCtxt<'_>) {
pub fn test_variance(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
let mut res = Ok(());
if tcx.has_attr(CRATE_DEF_ID, sym::rustc_variance_of_opaques) {
for id in tcx.hir().items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::OpaqueTy) {
let variances_of = tcx.variances_of(id.owner_id);
tcx.dcx().emit_err(errors::VariancesOf {
res = Err(tcx.dcx().emit_err(errors::VariancesOf {
span: tcx.def_span(id.owner_id),
variances_of: format!("{variances_of:?}"),
});
}));
}
}
}
@ -25,10 +27,11 @@ pub fn test_variance(tcx: TyCtxt<'_>) {
if tcx.has_attr(id.owner_id, sym::rustc_variance) {
let variances_of = tcx.variances_of(id.owner_id);
tcx.dcx().emit_err(errors::VariancesOf {
res = Err(tcx.dcx().emit_err(errors::VariancesOf {
span: tcx.def_span(id.owner_id),
variances_of: format!("{variances_of:?}"),
});
}));
}
}
res
}