]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #103171 - jackh726:gen-interior-hrtb-error, r=cjgillot
authorbors <bors@rust-lang.org>
Wed, 9 Nov 2022 02:02:28 +0000 (02:02 +0000)
committerbors <bors@rust-lang.org>
Wed, 9 Nov 2022 02:02:28 +0000 (02:02 +0000)
Better error for HRTB error from generator interior

cc #100013

This is just a first pass at an error. It could be better, and shouldn't really be emitted in the first place. But this is better than what was being emitted before.

1  2 
compiler/rustc_hir_analysis/src/astconv/mod.rs
compiler/rustc_hir_typeck/src/lib.rs
compiler/rustc_infer/src/infer/error_reporting/mod.rs
compiler/rustc_trait_selection/src/traits/select/mod.rs

index 2665813478c2c4649b108dbd119d2c8606cf338a,0e3d318dc4ca9538592cd55d50962f048f89c3e7..4518cf30acdd5fda428c2fa7d3ef6e9f26bacb84
@@@ -1201,8 -1201,7 +1201,8 @@@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o 
                      (_, _) => {
                          let got = if let Some(_) = term.ty() { "type" } else { "constant" };
                          let expected = def_kind.descr(assoc_item_def_id);
 -                        tcx.sess
 +                        let reported = tcx
 +                            .sess
                              .struct_span_err(
                                  binding.span,
                                  &format!("expected {expected} bound, found {got}"),
                              )
                              .emit();
                          term = match def_kind {
 -                            hir::def::DefKind::AssocTy => tcx.ty_error().into(),
 +                            hir::def::DefKind::AssocTy => {
 +                                tcx.ty_error_with_guaranteed(reported).into()
 +                            }
                              hir::def::DefKind::AssocConst => tcx
 -                                .const_error(
 +                                .const_error_with_guaranteed(
                                      tcx.bound_type_of(assoc_item_def_id)
                                          .subst(tcx, projection_ty.skip_binder().substs),
 +                                    reported,
                                  )
                                  .into(),
                              _ => unreachable!(),
                  .map(|&(trait_ref, _, _)| trait_ref.def_id())
                  .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
                  .map(|trait_ref| tcx.def_span(trait_ref));
 -            tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
 -            return tcx.ty_error();
 +            let reported =
 +                tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
 +            return tcx.ty_error_with_guaranteed(reported);
          }
  
          // Check that there are no gross object safety violations;
              let object_safety_violations =
                  astconv_object_safety_violations(tcx, item.trait_ref().def_id());
              if !object_safety_violations.is_empty() {
 -                report_object_safety_error(
 +                let reported = report_object_safety_error(
                      tcx,
                      span,
                      item.trait_ref().def_id(),
                      &object_safety_violations,
                  )
                  .emit();
 -                return tcx.ty_error();
 +                return tcx.ty_error_with_guaranteed(reported);
              }
          }
  
                  "Type"
              };
  
 -            self.report_ambiguous_associated_type(
 +            let reported = self.report_ambiguous_associated_type(
                  span,
                  type_name,
                  &path_str,
                  item_segment.ident.name,
              );
 -            return tcx.ty_error();
 +            return tcx.ty_error_with_guaranteed(reported)
          };
  
          debug!("qpath_to_ty: self_type={:?}", self_ty);
                      {
                          err.span_note(impl_.self_ty.span, "not a concrete type");
                      }
 -                    err.emit();
 -                    tcx.ty_error()
 +                    tcx.ty_error_with_guaranteed(err.emit())
                  } else {
                      self.normalize_ty(span, ty)
                  }
      ) {
          for br in referenced_regions.difference(&constrained_regions) {
              let br_name = match *br {
-                 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) | ty::BrEnv => {
+                 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
                      "an anonymous lifetime".to_string()
                  }
                  ty::BrNamed(_, name) => format!("lifetime `{}`", name),
  
              let mut err = generate_err(&br_name);
  
-             if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) = *br {
+             if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) = *br {
                  // The only way for an anonymous lifetime to wind up
                  // in the return type but **also** be unconstrained is
                  // if it only appears in "associated types" in the
index 052fdef2fc51824a5c450e78a89337fb719361d6,93c58475cfc7c4edfb0e8991916a3df34991b848..183e80f2e0840b610f47765a0972b3ab2d6f0e5f
@@@ -209,6 -209,7 +209,7 @@@ fn diagnostic_only_typeck<'tcx>(tcx: Ty
      typeck_with_fallback(tcx, def_id, fallback)
  }
  
+ #[instrument(level = "debug", skip(tcx, fallback), ret)]
  fn typeck_with_fallback<'tcx>(
      tcx: TyCtxt<'tcx>,
      def_id: LocalDefId,
              fcx
          };
  
 -        let fallback_has_occurred = fcx.type_inference_fallback();
 +        fcx.type_inference_fallback();
  
          // Even though coercion casts provide type hints, we check casts after fallback for
          // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
          fcx.check_casts();
 -        fcx.select_obligations_where_possible(fallback_has_occurred, |_| {});
 +        fcx.select_obligations_where_possible(|_| {});
  
          // Closure and generator analysis may run after fallback
          // because they don't constrain other type variables.
