From b7a5f3a41c6613033f0e6be9307c40e3174a9381 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 7 Mar 2023 05:40:55 +0000 Subject: [PATCH 01/11] Instantiate instead of erasing binder when probing param methods --- compiler/rustc_hir_typeck/src/method/probe.rs | 27 ++++++++++++------- .../non_lifetime_binders/method-probe.rs | 16 +++++++++++ .../non_lifetime_binders/method-probe.stderr | 11 ++++++++ 3 files changed, 45 insertions(+), 9 deletions(-) create mode 100644 tests/ui/traits/non_lifetime_binders/method-probe.rs create mode 100644 tests/ui/traits/non_lifetime_binders/method-probe.stderr diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 3bef5cfcd780e..2c8c9ed69d31c 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -792,6 +792,14 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // a `&self` method will wind up with an argument type like `&dyn Trait`. let trait_ref = principal.with_self_ty(self.tcx, self_ty); self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| { + if new_trait_ref.has_non_region_late_bound() { + this.tcx.sess.delay_span_bug( + this.span, + "tried to select method from HRTB with non-lifetime bound vars", + ); + return; + } + let new_trait_ref = this.erase_late_bound_regions(new_trait_ref); let (xform_self_ty, xform_ret_ty) = @@ -842,18 +850,15 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { }); self.elaborate_bounds(bounds, |this, poly_trait_ref, item| { - let trait_ref = this.erase_late_bound_regions(poly_trait_ref); + let trait_ref = this.instantiate_binder_with_fresh_vars( + this.span, + infer::LateBoundRegionConversionTime::FnCall, + poly_trait_ref, + ); let (xform_self_ty, xform_ret_ty) = this.xform_self_ty(item, trait_ref.self_ty(), trait_ref.substs); - // Because this trait derives from a where-clause, it - // should not contain any inference variables or other - // artifacts. This means it is safe to put into the - // `WhereClauseCandidate` and (eventually) into the - // `WhereClausePick`. - assert!(!trait_ref.substs.needs_infer()); - this.push_candidate( Candidate { xform_self_ty, @@ -963,7 +968,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { bound_trait_ref.def_id(), )); } else { - let new_trait_ref = self.erase_late_bound_regions(bound_trait_ref); + let new_trait_ref = self.instantiate_binder_with_fresh_vars( + self.span, + infer::LateBoundRegionConversionTime::FnCall, + bound_trait_ref, + ); let (xform_self_ty, xform_ret_ty) = self.xform_self_ty(item, new_trait_ref.self_ty(), new_trait_ref.substs); diff --git a/tests/ui/traits/non_lifetime_binders/method-probe.rs b/tests/ui/traits/non_lifetime_binders/method-probe.rs new file mode 100644 index 0000000000000..8df240c2082b7 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/method-probe.rs @@ -0,0 +1,16 @@ +// check-pass + +#![feature(non_lifetime_binders)] +//~^ WARN the feature `non_lifetime_binders` is incomplete + +trait Foo: for Bar {} + +trait Bar { + fn method() -> T; +} + +fn x() { + let _: i32 = T::method(); +} + +fn main() {} diff --git a/tests/ui/traits/non_lifetime_binders/method-probe.stderr b/tests/ui/traits/non_lifetime_binders/method-probe.stderr new file mode 100644 index 0000000000000..8f61792e6ce7f --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/method-probe.stderr @@ -0,0 +1,11 @@ +warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/method-probe.rs:3:12 + | +LL | #![feature(non_lifetime_binders)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #108185 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + From f7f2eb3e4171e4b87dbcab3a9a6709d5d084c54f Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Fri, 7 Apr 2023 19:45:17 +0100 Subject: [PATCH 02/11] Move `FnPtrAddr` error to `SessionDiagnostic` --- compiler/rustc_ty_utils/messages.ftl | 2 ++ compiler/rustc_ty_utils/src/errors.rs | 7 +++++++ compiler/rustc_ty_utils/src/instance.rs | 9 +++++---- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_ty_utils/messages.ftl b/compiler/rustc_ty_utils/messages.ftl index abe65a0e3fef0..e0aa27b73f626 100644 --- a/compiler/rustc_ty_utils/messages.ftl +++ b/compiler/rustc_ty_utils/messages.ftl @@ -45,3 +45,5 @@ ty_utils_control_flow_not_supported = control flow is not supported in generic c ty_utils_inline_asm_not_supported = assembly is not supported in generic constants ty_utils_operation_not_supported = unsupported operation in generic constants + +ty_utils_unexpected_fnptr_associated_item = `FnPtr` trait with unexpected associated item diff --git a/compiler/rustc_ty_utils/src/errors.rs b/compiler/rustc_ty_utils/src/errors.rs index ab3e62f048453..c05815d510ae3 100644 --- a/compiler/rustc_ty_utils/src/errors.rs +++ b/compiler/rustc_ty_utils/src/errors.rs @@ -67,3 +67,10 @@ pub enum GenericConstantTooComplexSub { #[label(ty_utils_operation_not_supported)] OperationNotSupported(#[primary_span] Span), } + +#[derive(Diagnostic)] +#[diag(ty_utils_unexpected_fnptr_associated_item)] +pub struct UnexpectedFnPtrAssociatedItem { + #[primary_span] + pub span: Span, +} diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index ad70154c98efa..0a6c118093e50 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -8,6 +8,8 @@ use rustc_span::sym; use rustc_trait_selection::traits; use traits::{translate_substs, Reveal}; +use crate::errors::UnexpectedFnPtrAssociatedItem; + fn resolve_instance<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>, @@ -282,10 +284,9 @@ fn resolve_associated_item<'tcx>( substs: rcvr_substs, }) } else { - tcx.sess.span_fatal( - tcx.def_span(trait_item_id), - "`FnPtrAddr` trait with unexpected assoc item", - ) + tcx.sess.emit_fatal(UnexpectedFnPtrAssociatedItem { + span: tcx.def_span(trait_item_id), + }) } } else { None From 066638b94ae1f19a059e813e54e6c3fb95efdcd2 Mon Sep 17 00:00:00 2001 From: Obei Sideg Date: Fri, 7 Apr 2023 02:04:42 +0300 Subject: [PATCH 03/11] Migrate `rustc_hir_analysis` to session diagnostic Part 3: Finishing `collect.rs` file --- compiler/rustc_hir_analysis/messages.ftl | 36 +++++ compiler/rustc_hir_analysis/src/collect.rs | 165 +++++++-------------- compiler/rustc_hir_analysis/src/errors.rs | 124 ++++++++++++++++ 3 files changed, 215 insertions(+), 110 deletions(-) diff --git a/compiler/rustc_hir_analysis/messages.ftl b/compiler/rustc_hir_analysis/messages.ftl index a57f398784916..1d7965ff5f66e 100644 --- a/compiler/rustc_hir_analysis/messages.ftl +++ b/compiler/rustc_hir_analysis/messages.ftl @@ -189,3 +189,39 @@ hir_analysis_return_type_notation_equality_bound = hir_analysis_return_type_notation_missing_method = cannot find associated function `{$assoc_name}` in trait `{$trait_name}` + +hir_analysis_placeholder_not_allowed_item_signatures = the placeholder `_` is not allowed within types on item signatures for {$kind} + .label = not allowed in type signatures + +hir_analysis_associated_type_trait_uninferred_generic_params = cannot use the associated type of a trait with uninferred generic parameters + .suggestion = use a fully qualified path with inferred lifetimes + +hir_analysis_associated_type_trait_uninferred_generic_params_multipart_suggestion = use a fully qualified path with explicit lifetimes + +hir_analysis_enum_discriminant_overflowed = enum discriminant overflowed + .label = overflowed on value after {$discr} + .note = explicitly set `{$item_name} = {$wrapped_discr}` if that is desired outcome + +hir_analysis_paren_sugar_attribute = the `#[rustc_paren_sugar]` attribute is a temporary means of controlling which traits can use parenthetical notation + .help = add `#![feature(unboxed_closures)]` to the crate attributes to use it + +hir_analysis_must_implement_one_of_attribute = the `#[rustc_must_implement_one_of]` attribute must be used with at least 2 args + +hir_analysis_must_be_name_of_associated_function = must be a name of an associated function + +hir_analysis_function_not_have_default_implementation = function doesn't have a default implementation + .note = required by this annotation + +hir_analysis_must_implement_not_function = not a function + +hir_analysis_must_implement_not_function_span_note = required by this annotation + +hir_analysis_must_implement_not_function_note = all `#[rustc_must_implement_one_of]` arguments must be associated function names + +hir_analysis_function_not_found_in_trait = function not found in this trait + +hir_analysis_functions_names_duplicated = functions names are duplicated + .note = all `#[rustc_must_implement_one_of]` arguments must be unique + +hir_analysis_simd_ffi_highly_experimental = use of SIMD type{$snip} in FFI is highly experimental and may result in invalid code + .help = add `#![feature(simd_ffi)]` to the crate attributes to enable diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index c41e96290df16..50862e3426238 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -20,7 +20,7 @@ use crate::errors; use hir::def::DefKind; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey}; +use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; @@ -333,17 +333,7 @@ fn bad_placeholder<'tcx>( let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) }; spans.sort(); - let mut err = struct_span_err!( - tcx.sess, - spans.clone(), - E0121, - "the placeholder `_` is not allowed within types on item signatures for {}", - kind - ); - for span in spans { - err.span_label(span, "not allowed in type signatures"); - } - err + tcx.sess.create_err(errors::PlaceholderNotAllowedItemSignatures { spans, kind }) } impl<'tcx> ItemCtxt<'tcx> { @@ -419,13 +409,8 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { self.tcx().mk_projection(item_def_id, item_substs) } else { // There are no late-bound regions; we can just ignore the binder. - let mut err = struct_span_err!( - self.tcx().sess, - span, - E0212, - "cannot use the associated type of a trait \ - with uninferred generic parameters" - ); + let (mut mpart_sugg, mut inferred_sugg) = (None, None); + let mut bound = String::new(); match self.node() { hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => { @@ -444,31 +429,25 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { (bound.span.shrink_to_lo(), format!("{}, ", lt_name)) } }; - let suggestions = vec![ - (lt_sp, sugg), - ( - span.with_hi(item_segment.ident.span.lo()), - format!( - "{}::", - // Replace the existing lifetimes with a new named lifetime. - self.tcx.replace_late_bound_regions_uncached( - poly_trait_ref, - |_| { - self.tcx.mk_re_early_bound(ty::EarlyBoundRegion { - def_id: item_def_id, - index: 0, - name: Symbol::intern(<_name), - }) - } - ), + mpart_sugg = Some(errors::AssociatedTypeTraitUninferredGenericParamsMultipartSuggestion { + fspan: lt_sp, + first: sugg, + sspan: span.with_hi(item_segment.ident.span.lo()), + second: format!( + "{}::", + // Replace the existing lifetimes with a new named lifetime. + self.tcx.replace_late_bound_regions_uncached( + poly_trait_ref, + |_| { + self.tcx.mk_re_early_bound(ty::EarlyBoundRegion { + def_id: item_def_id, + index: 0, + name: Symbol::intern(<_name), + }) + } ), ), - ]; - err.multipart_suggestion( - "use a fully qualified path with explicit lifetimes", - suggestions, - Applicability::MaybeIncorrect, - ); + }); } _ => {} } @@ -482,20 +461,23 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { | hir::Node::ForeignItem(_) | hir::Node::TraitItem(_) | hir::Node::ImplItem(_) => { - err.span_suggestion_verbose( - span.with_hi(item_segment.ident.span.lo()), - "use a fully qualified path with inferred lifetimes", - format!( - "{}::", - // Erase named lt, we want `::C`, not `::C`. - self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(), - ), - Applicability::MaybeIncorrect, + inferred_sugg = Some(span.with_hi(item_segment.ident.span.lo())); + bound = format!( + "{}::", + // Erase named lt, we want `::C`, not `::C`. + self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(), ); } _ => {} } - self.tcx().ty_error(err.emit()) + self.tcx().ty_error(self.tcx().sess.emit_err( + errors::AssociatedTypeTraitUninferredGenericParams { + span, + inferred_sugg, + bound, + mpart_sugg, + }, + )) } } @@ -763,14 +745,12 @@ fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) { Some(discr) } else { let span = tcx.def_span(variant.def_id); - struct_span_err!(tcx.sess, span, E0370, "enum discriminant overflowed") - .span_label(span, format!("overflowed on value after {}", prev_discr.unwrap())) - .note(&format!( - "explicitly set `{} = {}` if that is desired outcome", - tcx.item_name(variant.def_id), - wrapped_discr - )) - .emit(); + tcx.sess.emit_err(errors::EnumDiscriminantOverflowed { + span, + discr: prev_discr.unwrap().to_string(), + item_name: tcx.item_name(variant.def_id), + wrapped_discr: wrapped_discr.to_string(), + }); None } .unwrap_or(wrapped_discr), @@ -915,14 +895,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar); if paren_sugar && !tcx.features().unboxed_closures { - tcx.sess - .struct_span_err( - item.span, - "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \ - which traits can use parenthetical notation", - ) - .help("add `#![feature(unboxed_closures)]` to the crate attributes to use it") - .emit(); + tcx.sess.emit_err(errors::ParenSugarAttribute { span: item.span }); } let is_marker = tcx.has_attr(def_id, sym::marker); @@ -942,13 +915,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { // and that they are all identifiers .and_then(|attr| match attr.meta_item_list() { Some(items) if items.len() < 2 => { - tcx.sess - .struct_span_err( - attr.span, - "the `#[rustc_must_implement_one_of]` attribute must be \ - used with at least 2 args", - ) - .emit(); + tcx.sess.emit_err(errors::MustImplementOneOfAttribute { span: attr.span }); None } @@ -957,9 +924,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { .map(|item| item.ident().ok_or(item.span())) .collect::, _>>() .map_err(|span| { - tcx.sess - .struct_span_err(span, "must be a name of an associated function") - .emit(); + tcx.sess.emit_err(errors::MustBeNameOfAssociatedFunction { span }); }) .ok() .zip(Some(attr.span)), @@ -975,13 +940,10 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { match item { Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => { if !tcx.impl_defaultness(item.id.owner_id).has_value() { - tcx.sess - .struct_span_err( - item.span, - "function doesn't have a default implementation", - ) - .span_note(attr_span, "required by this annotation") - .emit(); + tcx.sess.emit_err(errors::FunctionNotHaveDefaultImplementation { + span: item.span, + note_span: attr_span, + }); return Some(()); } @@ -989,19 +951,14 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { return None; } Some(item) => { - tcx.sess - .struct_span_err(item.span, "not a function") - .span_note(attr_span, "required by this annotation") - .note( - "all `#[rustc_must_implement_one_of]` arguments must be associated \ - function names", - ) - .emit(); + tcx.sess.emit_err(errors::MustImplementNotFunction { + span: item.span, + span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span }, + note: errors::MustImplementNotFunctionNote {}, + }); } None => { - tcx.sess - .struct_span_err(ident.span, "function not found in this trait") - .emit(); + tcx.sess.emit_err(errors::FunctionNotFoundInTrait { span: ident.span }); } } @@ -1018,9 +975,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { for ident in &*list { if let Some(dup) = set.insert(ident.name, ident.span) { tcx.sess - .struct_span_err(vec![dup, ident.span], "functions names are duplicated") - .note("all `#[rustc_must_implement_one_of]` arguments must be unique") - .emit(); + .emit_err(errors::FunctionNamesDuplicated { spans: vec![dup, ident.span] }); no_dups = false; } @@ -1485,17 +1440,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( .source_map() .span_to_snippet(ast_ty.span) .map_or_else(|_| String::new(), |s| format!(" `{}`", s)); - tcx.sess - .struct_span_err( - ast_ty.span, - &format!( - "use of SIMD type{} in FFI is highly experimental and \ - may result in invalid code", - snip - ), - ) - .help("add `#![feature(simd_ffi)]` to the crate attributes to enable") - .emit(); + tcx.sess.emit_err(errors::SIMDFFIHighlyExperimental { span: ast_ty.span, snip }); } }; for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) { diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/errors.rs index c71ce9a0bc7cd..2a3a683489ddd 100644 --- a/compiler/rustc_hir_analysis/src/errors.rs +++ b/compiler/rustc_hir_analysis/src/errors.rs @@ -507,3 +507,127 @@ pub(crate) struct ReturnTypeNotationMissingMethod { pub trait_name: Symbol, pub assoc_name: Symbol, } + +#[derive(Diagnostic)] +#[diag(hir_analysis_placeholder_not_allowed_item_signatures, code = "E0121")] +pub(crate) struct PlaceholderNotAllowedItemSignatures { + #[primary_span] + #[label] + pub spans: Vec, + pub kind: String, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_associated_type_trait_uninferred_generic_params, code = "E0212")] +pub(crate) struct AssociatedTypeTraitUninferredGenericParams { + #[primary_span] + pub span: Span, + #[suggestion(style = "verbose", applicability = "maybe-incorrect", code = "{bound}")] + pub inferred_sugg: Option, + pub bound: String, + #[subdiagnostic] + pub mpart_sugg: Option, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion( + hir_analysis_associated_type_trait_uninferred_generic_params_multipart_suggestion, + applicability = "maybe-incorrect" +)] +pub(crate) struct AssociatedTypeTraitUninferredGenericParamsMultipartSuggestion { + #[suggestion_part(code = "{first}")] + pub fspan: Span, + pub first: String, + #[suggestion_part(code = "{second}")] + pub sspan: Span, + pub second: String, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_enum_discriminant_overflowed, code = "E0370")] +#[note] +pub(crate) struct EnumDiscriminantOverflowed { + #[primary_span] + #[label] + pub span: Span, + pub discr: String, + pub item_name: Symbol, + pub wrapped_discr: String, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_paren_sugar_attribute)] +#[help] +pub(crate) struct ParenSugarAttribute { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_must_implement_one_of_attribute)] +pub(crate) struct MustImplementOneOfAttribute { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_must_be_name_of_associated_function)] +pub(crate) struct MustBeNameOfAssociatedFunction { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_function_not_have_default_implementation)] +pub(crate) struct FunctionNotHaveDefaultImplementation { + #[primary_span] + pub span: Span, + #[note] + pub note_span: Span, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_must_implement_not_function)] +pub(crate) struct MustImplementNotFunction { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub span_note: MustImplementNotFunctionSpanNote, + #[subdiagnostic] + pub note: MustImplementNotFunctionNote, +} + +#[derive(Subdiagnostic)] +#[note(hir_analysis_must_implement_not_function_span_note)] +pub(crate) struct MustImplementNotFunctionSpanNote { + #[primary_span] + pub span: Span, +} + +#[derive(Subdiagnostic)] +#[note(hir_analysis_must_implement_not_function_note)] +pub(crate) struct MustImplementNotFunctionNote {} + +#[derive(Diagnostic)] +#[diag(hir_analysis_function_not_found_in_trait)] +pub(crate) struct FunctionNotFoundInTrait { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_functions_names_duplicated)] +#[note] +pub(crate) struct FunctionNamesDuplicated { + #[primary_span] + pub spans: Vec, +} + +#[derive(Diagnostic)] +#[diag(hir_analysis_simd_ffi_highly_experimental)] +#[help] +pub(crate) struct SIMDFFIHighlyExperimental { + #[primary_span] + pub span: Span, + pub snip: String, +} From 804e93871dfc879380fdd3bcde6c6958466814af Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Sat, 8 Apr 2023 20:01:14 +0100 Subject: [PATCH 04/11] Move SIMD layout errors to `SessionDiagnostic` --- compiler/rustc_ty_utils/messages.ftl | 8 ++++++ compiler/rustc_ty_utils/src/errors.rs | 26 ++++++++++++++++++ compiler/rustc_ty_utils/src/layout.rs | 39 +++++++++++++-------------- compiler/rustc_ty_utils/src/lib.rs | 2 ++ 4 files changed, 55 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_ty_utils/messages.ftl b/compiler/rustc_ty_utils/messages.ftl index e0aa27b73f626..a1e97bb95bc69 100644 --- a/compiler/rustc_ty_utils/messages.ftl +++ b/compiler/rustc_ty_utils/messages.ftl @@ -47,3 +47,11 @@ ty_utils_inline_asm_not_supported = assembly is not supported in generic constan ty_utils_operation_not_supported = unsupported operation in generic constants ty_utils_unexpected_fnptr_associated_item = `FnPtr` trait with unexpected associated item + +ty_utils_zero_length_simd_type = monomorphising SIMD type `{$ty}` of zero length + +ty_utils_multiple_array_fields_simd_type = monomorphising SIMD type `{$ty}` with more than one array field + +ty_utils_oversized_simd_type = monomorphising SIMD type `{$ty}` of length greater than {$max_lanes} + +ty_utils_non_primative_simd_type = monomorphising SIMD type `{$ty}` with a non-primitive-scalar (integer/float/pointer) element type `{$e_ty}` diff --git a/compiler/rustc_ty_utils/src/errors.rs b/compiler/rustc_ty_utils/src/errors.rs index c05815d510ae3..3db3c98e9e28e 100644 --- a/compiler/rustc_ty_utils/src/errors.rs +++ b/compiler/rustc_ty_utils/src/errors.rs @@ -74,3 +74,29 @@ pub struct UnexpectedFnPtrAssociatedItem { #[primary_span] pub span: Span, } + +#[derive(Diagnostic)] +#[diag(ty_utils_zero_length_simd_type)] +pub struct ZeroLengthSimdType<'tcx> { + pub ty: Ty<'tcx>, +} + +#[derive(Diagnostic)] +#[diag(ty_utils_multiple_array_fields_simd_type)] +pub struct MultipleArrayFieldsSimdType<'tcx> { + pub ty: Ty<'tcx>, +} + +#[derive(Diagnostic)] +#[diag(ty_utils_oversized_simd_type)] +pub struct OversizedSimdType<'tcx> { + pub ty: Ty<'tcx>, + pub max_lanes: u64, +} + +#[derive(Diagnostic)] +#[diag(ty_utils_non_primative_simd_type)] +pub struct NonPrimitiveSimdType<'tcx> { + pub ty: Ty<'tcx>, + pub e_ty: Ty<'tcx>, +} diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index d4420ec88db95..d08877233b3f9 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -17,6 +17,9 @@ use rustc_target::abi::*; use std::fmt::Debug; use std::iter; +use crate::errors::{ + MultipleArrayFieldsSimdType, NonPrimitiveSimdType, OversizedSimdType, ZeroLengthSimdType, +}; use crate::layout_sanity_check::sanity_check_layout; pub fn provide(providers: &mut ty::query::Providers) { @@ -294,6 +297,8 @@ fn layout_of_uncached<'tcx>( return Err(LayoutError::Unknown(ty)); } + let fields = &def.non_enum_variant().fields; + // Supported SIMD vectors are homogeneous ADTs with at least one field: // // * #[repr(simd)] struct S(T, T, T, T); @@ -304,18 +309,22 @@ fn layout_of_uncached<'tcx>( // SIMD vectors with zero fields are not supported. // (should be caught by typeck) - if def.non_enum_variant().fields.is_empty() { - tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty)); + if fields.is_empty() { + tcx.sess.emit_fatal(ZeroLengthSimdType { ty }) } // Type of the first ADT field: - let f0_ty = def.non_enum_variant().fields[FieldIdx::from_u32(0)].ty(tcx, substs); + let f0_ty = fields[FieldIdx::from_u32(0)].ty(tcx, substs); // Heterogeneous SIMD vectors are not supported: // (should be caught by typeck) - for fi in &def.non_enum_variant().fields { + for fi in fields { if fi.ty(tcx, substs) != f0_ty { - tcx.sess.fatal(&format!("monomorphising heterogeneous SIMD type `{}`", ty)); + tcx.sess.delay_span_bug( + DUMMY_SP, + "#[repr(simd)] was applied to an ADT with hetrogeneous field type", + ); + return Err(LayoutError::Unknown(ty)); } } @@ -330,12 +339,9 @@ fn layout_of_uncached<'tcx>( // First ADT field is an array: // SIMD vectors with multiple array fields are not supported: - // (should be caught by typeck) + // Can't be caught by typeck with a generic simd type. if def.non_enum_variant().fields.len() != 1 { - tcx.sess.fatal(&format!( - "monomorphising SIMD type `{}` with more than one array field", - ty - )); + tcx.sess.emit_fatal(MultipleArrayFieldsSimdType { ty }); } // Extract the number of elements from the layout of the array field: @@ -355,12 +361,9 @@ fn layout_of_uncached<'tcx>( // // Can't be caught in typeck if the array length is generic. if e_len == 0 { - tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty)); + tcx.sess.emit_fatal(ZeroLengthSimdType { ty }); } else if e_len > MAX_SIMD_LANES { - tcx.sess.fatal(&format!( - "monomorphising SIMD type `{}` of length greater than {}", - ty, MAX_SIMD_LANES, - )); + tcx.sess.emit_fatal(OversizedSimdType { ty, max_lanes: MAX_SIMD_LANES }); } // Compute the ABI of the element type: @@ -368,11 +371,7 @@ fn layout_of_uncached<'tcx>( let Abi::Scalar(e_abi) = e_ly.abi else { // This error isn't caught in typeck, e.g., if // the element type of the vector is generic. - tcx.sess.fatal(&format!( - "monomorphising SIMD type `{}` with a non-primitive-scalar \ - (integer/float/pointer) element type `{}`", - ty, e_ty - )) + tcx.sess.emit_fatal(NonPrimitiveSimdType {ty, e_ty }); }; // Compute the size and alignment of the vector: diff --git a/compiler/rustc_ty_utils/src/lib.rs b/compiler/rustc_ty_utils/src/lib.rs index 9195964a2f366..2613445f39bec 100644 --- a/compiler/rustc_ty_utils/src/lib.rs +++ b/compiler/rustc_ty_utils/src/lib.rs @@ -10,6 +10,8 @@ #![feature(never_type)] #![feature(box_patterns)] #![recursion_limit = "256"] +#![deny(rustc::untranslatable_diagnostic)] +#![deny(rustc::diagnostic_outside_of_impl)] #[macro_use] extern crate rustc_middle; From 8e76c7614917d687d49bdb0484473cb7b88d7fe2 Mon Sep 17 00:00:00 2001 From: matthewjasper <20113453+matthewjasper@users.noreply.github.com> Date: Sat, 8 Apr 2023 21:40:33 +0100 Subject: [PATCH 05/11] Update compiler/rustc_ty_utils/src/layout.rs Fix formatting that rustfmt can't handle currently. Co-authored-by: Michael Goulet --- compiler/rustc_ty_utils/src/layout.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index d08877233b3f9..63eb34f7d5529 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -371,7 +371,7 @@ fn layout_of_uncached<'tcx>( let Abi::Scalar(e_abi) = e_ly.abi else { // This error isn't caught in typeck, e.g., if // the element type of the vector is generic. - tcx.sess.emit_fatal(NonPrimitiveSimdType {ty, e_ty }); + tcx.sess.emit_fatal(NonPrimitiveSimdType { ty, e_ty }); }; // Compute the size and alignment of the vector: From c17a7057580fcd76caec41939f1c4d5534ff790e Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Sat, 8 Apr 2023 22:14:57 +0100 Subject: [PATCH 06/11] Add test for new delayed bug code path --- tests/ui/simd/monomorphize-heterogeneous.rs | 9 +++++++++ tests/ui/simd/monomorphize-heterogeneous.stderr | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 tests/ui/simd/monomorphize-heterogeneous.rs create mode 100644 tests/ui/simd/monomorphize-heterogeneous.stderr diff --git a/tests/ui/simd/monomorphize-heterogeneous.rs b/tests/ui/simd/monomorphize-heterogeneous.rs new file mode 100644 index 0000000000000..42e380dbb779b --- /dev/null +++ b/tests/ui/simd/monomorphize-heterogeneous.rs @@ -0,0 +1,9 @@ +#![feature(repr_simd)] + +#[repr(simd)] +struct I64F64(i64, f64); +//~^ ERROR SIMD vector should be homogeneous + +static X: I64F64 = I64F64(1, 2.0); + +fn main() {} diff --git a/tests/ui/simd/monomorphize-heterogeneous.stderr b/tests/ui/simd/monomorphize-heterogeneous.stderr new file mode 100644 index 0000000000000..e7b41cd787cd2 --- /dev/null +++ b/tests/ui/simd/monomorphize-heterogeneous.stderr @@ -0,0 +1,9 @@ +error[E0076]: SIMD vector should be homogeneous + --> $DIR/monomorphize-heterogeneous.rs:4:1 + | +LL | struct I64F64(i64, f64); + | ^^^^^^^^^^^^^ SIMD elements must have the same type + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0076`. From 5c75dcdefa8b6e239560bad3cfe5af9f036308a5 Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Sun, 9 Apr 2023 12:31:13 +0200 Subject: [PATCH 07/11] Add renaming of ignore-git to changelog --- src/bootstrap/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bootstrap/CHANGELOG.md b/src/bootstrap/CHANGELOG.md index 654e03d0c3c7f..fe6d450e3eb3b 100644 --- a/src/bootstrap/CHANGELOG.md +++ b/src/bootstrap/CHANGELOG.md @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - `remote-test-server`'s `remote` argument has been removed in favor of the `--bind` flag. Use `--bind 0.0.0.0:12345` to replicate the behavior of the `remote` argument. - `x.py fmt` now formats only files modified between the merge-base of HEAD and the last commit in the master branch of the rust-lang repository and the current working directory. To restore old behaviour, use `x.py fmt .`. The check mode is not affected by this change. [#105702](https://github.com/rust-lang/rust/pull/105702) - The `llvm.version-check` config option has been removed. Older versions were never supported. If you still need to support older versions (e.g. you are applying custom patches), patch `check_llvm_version` in bootstrap to change the minimum version. [#108619](https://github.com/rust-lang/rust/pull/108619) +- The `rust.ignore-git` option has been renamed to `rust.omit-git-hash`. ### Non-breaking changes From 3fcc007f96c625c3a6d326030fca5d5fb7f8abf2 Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Sun, 9 Apr 2023 12:36:15 +0200 Subject: [PATCH 08/11] Add PR link to changelog entry for renaming of ignore-git --- src/bootstrap/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/CHANGELOG.md b/src/bootstrap/CHANGELOG.md index fe6d450e3eb3b..74dd22df9e062 100644 --- a/src/bootstrap/CHANGELOG.md +++ b/src/bootstrap/CHANGELOG.md @@ -17,7 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - `remote-test-server`'s `remote` argument has been removed in favor of the `--bind` flag. Use `--bind 0.0.0.0:12345` to replicate the behavior of the `remote` argument. - `x.py fmt` now formats only files modified between the merge-base of HEAD and the last commit in the master branch of the rust-lang repository and the current working directory. To restore old behaviour, use `x.py fmt .`. The check mode is not affected by this change. [#105702](https://github.com/rust-lang/rust/pull/105702) - The `llvm.version-check` config option has been removed. Older versions were never supported. If you still need to support older versions (e.g. you are applying custom patches), patch `check_llvm_version` in bootstrap to change the minimum version. [#108619](https://github.com/rust-lang/rust/pull/108619) -- The `rust.ignore-git` option has been renamed to `rust.omit-git-hash`. +- The `rust.ignore-git` option has been renamed to `rust.omit-git-hash`. [#110059](https://github.com/rust-lang/rust/pull/110059) ### Non-breaking changes From 28e19f19aaa9388814fb0cc358e18258127397f3 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Wed, 5 Apr 2023 23:36:40 +0200 Subject: [PATCH 09/11] Add little `is_test_crate` function --- compiler/rustc_session/src/session.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 5730df9d5c6b9..340bb158e1791 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -294,6 +294,11 @@ impl Session { self.crate_types.get().unwrap().as_slice() } + /// Returns true if the crate is a testing one. + pub fn is_test_crate(&self) -> bool { + self.opts.test + } + pub fn needs_crate_hash(&self) -> bool { // Why is the crate hash needed for these configurations? // - debug_assertions: for the "fingerprint the result" check in From 7ca7c8fbf322171af8247509256c833b862f4618 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 9 Apr 2023 12:36:30 -0500 Subject: [PATCH 10/11] compiletest: Give a better error message if `node` isn't installed --- src/tools/compiletest/src/runtest.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index a35284f05b540..1a4b2bdb4e187 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2135,7 +2135,7 @@ impl<'test> TestCx<'test> { if let Some(ref p) = self.config.nodejs { args.push(p.clone()); } else { - self.fatal("no NodeJS binary found (--nodejs)"); + self.fatal("emscripten target requested and no NodeJS binary found (--nodejs)"); } // If this is otherwise wasm, then run tests under nodejs with our // shim @@ -2143,7 +2143,7 @@ impl<'test> TestCx<'test> { if let Some(ref p) = self.config.nodejs { args.push(p.clone()); } else { - self.fatal("no NodeJS binary found (--nodejs)"); + self.fatal("wasm32 target requested and no NodeJS binary found (--nodejs)"); } let src = self From 2c976765b8e426506285b334e0a1506c78b135e2 Mon Sep 17 00:00:00 2001 From: blyxyas Date: Sun, 9 Apr 2023 21:37:31 +0200 Subject: [PATCH 11/11] Migrate `sess.opts.tests` uses to `sess.is_test_crate()` --- compiler/rustc_builtin_macros/src/test_harness.rs | 2 +- compiler/rustc_codegen_ssa/src/back/link.rs | 2 +- compiler/rustc_interface/src/passes.rs | 4 ++-- compiler/rustc_passes/src/stability.rs | 2 +- compiler/rustc_resolve/src/check_unused.rs | 2 +- compiler/rustc_session/src/config.rs | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 43ab6c0442833..80f497333a632 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -53,7 +53,7 @@ pub fn inject(krate: &mut ast::Crate, sess: &Session, resolver: &mut dyn Resolve // even in non-test builds let test_runner = get_test_runner(span_diagnostic, &krate); - if sess.opts.test { + if sess.is_test_crate() { let panic_strategy = match (panic_strategy, sess.opts.unstable_opts.panic_abort_tests) { (PanicStrategy::Abort, true) => PanicStrategy::Abort, (PanicStrategy::Abort, false) => { diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 6a0d0ca55c255..7a5fa5a370cb9 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -2301,7 +2301,7 @@ fn add_native_libs_from_crate( || (whole_archive == None && bundle && cnum == LOCAL_CRATE - && sess.opts.test); + && sess.is_test_crate()); if bundle && cnum != LOCAL_CRATE { if let Some(filename) = lib.filename { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 8d4892470ac7b..0e4e20c7cd1d4 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -230,7 +230,7 @@ fn configure_and_expand( features: Some(features), recursion_limit, trace_mac: sess.opts.unstable_opts.trace_macros, - should_test: sess.opts.test, + should_test: sess.is_test_crate(), span_debug: sess.opts.unstable_opts.span_debug, proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace, ..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string()) @@ -292,7 +292,7 @@ fn configure_and_expand( } sess.time("maybe_create_a_macro_crate", || { - let is_test_crate = sess.opts.test; + let is_test_crate = sess.is_test_crate(); rustc_builtin_macros::proc_macro_harness::inject( &mut krate, sess, diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 4a1ba19c92064..4a35c6794663e 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -530,7 +530,7 @@ struct MissingStabilityAnnotations<'tcx> { impl<'tcx> MissingStabilityAnnotations<'tcx> { fn check_missing_stability(&self, def_id: LocalDefId, span: Span) { let stab = self.tcx.stability().local_stability(def_id); - if !self.tcx.sess.opts.test + if !self.tcx.sess.is_test_crate() && stab.is_none() && self.effective_visibilities.is_reachable(def_id) { diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs index dbf6cec788b5a..ae3fd0ede6cff 100644 --- a/compiler/rustc_resolve/src/check_unused.rs +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -393,7 +393,7 @@ impl Resolver<'_, '_> { // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]` // attribute; however, if not, suggest adding the attribute. There is no way to // retrieve attributes here because we do not have a `TyCtxt` yet. - let test_module_span = if tcx.sess.opts.test { + let test_module_span = if tcx.sess.is_test_crate() { None } else { let parent_module = visitor.r.get_nearest_non_block_module( diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index de0ddb53fa402..613abaa8e3cd1 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1258,7 +1258,7 @@ pub fn build_configuration(sess: &Session, mut user_cfg: CrateConfig) -> CrateCo // some default and generated configuration items. let default_cfg = default_configuration(sess); // If the user wants a test runner, then add the test cfg. - if sess.opts.test { + if sess.is_test_crate() { user_cfg.insert((sym::test, None)); } user_cfg.extend(default_cfg.iter().cloned());