@@@ -458,7 -459,7 +459,7 @@@ fn report_unexpected_variant_res(tcx: T
  /// # fn f(x: (isize, isize)) {}
  /// f((1, 2));
  /// ```
 -#[derive(Clone, Eq, PartialEq)]
 +#[derive(Copy, Clone, Eq, PartialEq)]
  enum TupleArgumentsFlag {
      DontTupleArguments,
      TupleArguments,
index 3dbc9b9f3f938fcc2c4262de81da3132e874196d,8a509cb8287a41b65f4368ea2d6da29565e09c00..61519454a2cf5d1942af8572c2c448323e24181c
@@@ -58,7 -58,7 +58,7 @@@ use crate::traits::
      StatementAsExpression,
  };
  
 -use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
  use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed, IntoDiagnosticArg};
  use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
  use rustc_hir as hir;
@@@ -91,7 -91,6 +91,7 @@@ pub mod nice_region_error
  pub struct TypeErrCtxt<'a, 'tcx> {
      pub infcx: &'a InferCtxt<'tcx>,
      pub typeck_results: Option<std::cell::Ref<'a, ty::TypeckResults<'tcx>>>,
 +    pub fallback_has_occurred: bool,
  }
  
  impl TypeErrCtxt<'_, '_> {
@@@ -207,9 -206,12 +207,12 @@@ fn msg_span_from_early_bound_and_free_r
                          };
                          (text, sp)
                      }
-                     ty::BrAnon(idx) => (
+                     ty::BrAnon(idx, span) => (
                          format!("the anonymous lifetime #{} defined here", idx + 1),
-                         tcx.def_span(scope)
+                         match span {
+                             Some(span) => span,
+                             None => tcx.def_span(scope)
+                         }
                      ),
                      _ => (
                          format!("the lifetime `{}` as defined here", region),
@@@ -1499,9 -1501,9 +1502,9 @@@ impl<'tcx> TypeErrCtxt<'_, 'tcx> 
              values = None;
          }
          struct OpaqueTypesVisitor<'tcx> {
 -            types: FxHashMap<TyCategory, FxHashSet<Span>>,
 -            expected: FxHashMap<TyCategory, FxHashSet<Span>>,
 -            found: FxHashMap<TyCategory, FxHashSet<Span>>,
 +            types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
 +            expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
 +            found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
              ignore_span: Span,
              tcx: TyCtxt<'tcx>,
          }
                  &self,
                  err: &mut Diagnostic,
                  target: &str,
 -                types: &FxHashMap<TyCategory, FxHashSet<Span>>,
 +                types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
              ) {
                  for (key, values) in types.iter() {
                      let count = values.len();
@@@ -3255,7 -3257,7 +3258,7 @@@ impl<'tcx> TypeErrCtxt<'_, 'tcx> 
          if blk.expr.is_some() {
              return false;
          }
 -        let mut shadowed = FxHashSet::default();
 +        let mut shadowed = FxIndexSet::default();
          let mut candidate_idents = vec![];
          let mut find_compatible_candidates = |pat: &hir::Pat<'_>| {
              if let hir::PatKind::Binding(_, hir_id, ident, _) = &pat.kind
index 2954a2c163f4072c52e5d17c70f6b429309f27cc,debf06593459fd980f52b61513e92359d46c3dab..c6ff83120a73629bac1391c09d8856e3ee4104ad
@@@ -294,6 -294,9 +294,6 @@@ impl<'cx, 'tcx> SelectionContext<'cx, '
                  assert!(self.query_mode == TraitQueryMode::Canonical);
                  return Err(SelectionError::Overflow(OverflowError::Canonical));
              }
 -            Err(SelectionError::Ambiguous(_)) => {
 -                return Ok(None);
 -            }
              Err(e) => {
                  return Err(e);
              }
  
          match self.candidate_from_obligation(stack) {
              Ok(Some(c)) => self.evaluate_candidate(stack, &c),
 -            Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
              Ok(None) => Ok(EvaluatedToAmbig),
              Err(Overflow(OverflowError::Canonical)) => Err(OverflowError::Canonical),
              Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
      /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
      /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
      /// ```
+     #[instrument(level = "debug", skip(self), ret)]
      fn constituent_types_for_ty(
          &self,
          t: ty::Binder<'tcx, Ty<'tcx>>,