1 // ignore-tidy-filelength FIXME(#67418) Split up this file.
2 //! Conversion from AST representation of types to the `ty.rs` representation.
3 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
4 //! instance of `AstConv`.
6 // ignore-tidy-filelength
8 use crate::collect::PlaceholderHirTyCollector;
9 use crate::middle::resolve_lifetime as rl;
10 use crate::require_c_abi_if_c_variadic;
11 use rustc_ast::{ast::ParamKindOrd, util::lev_distance::find_best_match_for_name};
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_errors::ErrorReported;
14 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError};
16 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_hir::intravisit::{walk_generics, Visitor as _};
19 use rustc_hir::lang_items::SizedTraitLangItem;
20 use rustc_hir::{Constness, GenericArg, GenericArgs};
21 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
22 use rustc_middle::ty::{
23 self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
25 use rustc_middle::ty::{GenericParamDef, GenericParamDefKind};
26 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS};
27 use rustc_session::parse::feature_err;
28 use rustc_session::Session;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::{MultiSpan, Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use rustc_trait_selection::traits;
33 use rustc_trait_selection::traits::astconv_object_safety_violations;
34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
35 use rustc_trait_selection::traits::wf::object_region_bounds;
37 use smallvec::SmallVec;
38 use std::collections::BTreeSet;
43 pub struct PathSeg(pub DefId, pub usize);
45 pub trait AstConv<'tcx> {
46 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
48 fn item_def_id(&self) -> Option<DefId>;
50 fn default_constness_for_trait_bounds(&self) -> Constness;
52 /// Returns predicates in scope of the form `X: Foo`, where `X` is
53 /// a type parameter `X` with the given id `def_id`. This is a
54 /// subset of the full set of predicates.
56 /// This is used for one specific purpose: resolving "short-hand"
57 /// associated type references like `T::Item`. In principle, we
58 /// would do that by first getting the full set of predicates in
59 /// scope and then filtering down to find those that apply to `T`,
60 /// but this can lead to cycle errors. The problem is that we have
61 /// to do this resolution *in order to create the predicates in
62 /// the first place*. Hence, we have this "special pass".
63 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
65 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
66 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
67 -> Option<ty::Region<'tcx>>;
69 /// Returns the type to use when a type is omitted.
70 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
72 /// Returns `true` if `_` is allowed in type signatures in the current context.
73 fn allow_ty_infer(&self) -> bool;
75 /// Returns the const to use when a const is omitted.
79 param: Option<&ty::GenericParamDef>,
81 ) -> &'tcx Const<'tcx>;
83 /// Projecting an associated type from a (potentially)
84 /// higher-ranked trait reference is more complicated, because of
85 /// the possibility of late-bound regions appearing in the
86 /// associated type binding. This is not legal in function
87 /// signatures for that reason. In a function body, we can always
88 /// handle it because we can use inference variables to remove the
89 /// late-bound regions.
90 fn projected_ty_from_poly_trait_ref(
94 item_segment: &hir::PathSegment<'_>,
95 poly_trait_ref: ty::PolyTraitRef<'tcx>,
98 /// Normalize an associated type coming from the user.
99 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
101 /// Invoked when we encounter an error from some prior pass
102 /// (e.g., resolve) that is translated into a ty-error. This is
103 /// used to help suppress derived errors typeck might otherwise
105 fn set_tainted_by_errors(&self);
107 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
110 pub enum SizedByDefault {
115 struct ConvertedBinding<'a, 'tcx> {
117 kind: ConvertedBindingKind<'a, 'tcx>,
121 enum ConvertedBindingKind<'a, 'tcx> {
123 Constraint(&'a [hir::GenericBound<'a>]),
126 /// New-typed boolean indicating whether explicit late-bound lifetimes
127 /// are present in a set of generic arguments.
129 /// For example if we have some method `fn f<'a>(&'a self)` implemented
130 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
131 /// is late-bound so should not be provided explicitly. Thus, if `f` is
132 /// instantiated with some generic arguments providing `'a` explicitly,
133 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
134 /// can provide an appropriate diagnostic later.
135 #[derive(Copy, Clone, PartialEq)]
136 pub enum ExplicitLateBound {
141 #[derive(Copy, Clone, PartialEq)]
142 enum GenericArgPosition {
144 Value, // e.g., functions
148 /// A marker denoting that the generic arguments that were
149 /// provided did not match the respective generic parameters.
150 #[derive(Clone, Default)]
151 pub struct GenericArgCountMismatch {
152 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
153 pub reported: Option<ErrorReported>,
154 /// A list of spans of arguments provided that were not valid.
155 pub invalid_args: Vec<Span>,
158 /// Decorates the result of a generic argument count mismatch
159 /// check with whether explicit late bounds were provided.
161 pub struct GenericArgCountResult {
162 pub explicit_late_bound: ExplicitLateBound,
163 pub correct: Result<(), GenericArgCountMismatch>,
166 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
167 pub fn ast_region_to_region(
169 lifetime: &hir::Lifetime,
170 def: Option<&ty::GenericParamDef>,
171 ) -> ty::Region<'tcx> {
172 let tcx = self.tcx();
173 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id));
175 let r = match tcx.named_region(lifetime.hir_id) {
176 Some(rl::Region::Static) => tcx.lifetimes.re_static,
178 Some(rl::Region::LateBound(debruijn, id, _)) => {
179 let name = lifetime_name(id.expect_local());
180 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
183 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
184 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
187 Some(rl::Region::EarlyBound(index, id, _)) => {
188 let name = lifetime_name(id.expect_local());
189 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
192 Some(rl::Region::Free(scope, id)) => {
193 let name = lifetime_name(id.expect_local());
194 tcx.mk_region(ty::ReFree(ty::FreeRegion {
196 bound_region: ty::BrNamed(id, name),
199 // (*) -- not late-bound, won't change
203 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
204 // This indicates an illegal lifetime
205 // elision. `resolve_lifetime` should have
206 // reported an error in this case -- but if
207 // not, let's error out.
208 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
210 // Supply some dummy value. We don't have an
211 // `re_error`, annoyingly, so use `'static`.
212 tcx.lifetimes.re_static
217 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
222 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
223 /// returns an appropriate set of substitutions for this particular reference to `I`.
224 pub fn ast_path_substs_for_ty(
228 item_segment: &hir::PathSegment<'_>,
229 ) -> SubstsRef<'tcx> {
230 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
234 item_segment.generic_args(),
235 item_segment.infer_args,
239 if let Some(b) = assoc_bindings.first() {
240 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
246 /// Report error if there is an explicit type parameter when using `impl Trait`.
249 seg: &hir::PathSegment<'_>,
250 generics: &ty::Generics,
252 let explicit = !seg.infer_args;
253 let impl_trait = generics.params.iter().any(|param| match param.kind {
254 ty::GenericParamDefKind::Type {
255 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
261 if explicit && impl_trait {
266 .filter_map(|arg| match arg {
267 GenericArg::Type(_) => Some(arg.span()),
270 .collect::<Vec<_>>();
272 let mut err = struct_span_err! {
276 "cannot provide explicit generic arguments when `impl Trait` is \
277 used in argument position"
281 err.span_label(span, "explicit generic argument not allowed");
290 /// Checks that the correct number of generic arguments have been provided.
291 /// Used specifically for function calls.
292 pub fn check_generic_arg_count_for_call(
296 seg: &hir::PathSegment<'_>,
297 is_method_call: bool,
298 ) -> GenericArgCountResult {
299 let empty_args = hir::GenericArgs::none();
300 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
301 Self::check_generic_arg_count(
305 if let Some(ref args) = seg.args { args } else { &empty_args },
306 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
307 def.parent.is_none() && def.has_self, // `has_self`
308 seg.infer_args || suppress_mismatch, // `infer_args`
312 /// Checks that the correct number of generic arguments have been provided.
313 /// This is used both for datatypes and function calls.
314 fn check_generic_arg_count(
318 args: &hir::GenericArgs<'_>,
319 position: GenericArgPosition,
322 ) -> GenericArgCountResult {
323 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
324 // that lifetimes will proceed types. So it suffices to check the number of each generic
325 // arguments in order to validate them with respect to the generic parameters.
326 let param_counts = def.own_counts();
327 let arg_counts = args.own_counts();
328 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
330 let mut defaults: ty::GenericParamCount = Default::default();
331 for param in &def.params {
333 GenericParamDefKind::Lifetime => {}
334 GenericParamDefKind::Type { has_default, .. } => {
335 defaults.types += has_default as usize
337 GenericParamDefKind::Const => {
338 // FIXME(const_generics:defaults)
343 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
344 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
347 let explicit_late_bound =
348 Self::prohibit_explicit_late_bound_lifetimes(tcx, def, args, position);
350 let check_kind_count = |kind,
355 unexpected_spans: &mut Vec<Span>,
358 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
359 kind, required, permitted, provided, offset
361 // We enforce the following: `required` <= `provided` <= `permitted`.
362 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
363 // For other kinds (i.e., types), `permitted` may be greater than `required`.
364 if required <= provided && provided <= permitted {
372 // Unfortunately lifetime and type parameter mismatches are typically styled
373 // differently in diagnostics, which means we have a few cases to consider here.
374 let (bound, quantifier) = if required != permitted {
375 if provided < required {
376 (required, "at least ")
378 // provided > permitted
379 (permitted, "at most ")
385 let (spans, label) = if required == permitted && provided > permitted {
386 // In the case when the user has provided too many arguments,
387 // we want to point to the unexpected arguments.
388 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
390 .map(|arg| arg.span())
392 unexpected_spans.extend(spans.clone());
393 (spans, format!("unexpected {} argument", kind))
398 "expected {}{} {} argument{}",
407 let mut err = tcx.sess.struct_span_err_with_code(
410 "wrong number of {} arguments: expected {}{}, found {}",
411 kind, quantifier, bound, provided,
413 DiagnosticId::Error("E0107".into()),
416 err.span_label(span, label.as_str());
423 let mut arg_count_correct = Ok(());
424 let mut unexpected_spans = vec![];
426 if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
427 arg_count_correct = check_kind_count(
429 param_counts.lifetimes,
430 param_counts.lifetimes,
431 arg_counts.lifetimes,
433 &mut unexpected_spans,
434 explicit_late_bound == ExplicitLateBound::Yes,
436 .and(arg_count_correct);
438 // FIXME(const_generics:defaults)
439 if !infer_args || arg_counts.consts > param_counts.consts {
440 arg_count_correct = check_kind_count(
445 arg_counts.lifetimes + arg_counts.types,
446 &mut unexpected_spans,
449 .and(arg_count_correct);
451 // Note that type errors are currently be emitted *after* const errors.
452 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
454 arg_count_correct = check_kind_count(
456 param_counts.types - defaults.types - has_self as usize,
457 param_counts.types - has_self as usize,
459 arg_counts.lifetimes,
460 &mut unexpected_spans,
463 .and(arg_count_correct);
466 GenericArgCountResult {
468 correct: arg_count_correct.map_err(|reported_err| GenericArgCountMismatch {
469 reported: if reported_err { Some(ErrorReported) } else { None },
470 invalid_args: unexpected_spans,
475 /// Report an error that a generic argument did not match the generic parameter that was
477 fn generic_arg_mismatch_err(
479 arg: &GenericArg<'_>,
483 let mut err = struct_span_err!(
487 "{} provided when a {} was expected",
492 let kind_ord = match kind {
493 "lifetime" => ParamKindOrd::Lifetime,
494 "type" => ParamKindOrd::Type,
495 "constant" => ParamKindOrd::Const,
496 // It's more concise to match on the string representation, though it means
497 // the match is non-exhaustive.
498 _ => bug!("invalid generic parameter kind {}", kind),
500 let arg_ord = match arg {
501 GenericArg::Lifetime(_) => ParamKindOrd::Lifetime,
502 GenericArg::Type(_) => ParamKindOrd::Type,
503 GenericArg::Const(_) => ParamKindOrd::Const,
506 // This note will be true as long as generic parameters are strictly ordered by their kind.
508 if kind_ord < arg_ord { (kind, arg.descr()) } else { (arg.descr(), kind) };
509 err.note(&format!("{} arguments must be provided before {} arguments", first, last));
511 if let Some(help) = help {
517 /// Creates the relevant generic argument substitutions
518 /// corresponding to a set of generic parameters. This is a
519 /// rather complex function. Let us try to explain the role
520 /// of each of its parameters:
522 /// To start, we are given the `def_id` of the thing we are
523 /// creating the substitutions for, and a partial set of
524 /// substitutions `parent_substs`. In general, the substitutions
525 /// for an item begin with substitutions for all the "parents" of
526 /// that item -- e.g., for a method it might include the
527 /// parameters from the impl.
529 /// Therefore, the method begins by walking down these parents,
530 /// starting with the outermost parent and proceed inwards until
531 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
532 /// first to see if the parent's substitutions are listed in there. If so,
533 /// we can append those and move on. Otherwise, it invokes the
534 /// three callback functions:
536 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
537 /// generic arguments that were given to that parent from within
538 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
539 /// might refer to the trait `Foo`, and the arguments might be
540 /// `[T]`. The boolean value indicates whether to infer values
541 /// for arguments whose values were not explicitly provided.
542 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
543 /// instantiate a `GenericArg`.
544 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
545 /// creates a suitable inference variable.
546 pub fn create_substs_for_generic_args<'b>(
549 parent_substs: &[subst::GenericArg<'tcx>],
551 self_ty: Option<Ty<'tcx>>,
552 arg_count: GenericArgCountResult,
553 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
554 mut provided_kind: impl FnMut(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
555 mut inferred_kind: impl FnMut(
556 Option<&[subst::GenericArg<'tcx>]>,
559 ) -> subst::GenericArg<'tcx>,
560 ) -> SubstsRef<'tcx> {
561 // Collect the segments of the path; we need to substitute arguments
562 // for parameters throughout the entire path (wherever there are
563 // generic parameters).
564 let mut parent_defs = tcx.generics_of(def_id);
565 let count = parent_defs.count();
566 let mut stack = vec![(def_id, parent_defs)];
567 while let Some(def_id) = parent_defs.parent {
568 parent_defs = tcx.generics_of(def_id);
569 stack.push((def_id, parent_defs));
572 // We manually build up the substitution, rather than using convenience
573 // methods in `subst.rs`, so that we can iterate over the arguments and
574 // parameters in lock-step linearly, instead of trying to match each pair.
575 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
576 // Iterate over each segment of the path.
577 while let Some((def_id, defs)) = stack.pop() {
578 let mut params = defs.params.iter().peekable();
580 // If we have already computed substitutions for parents, we can use those directly.
581 while let Some(¶m) = params.peek() {
582 if let Some(&kind) = parent_substs.get(param.index as usize) {
590 // `Self` is handled first, unless it's been handled in `parent_substs`.
592 if let Some(¶m) = params.peek() {
593 if param.index == 0 {
594 if let GenericParamDefKind::Type { .. } = param.kind {
598 .unwrap_or_else(|| inferred_kind(None, param, true)),
606 // Check whether this segment takes generic arguments and the user has provided any.
607 let (generic_args, infer_args) = args_for_def_id(def_id);
610 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
612 // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
613 // If we later encounter a lifetime, we know that the arguments were provided in the
614 // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
615 // inferred, so we can use it for diagnostics later.
616 let mut force_infer_lt = None;
619 // We're going to iterate through the generic arguments that the user
620 // provided, matching them with the generic parameters we expect.
621 // Mismatches can occur as a result of elided lifetimes, or for malformed
622 // input. We try to handle both sensibly.
623 match (args.peek(), params.peek()) {
624 (Some(&arg), Some(¶m)) => {
625 match (arg, ¶m.kind, arg_count.explicit_late_bound) {
626 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
627 | (GenericArg::Type(_), GenericParamDefKind::Type { .. }, _)
628 | (GenericArg::Const(_), GenericParamDefKind::Const, _) => {
629 substs.push(provided_kind(param, arg));
634 GenericArg::Type(_) | GenericArg::Const(_),
635 GenericParamDefKind::Lifetime,
638 // We expected a lifetime argument, but got a type or const
639 // argument. That means we're inferring the lifetimes.
640 substs.push(inferred_kind(None, param, infer_args));
641 force_infer_lt = Some(arg);
644 (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
645 // We've come across a lifetime when we expected something else in
646 // the presence of explicit late bounds. This is most likely
647 // due to the presence of the explicit bound so we're just going to
652 // We expected one kind of parameter, but the user provided
653 // another. This is an error. However, if we already know that
654 // the arguments don't match up with the parameters, we won't issue
655 // an additional error, as the user already knows what's wrong.
656 if arg_count.correct.is_ok()
657 && arg_count.explicit_late_bound == ExplicitLateBound::No
659 // We're going to iterate over the parameters to sort them out, and
660 // show that order to the user as a possible order for the parameters
661 let mut param_types_present = defs
668 GenericParamDefKind::Lifetime => {
669 ParamKindOrd::Lifetime
671 GenericParamDefKind::Type { .. } => {
674 GenericParamDefKind::Const => {
681 .collect::<Vec<(ParamKindOrd, GenericParamDef)>>();
682 param_types_present.sort_by_key(|(ord, _)| *ord);
683 let (mut param_types_present, ordered_params): (
685 Vec<GenericParamDef>,
686 ) = param_types_present.into_iter().unzip();
687 param_types_present.dedup();
689 Self::generic_arg_mismatch_err(
694 "reorder the arguments: {}: `<{}>`",
697 .map(|ord| format!("{}s", ord.to_string()))
698 .collect::<Vec<String>>()
702 .filter_map(|param| {
703 if param.name == kw::SelfUpper {
706 Some(param.name.to_string())
709 .collect::<Vec<String>>()
715 // We've reported the error, but we want to make sure that this
716 // problem doesn't bubble down and create additional, irrelevant
717 // errors. In this case, we're simply going to ignore the argument
718 // and any following arguments. The rest of the parameters will be
720 while args.next().is_some() {}
725 (Some(&arg), None) => {
726 // We should never be able to reach this point with well-formed input.
727 // There are three situations in which we can encounter this issue.
729 // 1. The number of arguments is incorrect. In this case, an error
730 // will already have been emitted, and we can ignore it.
731 // 2. There are late-bound lifetime parameters present, yet the
732 // lifetime arguments have also been explicitly specified by the
734 // 3. We've inferred some lifetimes, which have been provided later (i.e.
735 // after a type or const). We want to throw an error in this case.
737 if arg_count.correct.is_ok()
738 && arg_count.explicit_late_bound == ExplicitLateBound::No
740 let kind = arg.descr();
741 assert_eq!(kind, "lifetime");
743 force_infer_lt.expect("lifetimes ought to have been inferred");
744 Self::generic_arg_mismatch_err(tcx.sess, provided, kind, None);
750 (None, Some(¶m)) => {
751 // If there are fewer arguments than parameters, it means
752 // we're inferring the remaining arguments.
753 substs.push(inferred_kind(Some(&substs), param, infer_args));
757 (None, None) => break,
762 tcx.intern_substs(&substs)
765 /// Given the type/lifetime/const arguments provided to some path (along with
766 /// an implicit `Self`, if this is a trait reference), returns the complete
767 /// set of substitutions. This may involve applying defaulted type parameters.
768 /// Also returns back constraints on associated types.
773 /// T: std::ops::Index<usize, Output = u32>
774 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
777 /// 1. The `self_ty` here would refer to the type `T`.
778 /// 2. The path in question is the path to the trait `std::ops::Index`,
779 /// which will have been resolved to a `def_id`
780 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
781 /// parameters are returned in the `SubstsRef`, the associated type bindings like
782 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
784 /// Note that the type listing given here is *exactly* what the user provided.
786 /// For (generic) associated types
789 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
792 /// We have the parent substs are the substs for the parent trait:
793 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
794 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
795 /// lists: `[Vec<u8>, u8, 'a]`.
796 fn create_substs_for_ast_path<'a>(
800 parent_substs: &[subst::GenericArg<'tcx>],
801 generic_args: &'a hir::GenericArgs<'_>,
803 self_ty: Option<Ty<'tcx>>,
804 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
805 // If the type is parameterized by this region, then replace this
806 // region with the current anon region binding (in other words,
807 // whatever & would get replaced with).
809 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
811 def_id, self_ty, generic_args
814 let tcx = self.tcx();
815 let generic_params = tcx.generics_of(def_id);
817 if generic_params.has_self {
818 if generic_params.parent.is_some() {
819 // The parent is a trait so it should have at least one subst
820 // for the `Self` type.
821 assert!(!parent_substs.is_empty())
823 // This item (presumably a trait) needs a self-type.
824 assert!(self_ty.is_some());
827 assert!(self_ty.is_none() && parent_substs.is_empty());
830 let arg_count = Self::check_generic_arg_count(
835 GenericArgPosition::Type,
840 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
841 let default_needs_object_self = |param: &ty::GenericParamDef| {
842 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
843 if is_object && has_default {
844 let default_ty = tcx.at(span).type_of(param.def_id);
845 let self_param = tcx.types.self_param;
846 if default_ty.walk().any(|arg| arg == self_param.into()) {
847 // There is no suitable inference default for a type parameter
848 // that references self, in an object type.
857 let mut missing_type_params = vec![];
858 let mut inferred_params = vec![];
859 let substs = Self::create_substs_for_generic_args(
866 // Provide the generic args, and whether types should be inferred.
869 (Some(generic_args), infer_args)
871 // The last component of this tuple is unimportant.
875 // Provide substitutions for parameters for which (valid) arguments have been provided.
876 |param, arg| match (¶m.kind, arg) {
877 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
878 self.ast_region_to_region(<, Some(param)).into()
880 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
881 if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
882 inferred_params.push(ty.span);
883 tcx.ty_error().into()
885 self.ast_ty_to_ty(&ty).into()
888 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
889 ty::Const::from_opt_const_arg_anon_const(
891 ty::WithOptConstParam {
892 did: tcx.hir().local_def_id(ct.value.hir_id),
893 const_param_did: Some(param.def_id),
900 // Provide substitutions for parameters for which arguments are inferred.
901 |substs, param, infer_args| {
903 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
904 GenericParamDefKind::Type { has_default, .. } => {
905 if !infer_args && has_default {
906 // No type parameter provided, but a default exists.
908 // If we are converting an object type, then the
909 // `Self` parameter is unknown. However, some of the
910 // other type parameters may reference `Self` in their
911 // defaults. This will lead to an ICE if we are not
913 if default_needs_object_self(param) {
914 missing_type_params.push(param.name.to_string());
915 tcx.ty_error().into()
917 // This is a default type parameter.
920 tcx.at(span).type_of(param.def_id).subst_spanned(
928 } else if infer_args {
929 // No type parameters were provided, we can infer all.
931 if !default_needs_object_self(param) { Some(param) } else { None };
932 self.ty_infer(param, span).into()
934 // We've already errored above about the mismatch.
935 tcx.ty_error().into()
938 GenericParamDefKind::Const => {
939 let ty = tcx.at(span).type_of(param.def_id);
940 // FIXME(const_generics:defaults)
942 // No const parameters were provided, we can infer all.
943 self.ct_infer(ty, Some(param), span).into()
945 // We've already errored above about the mismatch.
946 tcx.const_error(ty).into()
953 self.complain_about_missing_type_params(
957 generic_args.args.is_empty(),
960 // Convert associated-type bindings or constraints into a separate vector.
961 // Example: Given this:
963 // T: Iterator<Item = u32>
965 // The `T` is passed in as a self-type; the `Item = u32` is
966 // not a "type parameter" of the `Iterator` trait, but rather
967 // a restriction on `<T as Iterator>::Item`, so it is passed
969 let assoc_bindings = generic_args
973 let kind = match binding.kind {
974 hir::TypeBindingKind::Equality { ref ty } => {
975 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
977 hir::TypeBindingKind::Constraint { ref bounds } => {
978 ConvertedBindingKind::Constraint(bounds)
981 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
986 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
987 generic_params, self_ty, substs
990 (substs, assoc_bindings, arg_count)
993 crate fn create_substs_for_associated_item(
998 item_segment: &hir::PathSegment<'_>,
999 parent_substs: SubstsRef<'tcx>,
1000 ) -> SubstsRef<'tcx> {
1001 if tcx.generics_of(item_def_id).params.is_empty() {
1002 self.prohibit_generics(slice::from_ref(item_segment));
1006 self.create_substs_for_ast_path(
1010 item_segment.generic_args(),
1011 item_segment.infer_args,
1018 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
1019 /// the type parameter's name as a placeholder.
1020 fn complain_about_missing_type_params(
1022 missing_type_params: Vec<String>,
1025 empty_generic_args: bool,
1027 if missing_type_params.is_empty() {
1031 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1032 let mut err = struct_span_err!(
1036 "the type parameter{} {} must be explicitly specified",
1037 pluralize!(missing_type_params.len()),
1041 self.tcx().def_span(def_id),
1043 "type parameter{} {} must be specified for this",
1044 pluralize!(missing_type_params.len()),
1048 let mut suggested = false;
1049 if let (Ok(snippet), true) = (
1050 self.tcx().sess.source_map().span_to_snippet(span),
1051 // Don't suggest setting the type params if there are some already: the order is
1052 // tricky to get right and the user will already know what the syntax is.
1055 if snippet.ends_with('>') {
1056 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
1057 // we would have to preserve the right order. For now, as clearly the user is
1058 // aware of the syntax, we do nothing.
1060 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1061 // least we can clue them to the correct syntax `Iterator<Type>`.
1062 err.span_suggestion(
1065 "set the type parameter{plural} to the desired type{plural}",
1066 plural = pluralize!(missing_type_params.len()),
1068 format!("{}<{}>", snippet, missing_type_params.join(", ")),
1069 Applicability::HasPlaceholders,
1078 "missing reference{} to {}",
1079 pluralize!(missing_type_params.len()),
1085 "because of the default `Self` reference, type parameters must be \
1086 specified on object types",
1091 /// Instantiates the path for the given trait reference, assuming that it's
1092 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
1093 /// The type _cannot_ be a type other than a trait type.
1095 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
1096 /// are disallowed. Otherwise, they are pushed onto the vector given.
1097 pub fn instantiate_mono_trait_ref(
1099 trait_ref: &hir::TraitRef<'_>,
1101 ) -> ty::TraitRef<'tcx> {
1102 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1104 self.ast_path_to_mono_trait_ref(
1105 trait_ref.path.span,
1106 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
1108 trait_ref.path.segments.last().unwrap(),
1112 /// The given trait-ref must actually be a trait.
1113 pub(super) fn instantiate_poly_trait_ref_inner(
1115 trait_ref: &hir::TraitRef<'_>,
1117 constness: Constness,
1119 bounds: &mut Bounds<'tcx>,
1121 ) -> GenericArgCountResult {
1122 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
1124 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
1126 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1128 let (substs, assoc_bindings, arg_count) = self.create_substs_for_ast_trait_ref(
1129 trait_ref.path.span,
1132 trait_ref.path.segments.last().unwrap(),
1134 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
1136 bounds.trait_bounds.push((poly_trait_ref, span, constness));
1138 let mut dup_bindings = FxHashMap::default();
1139 for binding in &assoc_bindings {
1140 // Specify type to assert that error was already reported in `Err` case.
1141 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
1142 trait_ref.hir_ref_id,
1150 // Okay to ignore `Err` because of `ErrorReported` (see above).
1154 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
1155 trait_ref, bounds, poly_trait_ref
1161 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
1162 /// a full trait reference. The resulting trait reference is returned. This may also generate
1163 /// auxiliary bounds, which are added to `bounds`.
1168 /// poly_trait_ref = Iterator<Item = u32>
1172 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
1174 /// **A note on binders:** against our usual convention, there is an implied bounder around
1175 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
1176 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
1177 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
1178 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
1180 pub fn instantiate_poly_trait_ref(
1182 poly_trait_ref: &hir::PolyTraitRef<'_>,
1183 constness: Constness,
1185 bounds: &mut Bounds<'tcx>,
1186 ) -> GenericArgCountResult {
1187 self.instantiate_poly_trait_ref_inner(
1188 &poly_trait_ref.trait_ref,
1189 poly_trait_ref.span,
1197 fn ast_path_to_mono_trait_ref(
1200 trait_def_id: DefId,
1202 trait_segment: &hir::PathSegment<'_>,
1203 ) -> ty::TraitRef<'tcx> {
1204 let (substs, assoc_bindings, _) =
1205 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1206 if let Some(b) = assoc_bindings.first() {
1207 AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span);
1209 ty::TraitRef::new(trait_def_id, substs)
1212 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1213 /// an error and attempt to build a reasonable structured suggestion.
1214 fn complain_about_internal_fn_trait(
1217 trait_def_id: DefId,
1218 trait_segment: &'a hir::PathSegment<'a>,
1220 let trait_def = self.tcx().trait_def(trait_def_id);
1222 if !self.tcx().features().unboxed_closures
1223 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1225 let sess = &self.tcx().sess.parse_sess;
1226 // For now, require that parenthetical notation be used only with `Fn()` etc.
1227 let (msg, sugg) = if trait_def.paren_sugar {
1229 "the precise format of `Fn`-family traits' type parameters is subject to \
1233 trait_segment.ident,
1237 .and_then(|args| args.args.get(0))
1238 .and_then(|arg| match arg {
1239 hir::GenericArg::Type(ty) => match ty.kind {
1240 hir::TyKind::Tup(t) => t
1242 .map(|e| sess.source_map().span_to_snippet(e.span))
1243 .collect::<Result<Vec<_>, _>>()
1244 .map(|a| a.join(", ")),
1245 _ => sess.source_map().span_to_snippet(ty.span),
1247 .map(|s| format!("({})", s))
1251 .unwrap_or_else(|| "()".to_string()),
1256 .find_map(|b| match (b.ident.name == sym::Output, &b.kind) {
1257 (true, hir::TypeBindingKind::Equality { ty }) => {
1258 sess.source_map().span_to_snippet(ty.span).ok()
1262 .unwrap_or_else(|| "()".to_string()),
1266 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1268 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1269 if let Some(sugg) = sugg {
1270 let msg = "use parenthetical notation instead";
1271 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1277 fn create_substs_for_ast_trait_ref<'a>(
1280 trait_def_id: DefId,
1282 trait_segment: &'a hir::PathSegment<'a>,
1283 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
1284 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1286 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1288 self.create_substs_for_ast_path(
1292 trait_segment.generic_args(),
1293 trait_segment.infer_args,
1298 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
1300 .associated_items(trait_def_id)
1301 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
1305 // Returns `true` if a bounds list includes `?Sized`.
1306 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1307 let tcx = self.tcx();
1309 // Try to find an unbound in bounds.
1310 let mut unbound = None;
1311 for ab in ast_bounds {
1312 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1313 if unbound.is_none() {
1314 unbound = Some(&ptr.trait_ref);
1320 "type parameter has more than one relaxed default \
1321 bound, only one is supported"
1328 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1331 // FIXME(#8559) currently requires the unbound to be built-in.
1332 if let Ok(kind_id) = kind_id {
1333 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1336 "default bound relaxed for a type parameter, but \
1337 this does nothing because the given bound is not \
1338 a default; only `?Sized` is supported",
1343 _ if kind_id.is_ok() => {
1346 // No lang item for `Sized`, so we can't add it as a bound.
1353 /// This helper takes a *converted* parameter type (`param_ty`)
1354 /// and an *unconverted* list of bounds:
1357 /// fn foo<T: Debug>
1358 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1360 /// `param_ty`, in ty form
1363 /// It adds these `ast_bounds` into the `bounds` structure.
1365 /// **A note on binders:** there is an implied binder around
1366 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1367 /// for more details.
1371 ast_bounds: &[hir::GenericBound<'_>],
1372 bounds: &mut Bounds<'tcx>,
1374 let mut trait_bounds = Vec::new();
1375 let mut region_bounds = Vec::new();
1377 let constness = self.default_constness_for_trait_bounds();
1378 for ast_bound in ast_bounds {
1380 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1381 trait_bounds.push((b, constness))
1383 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
1384 trait_bounds.push((b, Constness::NotConst))
1386 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1387 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1391 for (bound, constness) in trait_bounds {
1392 let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
1395 bounds.region_bounds.extend(
1396 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1400 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1401 /// The self-type for the bounds is given by `param_ty`.
1406 /// fn foo<T: Bar + Baz>() { }
1407 /// ^ ^^^^^^^^^ ast_bounds
1411 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1412 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1413 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1415 /// `span` should be the declaration size of the parameter.
1416 pub fn compute_bounds(
1419 ast_bounds: &[hir::GenericBound<'_>],
1420 sized_by_default: SizedByDefault,
1423 let mut bounds = Bounds::default();
1425 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1426 bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
1428 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1429 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1437 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1440 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1441 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1442 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1443 fn add_predicates_for_ast_type_binding(
1445 hir_ref_id: hir::HirId,
1446 trait_ref: ty::PolyTraitRef<'tcx>,
1447 binding: &ConvertedBinding<'_, 'tcx>,
1448 bounds: &mut Bounds<'tcx>,
1450 dup_bindings: &mut FxHashMap<DefId, Span>,
1452 ) -> Result<(), ErrorReported> {
1453 let tcx = self.tcx();
1456 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1457 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1458 // subtle in the event that `T` is defined in a supertrait of
1459 // `SomeTrait`, because in that case we need to upcast.
1461 // That is, consider this case:
1464 // trait SubTrait: SuperTrait<i32> { }
1465 // trait SuperTrait<A> { type T; }
1467 // ... B: SubTrait<T = foo> ...
1470 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1472 // Find any late-bound regions declared in `ty` that are not
1473 // declared in the trait-ref. These are not well-formed.
1477 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1478 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1479 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1480 let late_bound_in_trait_ref =
1481 tcx.collect_constrained_late_bound_regions(&trait_ref);
1482 let late_bound_in_ty =
1483 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1484 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1485 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1487 // FIXME: point at the type params that don't have appropriate lifetimes:
1488 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1489 // ---- ---- ^^^^^^^
1490 self.validate_late_bound_regions(
1491 late_bound_in_trait_ref,
1498 "binding for associated type `{}` references {}, \
1499 which does not appear in the trait input types",
1509 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1510 // Simple case: X is defined in the current trait.
1513 // Otherwise, we have to walk through the supertraits to find
1515 self.one_bound_for_assoc_type(
1516 || traits::supertraits(tcx, trait_ref),
1517 || trait_ref.print_only_trait_path().to_string(),
1520 || match binding.kind {
1521 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1527 let (assoc_ident, def_scope) =
1528 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1530 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1531 // of calling `filter_by_name_and_kind`.
1533 .associated_items(candidate.def_id())
1534 .filter_by_name_unhygienic(assoc_ident.name)
1536 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1538 .expect("missing associated type");
1540 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1544 &format!("associated type `{}` is private", binding.item_name),
1546 .span_label(binding.span, "private associated type")
1549 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1553 .entry(assoc_ty.def_id)
1554 .and_modify(|prev_span| {
1559 "the value of the associated type `{}` (from trait `{}`) \
1560 is already specified",
1562 tcx.def_path_str(assoc_ty.container.id())
1564 .span_label(binding.span, "re-bound here")
1565 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1568 .or_insert(binding.span);
1571 match binding.kind {
1572 ConvertedBindingKind::Equality(ref ty) => {
1573 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1574 // the "projection predicate" for:
1576 // `<T as Iterator>::Item = u32`
1577 bounds.projection_bounds.push((
1578 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1579 projection_ty: ty::ProjectionTy::from_ref_and_name(
1589 ConvertedBindingKind::Constraint(ast_bounds) => {
1590 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1592 // `<T as Iterator>::Item: Debug`
1594 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1595 // parameter to have a skipped binder.
1596 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1597 self.add_bounds(param_ty, ast_bounds, bounds);
1607 item_segment: &hir::PathSegment<'_>,
1609 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1610 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1613 fn conv_object_ty_poly_trait_ref(
1616 trait_bounds: &[hir::PolyTraitRef<'_>],
1617 lifetime: &hir::Lifetime,
1619 let tcx = self.tcx();
1621 let mut bounds = Bounds::default();
1622 let mut potential_assoc_types = Vec::new();
1623 let dummy_self = self.tcx().types.trait_object_dummy_self;
1624 for trait_bound in trait_bounds.iter().rev() {
1625 if let GenericArgCountResult {
1627 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1629 } = self.instantiate_poly_trait_ref(
1631 Constness::NotConst,
1635 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1639 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1640 // is used and no 'maybe' bounds are used.
1641 let expanded_traits =
1642 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1643 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1644 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1645 if regular_traits.len() > 1 {
1646 let first_trait = ®ular_traits[0];
1647 let additional_trait = ®ular_traits[1];
1648 let mut err = struct_span_err!(
1650 additional_trait.bottom().1,
1652 "only auto traits can be used as additional traits in a trait object"
1654 additional_trait.label_with_exp_info(
1656 "additional non-auto trait",
1659 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1663 if regular_traits.is_empty() && auto_traits.is_empty() {
1668 "at least one trait is required for an object type"
1671 return tcx.ty_error();
1674 // Check that there are no gross object safety violations;
1675 // most importantly, that the supertraits don't contain `Self`,
1677 for item in ®ular_traits {
1678 let object_safety_violations =
1679 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1680 if !object_safety_violations.is_empty() {
1681 report_object_safety_error(
1684 item.trait_ref().def_id(),
1685 &object_safety_violations[..],
1688 return tcx.ty_error();
1692 // Use a `BTreeSet` to keep output in a more consistent order.
1693 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1695 let regular_traits_refs_spans = bounds
1698 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1700 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1701 assert_eq!(constness, Constness::NotConst);
1703 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1705 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1706 obligation.predicate
1709 match obligation.predicate.skip_binders() {
1710 ty::PredicateAtom::Trait(pred, _) => {
1711 let pred = ty::Binder::bind(pred);
1712 associated_types.entry(span).or_default().extend(
1713 tcx.associated_items(pred.def_id())
1714 .in_definition_order()
1715 .filter(|item| item.kind == ty::AssocKind::Type)
1716 .map(|item| item.def_id),
1719 ty::PredicateAtom::Projection(pred) => {
1720 let pred = ty::Binder::bind(pred);
1721 // A `Self` within the original bound will be substituted with a
1722 // `trait_object_dummy_self`, so check for that.
1723 let references_self =
1724 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1726 // If the projection output contains `Self`, force the user to
1727 // elaborate it explicitly to avoid a lot of complexity.
1729 // The "classicaly useful" case is the following:
1731 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1736 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1737 // but actually supporting that would "expand" to an infinitely-long type
1738 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1740 // Instead, we force the user to write
1741 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1742 // the discussion in #56288 for alternatives.
1743 if !references_self {
1744 // Include projections defined on supertraits.
1745 bounds.projection_bounds.push((pred, span));
1753 for (projection_bound, _) in &bounds.projection_bounds {
1754 for def_ids in associated_types.values_mut() {
1755 def_ids.remove(&projection_bound.projection_def_id());
1759 self.complain_about_missing_associated_types(
1761 potential_assoc_types,
1765 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1766 // `dyn Trait + Send`.
1767 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1768 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1769 debug!("regular_traits: {:?}", regular_traits);
1770 debug!("auto_traits: {:?}", auto_traits);
1772 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1773 // removing the dummy `Self` type (`trait_object_dummy_self`).
1774 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1775 if trait_ref.self_ty() != dummy_self {
1776 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1777 // which picks up non-supertraits where clauses - but also, the object safety
1778 // completely ignores trait aliases, which could be object safety hazards. We
1779 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1780 // disabled. (#66420)
1781 tcx.sess.delay_span_bug(
1784 "trait_ref_to_existential called on {:?} with non-dummy Self",
1789 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1792 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1793 let existential_trait_refs =
1794 regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1795 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1796 bound.map_bound(|b| {
1797 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1798 ty::ExistentialProjection {
1800 item_def_id: b.projection_ty.item_def_id,
1801 substs: trait_ref.substs,
1806 // Calling `skip_binder` is okay because the predicates are re-bound.
1807 let regular_trait_predicates = existential_trait_refs
1808 .map(|trait_ref| ty::ExistentialPredicate::Trait(trait_ref.skip_binder()));
1809 let auto_trait_predicates = auto_traits
1811 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1812 let mut v = regular_trait_predicates
1813 .chain(auto_trait_predicates)
1815 existential_projections
1816 .map(|x| ty::ExistentialPredicate::Projection(x.skip_binder())),
1818 .collect::<SmallVec<[_; 8]>>();
1819 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1821 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1823 // Use explicitly-specified region bound.
1824 let region_bound = if !lifetime.is_elided() {
1825 self.ast_region_to_region(lifetime, None)
1827 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1828 if tcx.named_region(lifetime.hir_id).is_some() {
1829 self.ast_region_to_region(lifetime, None)
1831 self.re_infer(None, span).unwrap_or_else(|| {
1832 // FIXME: these can be redundant with E0106, but not always.
1837 "the lifetime bound for this object type cannot be deduced \
1838 from context; please supply an explicit bound"
1841 tcx.lifetimes.re_static
1846 debug!("region_bound: {:?}", region_bound);
1848 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1849 debug!("trait_object_type: {:?}", ty);
1853 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1854 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1855 /// same trait bound have the same name (as they come from different super-traits), we instead
1856 /// emit a generic note suggesting using a `where` clause to constraint instead.
1857 fn complain_about_missing_associated_types(
1859 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1860 potential_assoc_types: Vec<Span>,
1861 trait_bounds: &[hir::PolyTraitRef<'_>],
1863 if associated_types.values().all(|v| v.is_empty()) {
1866 let tcx = self.tcx();
1867 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1868 // appropriate one, but this should be handled earlier in the span assignment.
1869 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1871 .map(|(span, def_ids)| {
1872 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1875 let mut names = vec![];
1877 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1878 // `issue-22560.rs`.
1879 let mut trait_bound_spans: Vec<Span> = vec![];
1880 for (span, items) in &associated_types {
1881 if !items.is_empty() {
1882 trait_bound_spans.push(*span);
1884 for assoc_item in items {
1885 let trait_def_id = assoc_item.container.id();
1887 "`{}` (from trait `{}`)",
1889 tcx.def_path_str(trait_def_id),
1893 if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
1894 match &bound.trait_ref.path.segments[..] {
1895 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1896 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1897 // around that bug here, even though it should be fixed elsewhere.
1898 // This would otherwise cause an invalid suggestion. For an example, look at
1899 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1901 // error[E0191]: the value of the associated type `Output`
1902 // (from trait `std::ops::BitXor`) must be specified
1903 // --> $DIR/issue-28344.rs:4:17
1905 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1906 // | ^^^^^^ help: specify the associated type:
1907 // | `BitXor<Output = Type>`
1911 // error[E0191]: the value of the associated type `Output`
1912 // (from trait `std::ops::BitXor`) must be specified
1913 // --> $DIR/issue-28344.rs:4:17
1915 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1916 // | ^^^^^^^^^^^^^ help: specify the associated type:
1917 // | `BitXor::bitor<Output = Type>`
1918 [segment] if segment.args.is_none() => {
1919 trait_bound_spans = vec![segment.ident.span];
1920 associated_types = associated_types
1922 .map(|(_, items)| (segment.ident.span, items))
1929 trait_bound_spans.sort();
1930 let mut err = struct_span_err!(
1934 "the value of the associated type{} {} must be specified",
1935 pluralize!(names.len()),
1938 let mut suggestions = vec![];
1939 let mut types_count = 0;
1940 let mut where_constraints = vec![];
1941 for (span, assoc_items) in &associated_types {
1942 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1943 for item in assoc_items {
1945 *names.entry(item.ident.name).or_insert(0) += 1;
1947 let mut dupes = false;
1948 for item in assoc_items {
1949 let prefix = if names[&item.ident.name] > 1 {
1950 let trait_def_id = item.container.id();
1952 format!("{}::", tcx.def_path_str(trait_def_id))
1956 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1957 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1960 if potential_assoc_types.len() == assoc_items.len() {
1961 // Only suggest when the amount of missing associated types equals the number of
1962 // extra type arguments present, as that gives us a relatively high confidence
1963 // that the user forgot to give the associtated type's name. The canonical
1964 // example would be trying to use `Iterator<isize>` instead of
1965 // `Iterator<Item = isize>`.
1966 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1967 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1968 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1971 } else if let (Ok(snippet), false) =
1972 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1975 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1976 let code = if snippet.ends_with('>') {
1977 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1978 // suggest, but at least we can clue them to the correct syntax
1979 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1981 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1983 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1984 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1985 format!("{}<{}>", snippet, types.join(", "))
1987 suggestions.push((*span, code));
1989 where_constraints.push(*span);
1992 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1993 using the fully-qualified path to the associated types";
1994 if !where_constraints.is_empty() && suggestions.is_empty() {
1995 // If there are duplicates associated type names and a single trait bound do not
1996 // use structured suggestion, it means that there are multiple super-traits with
1997 // the same associated type name.
1998 err.help(where_msg);
2000 if suggestions.len() != 1 {
2001 // We don't need this label if there's an inline suggestion, show otherwise.
2002 for (span, assoc_items) in &associated_types {
2003 let mut names: FxHashMap<_, usize> = FxHashMap::default();
2004 for item in assoc_items {
2006 *names.entry(item.ident.name).or_insert(0) += 1;
2008 let mut label = vec![];
2009 for item in assoc_items {
2010 let postfix = if names[&item.ident.name] > 1 {
2011 let trait_def_id = item.container.id();
2012 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
2016 label.push(format!("`{}`{}", item.ident, postfix));
2018 if !label.is_empty() {
2022 "associated type{} {} must be specified",
2023 pluralize!(label.len()),
2030 if !suggestions.is_empty() {
2031 err.multipart_suggestion(
2032 &format!("specify the associated type{}", pluralize!(types_count)),
2034 Applicability::HasPlaceholders,
2036 if !where_constraints.is_empty() {
2037 err.span_help(where_constraints, where_msg);
2043 fn report_ambiguous_associated_type(
2050 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
2051 if let (Some(_), Ok(snippet)) = (
2052 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
2053 self.tcx().sess.source_map().span_to_snippet(span),
2055 err.span_suggestion(
2057 "you are looking for the module in `std`, not the primitive type",
2058 format!("std::{}", snippet),
2059 Applicability::MachineApplicable,
2062 err.span_suggestion(
2064 "use fully-qualified syntax",
2065 format!("<{} as {}>::{}", type_str, trait_str, name),
2066 Applicability::HasPlaceholders,
2072 // Search for a bound on a type parameter which includes the associated item
2073 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
2074 // This function will fail if there are no suitable bounds or there is
2076 fn find_bound_for_assoc_item(
2078 ty_param_def_id: LocalDefId,
2081 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
2082 let tcx = self.tcx();
2085 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
2086 ty_param_def_id, assoc_name, span,
2090 &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
2092 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
2094 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id);
2095 let param_name = tcx.hir().ty_param_name(param_hir_id);
2096 self.one_bound_for_assoc_type(
2098 traits::transitive_bounds(
2100 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
2103 || param_name.to_string(),
2110 // Checks that `bounds` contains exactly one element and reports appropriate
2111 // errors otherwise.
2112 fn one_bound_for_assoc_type<I>(
2114 all_candidates: impl Fn() -> I,
2115 ty_param_name: impl Fn() -> String,
2118 is_equality: impl Fn() -> Option<String>,
2119 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
2121 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2123 let mut matching_candidates = all_candidates()
2124 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
2126 let bound = match matching_candidates.next() {
2127 Some(bound) => bound,
2129 self.complain_about_assoc_type_not_found(
2135 return Err(ErrorReported);
2139 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
2141 if let Some(bound2) = matching_candidates.next() {
2142 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
2144 let is_equality = is_equality();
2145 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
2146 let mut err = if is_equality.is_some() {
2147 // More specific Error Index entry.
2152 "ambiguous associated type `{}` in bounds of `{}`",
2161 "ambiguous associated type `{}` in bounds of `{}`",
2166 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
2168 let mut where_bounds = vec![];
2169 for bound in bounds {
2170 let bound_id = bound.def_id();
2171 let bound_span = self
2173 .associated_items(bound_id)
2174 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
2175 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
2177 if let Some(bound_span) = bound_span {
2181 "ambiguous `{}` from `{}`",
2183 bound.print_only_trait_path(),
2186 if let Some(constraint) = &is_equality {
2187 where_bounds.push(format!(
2188 " T: {trait}::{assoc} = {constraint}",
2189 trait=bound.print_only_trait_path(),
2191 constraint=constraint,
2194 err.span_suggestion(
2196 "use fully qualified syntax to disambiguate",
2200 bound.print_only_trait_path(),
2203 Applicability::MaybeIncorrect,
2208 "associated type `{}` could derive from `{}`",
2210 bound.print_only_trait_path(),
2214 if !where_bounds.is_empty() {
2216 "consider introducing a new type parameter `T` and adding `where` constraints:\
2217 \n where\n T: {},\n{}",
2219 where_bounds.join(",\n"),
2223 if !where_bounds.is_empty() {
2224 return Err(ErrorReported);
2230 fn complain_about_assoc_type_not_found<I>(
2232 all_candidates: impl Fn() -> I,
2233 ty_param_name: &str,
2237 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2239 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2240 // valid span, so we point at the whole path segment instead.
2241 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2242 let mut err = struct_span_err!(
2246 "associated type `{}` not found for `{}`",
2251 let all_candidate_names: Vec<_> = all_candidates()
2252 .map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
2255 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2259 if let (Some(suggested_name), true) = (
2260 find_best_match_for_name(all_candidate_names.iter(), assoc_name.name, None),
2261 assoc_name.span != DUMMY_SP,
2263 err.span_suggestion(
2265 "there is an associated type with a similar name",
2266 suggested_name.to_string(),
2267 Applicability::MaybeIncorrect,
2270 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2276 // Create a type from a path to an associated type.
2277 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2278 // and item_segment is the path segment for `D`. We return a type and a def for
2280 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2281 // parameter or `Self`.
2282 pub fn associated_path_to_ty(
2284 hir_ref_id: hir::HirId,
2288 assoc_segment: &hir::PathSegment<'_>,
2289 permit_variants: bool,
2290 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2291 let tcx = self.tcx();
2292 let assoc_ident = assoc_segment.ident;
2294 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2296 // Check if we have an enum variant.
2297 let mut variant_resolution = None;
2298 if let ty::Adt(adt_def, _) = qself_ty.kind {
2299 if adt_def.is_enum() {
2300 let variant_def = adt_def
2303 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2304 if let Some(variant_def) = variant_def {
2305 if permit_variants {
2306 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2307 self.prohibit_generics(slice::from_ref(assoc_segment));
2308 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2310 variant_resolution = Some(variant_def.def_id);
2316 // Find the type of the associated item, and the trait where the associated
2317 // item is declared.
2318 let bound = match (&qself_ty.kind, qself_res) {
2319 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2320 // `Self` in an impl of a trait -- we have a concrete self type and a
2322 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2323 Some(trait_ref) => trait_ref,
2325 // A cycle error occurred, most likely.
2326 return Err(ErrorReported);
2330 self.one_bound_for_assoc_type(
2331 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2332 || "Self".to_string(),
2340 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
2341 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2343 if variant_resolution.is_some() {
2344 // Variant in type position
2345 let msg = format!("expected type, found variant `{}`", assoc_ident);
2346 tcx.sess.span_err(span, &msg);
2347 } else if qself_ty.is_enum() {
2348 let mut err = struct_span_err!(
2352 "no variant named `{}` found for enum `{}`",
2357 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2358 if let Some(suggested_name) = find_best_match_for_name(
2359 adt_def.variants.iter().map(|variant| &variant.ident.name),
2363 err.span_suggestion(
2365 "there is a variant with a similar name",
2366 suggested_name.to_string(),
2367 Applicability::MaybeIncorrect,
2372 format!("variant not found in `{}`", qself_ty),
2376 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2377 let sp = tcx.sess.source_map().guess_head_span(sp);
2378 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2382 } else if !qself_ty.references_error() {
2383 // Don't print `TyErr` to the user.
2384 self.report_ambiguous_associated_type(
2386 &qself_ty.to_string(),
2391 return Err(ErrorReported);
2395 let trait_did = bound.def_id();
2396 let (assoc_ident, def_scope) =
2397 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2399 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2400 // of calling `filter_by_name_and_kind`.
2402 .associated_items(trait_did)
2403 .in_definition_order()
2405 i.kind.namespace() == Namespace::TypeNS
2406 && i.ident.normalize_to_macros_2_0() == assoc_ident
2408 .expect("missing associated type");
2410 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2411 let ty = self.normalize_ty(span, ty);
2413 let kind = DefKind::AssocTy;
2414 if !item.vis.is_accessible_from(def_scope, tcx) {
2415 let kind = kind.descr(item.def_id);
2416 let msg = format!("{} `{}` is private", kind, assoc_ident);
2418 .struct_span_err(span, &msg)
2419 .span_label(span, &format!("private {}", kind))
2422 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2424 if let Some(variant_def_id) = variant_resolution {
2425 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2426 let mut err = lint.build("ambiguous associated item");
2427 let mut could_refer_to = |kind: DefKind, def_id, also| {
2428 let note_msg = format!(
2429 "`{}` could{} refer to the {} defined here",
2434 err.span_note(tcx.def_span(def_id), ¬e_msg);
2437 could_refer_to(DefKind::Variant, variant_def_id, "");
2438 could_refer_to(kind, item.def_id, " also");
2440 err.span_suggestion(
2442 "use fully-qualified syntax",
2443 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2444 Applicability::MachineApplicable,
2450 Ok((ty, kind, item.def_id))
2456 opt_self_ty: Option<Ty<'tcx>>,
2458 trait_segment: &hir::PathSegment<'_>,
2459 item_segment: &hir::PathSegment<'_>,
2461 let tcx = self.tcx();
2463 let trait_def_id = tcx.parent(item_def_id).unwrap();
2465 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2467 let self_ty = if let Some(ty) = opt_self_ty {
2470 let path_str = tcx.def_path_str(trait_def_id);
2472 let def_id = self.item_def_id();
2474 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2476 let parent_def_id = def_id
2477 .and_then(|def_id| {
2478 def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id))
2480 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
2482 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2484 // If the trait in segment is the same as the trait defining the item,
2485 // use the `<Self as ..>` syntax in the error.
2486 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2487 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2489 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2495 self.report_ambiguous_associated_type(
2499 item_segment.ident.name,
2501 return tcx.ty_error();
2504 debug!("qpath_to_ty: self_type={:?}", self_ty);
2506 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2508 let item_substs = self.create_substs_for_associated_item(
2516 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2518 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2521 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2525 let mut has_err = false;
2526 for segment in segments {
2527 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2528 for arg in segment.generic_args().args {
2529 let (span, kind) = match arg {
2530 hir::GenericArg::Lifetime(lt) => {
2536 (lt.span, "lifetime")
2538 hir::GenericArg::Type(ty) => {
2546 hir::GenericArg::Const(ct) => {
2555 let mut err = struct_span_err!(
2559 "{} arguments are not allowed for this type",
2562 err.span_label(span, format!("{} argument not allowed", kind));
2564 if err_for_lt && err_for_ty && err_for_ct {
2569 // Only emit the first error to avoid overloading the user with error messages.
2570 if let [binding, ..] = segment.generic_args().bindings {
2572 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2578 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2579 let mut err = struct_span_err!(
2583 "associated type bindings are not allowed here"
2585 err.span_label(span, "associated type not allowed here").emit();
2588 /// Prohibits explicit lifetime arguments if late-bound lifetime parameters
2589 /// are present. This is used both for datatypes and function calls.
2590 fn prohibit_explicit_late_bound_lifetimes(
2593 args: &hir::GenericArgs<'_>,
2594 position: GenericArgPosition,
2595 ) -> ExplicitLateBound {
2596 let param_counts = def.own_counts();
2597 let arg_counts = args.own_counts();
2598 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
2600 if infer_lifetimes {
2601 ExplicitLateBound::No
2602 } else if let Some(span_late) = def.has_late_bound_regions {
2603 let msg = "cannot specify lifetime arguments explicitly \
2604 if late bound lifetime parameters are present";
2605 let note = "the late bound lifetime parameter is introduced here";
2606 let span = args.args[0].span();
2607 if position == GenericArgPosition::Value
2608 && arg_counts.lifetimes != param_counts.lifetimes
2610 let mut err = tcx.sess.struct_span_err(span, msg);
2611 err.span_note(span_late, note);
2614 let mut multispan = MultiSpan::from_span(span);
2615 multispan.push_span_label(span_late, note.to_string());
2616 tcx.struct_span_lint_hir(
2617 LATE_BOUND_LIFETIME_ARGUMENTS,
2620 |lint| lint.build(msg).emit(),
2623 ExplicitLateBound::Yes
2625 ExplicitLateBound::No
2629 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2630 pub fn def_ids_for_value_path_segments(
2632 segments: &[hir::PathSegment<'_>],
2633 self_ty: Option<Ty<'tcx>>,
2637 // We need to extract the type parameters supplied by the user in
2638 // the path `path`. Due to the current setup, this is a bit of a
2639 // tricky-process; the problem is that resolve only tells us the
2640 // end-point of the path resolution, and not the intermediate steps.
2641 // Luckily, we can (at least for now) deduce the intermediate steps
2642 // just from the end-point.
2644 // There are basically five cases to consider:
2646 // 1. Reference to a constructor of a struct:
2648 // struct Foo<T>(...)
2650 // In this case, the parameters are declared in the type space.
2652 // 2. Reference to a constructor of an enum variant:
2654 // enum E<T> { Foo(...) }
2656 // In this case, the parameters are defined in the type space,
2657 // but may be specified either on the type or the variant.
2659 // 3. Reference to a fn item or a free constant:
2663 // In this case, the path will again always have the form
2664 // `a::b::foo::<T>` where only the final segment should have
2665 // type parameters. However, in this case, those parameters are
2666 // declared on a value, and hence are in the `FnSpace`.
2668 // 4. Reference to a method or an associated constant:
2670 // impl<A> SomeStruct<A> {
2674 // Here we can have a path like
2675 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2676 // may appear in two places. The penultimate segment,
2677 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2678 // final segment, `foo::<B>` contains parameters in fn space.
2680 // The first step then is to categorize the segments appropriately.
2682 let tcx = self.tcx();
2684 assert!(!segments.is_empty());
2685 let last = segments.len() - 1;
2687 let mut path_segs = vec![];
2690 // Case 1. Reference to a struct constructor.
2691 DefKind::Ctor(CtorOf::Struct, ..) => {
2692 // Everything but the final segment should have no
2693 // parameters at all.
2694 let generics = tcx.generics_of(def_id);
2695 // Variant and struct constructors use the
2696 // generics of their parent type definition.
2697 let generics_def_id = generics.parent.unwrap_or(def_id);
2698 path_segs.push(PathSeg(generics_def_id, last));
2701 // Case 2. Reference to a variant constructor.
2702 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2703 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2704 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2705 debug_assert!(adt_def.is_enum());
2707 } else if last >= 1 && segments[last - 1].args.is_some() {
2708 // Everything but the penultimate segment should have no
2709 // parameters at all.
2710 let mut def_id = def_id;
2712 // `DefKind::Ctor` -> `DefKind::Variant`
2713 if let DefKind::Ctor(..) = kind {
2714 def_id = tcx.parent(def_id).unwrap()
2717 // `DefKind::Variant` -> `DefKind::Enum`
2718 let enum_def_id = tcx.parent(def_id).unwrap();
2719 (enum_def_id, last - 1)
2721 // FIXME: lint here recommending `Enum::<...>::Variant` form
2722 // instead of `Enum::Variant::<...>` form.
2724 // Everything but the final segment should have no
2725 // parameters at all.
2726 let generics = tcx.generics_of(def_id);
2727 // Variant and struct constructors use the
2728 // generics of their parent type definition.
2729 (generics.parent.unwrap_or(def_id), last)
2731 path_segs.push(PathSeg(generics_def_id, index));
2734 // Case 3. Reference to a top-level value.
2735 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2736 path_segs.push(PathSeg(def_id, last));
2739 // Case 4. Reference to a method or associated const.
2740 DefKind::AssocFn | DefKind::AssocConst => {
2741 if segments.len() >= 2 {
2742 let generics = tcx.generics_of(def_id);
2743 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2745 path_segs.push(PathSeg(def_id, last));
2748 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2751 debug!("path_segs = {:?}", path_segs);
2756 // Check a type `Path` and convert it to a `Ty`.
2759 opt_self_ty: Option<Ty<'tcx>>,
2760 path: &hir::Path<'_>,
2761 permit_variants: bool,
2763 let tcx = self.tcx();
2766 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2767 path.res, opt_self_ty, path.segments
2770 let span = path.span;
2772 Res::Def(DefKind::OpaqueTy, did) => {
2773 // Check for desugared `impl Trait`.
2774 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2775 let item_segment = path.segments.split_last().unwrap();
2776 self.prohibit_generics(item_segment.1);
2777 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2778 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2785 | DefKind::ForeignTy,
2788 assert_eq!(opt_self_ty, None);
2789 self.prohibit_generics(path.segments.split_last().unwrap().1);
2790 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2792 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2793 // Convert "variant type" as if it were a real type.
2794 // The resulting `Ty` is type of the variant's enum for now.
2795 assert_eq!(opt_self_ty, None);
2798 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2799 let generic_segs: FxHashSet<_> =
2800 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2801 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2803 if !generic_segs.contains(&index) { Some(seg) } else { None }
2807 let PathSeg(def_id, index) = path_segs.last().unwrap();
2808 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2810 Res::Def(DefKind::TyParam, def_id) => {
2811 assert_eq!(opt_self_ty, None);
2812 self.prohibit_generics(path.segments);
2814 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
2815 let item_id = tcx.hir().get_parent_node(hir_id);
2816 let item_def_id = tcx.hir().local_def_id(item_id);
2817 let generics = tcx.generics_of(item_def_id);
2818 let index = generics.param_def_id_to_index[&def_id];
2819 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2821 Res::SelfTy(Some(_), None) => {
2822 // `Self` in trait or type alias.
2823 assert_eq!(opt_self_ty, None);
2824 self.prohibit_generics(path.segments);
2825 tcx.types.self_param
2827 Res::SelfTy(_, Some(def_id)) => {
2828 // `Self` in impl (we know the concrete type).
2829 assert_eq!(opt_self_ty, None);
2830 self.prohibit_generics(path.segments);
2831 // Try to evaluate any array length constants.
2832 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2834 Res::Def(DefKind::AssocTy, def_id) => {
2835 debug_assert!(path.segments.len() >= 2);
2836 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2841 &path.segments[path.segments.len() - 2],
2842 path.segments.last().unwrap(),
2845 Res::PrimTy(prim_ty) => {
2846 assert_eq!(opt_self_ty, None);
2847 self.prohibit_generics(path.segments);
2849 hir::PrimTy::Bool => tcx.types.bool,
2850 hir::PrimTy::Char => tcx.types.char,
2851 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2852 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2853 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2854 hir::PrimTy::Str => tcx.types.str_,
2858 self.set_tainted_by_errors();
2859 self.tcx().ty_error()
2861 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2865 /// Parses the programmer's textual representation of a type into our
2866 /// internal notion of a type.
2867 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2868 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2870 let tcx = self.tcx();
2872 let result_ty = match ast_ty.kind {
2873 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2874 hir::TyKind::Ptr(ref mt) => {
2875 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2877 hir::TyKind::Rptr(ref region, ref mt) => {
2878 let r = self.ast_region_to_region(region, None);
2879 debug!("ast_ty_to_ty: r={:?}", r);
2880 let t = self.ast_ty_to_ty(&mt.ty);
2881 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2883 hir::TyKind::Never => tcx.types.never,
2884 hir::TyKind::Tup(ref fields) => {
2885 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2887 hir::TyKind::BareFn(ref bf) => {
2888 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2889 tcx.mk_fn_ptr(self.ty_of_fn(
2893 &hir::Generics::empty(),
2897 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2898 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2900 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2901 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2902 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2903 self.res_to_ty(opt_self_ty, path, false)
2905 hir::TyKind::OpaqueDef(item_id, ref lifetimes) => {
2906 let opaque_ty = tcx.hir().expect_item(item_id.id);
2907 let def_id = tcx.hir().local_def_id(item_id.id).to_def_id();
2909 match opaque_ty.kind {
2910 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
2911 self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some())
2913 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2916 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2917 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2918 let ty = self.ast_ty_to_ty(qself);
2920 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2925 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2926 .map(|(ty, _, _)| ty)
2927 .unwrap_or_else(|_| tcx.ty_error())
2929 hir::TyKind::Array(ref ty, ref length) => {
2930 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2931 let length = ty::Const::from_anon_const(tcx, length_def_id);
2932 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2933 self.normalize_ty(ast_ty.span, array_ty)
2935 hir::TyKind::Typeof(ref _e) => {
2940 "`typeof` is a reserved keyword but unimplemented"
2942 .span_label(ast_ty.span, "reserved keyword")
2947 hir::TyKind::Infer => {
2948 // Infer also appears as the type of arguments or return
2949 // values in a ExprKind::Closure, or as
2950 // the type of local variables. Both of these cases are
2951 // handled specially and will not descend into this routine.
2952 self.ty_infer(None, ast_ty.span)
2954 hir::TyKind::Err => tcx.ty_error(),
2957 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2959 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2963 pub fn impl_trait_ty_to_ty(
2966 lifetimes: &[hir::GenericArg<'_>],
2967 replace_parent_lifetimes: bool,
2969 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2970 let tcx = self.tcx();
2972 let generics = tcx.generics_of(def_id);
2974 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2975 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2976 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2977 // Our own parameters are the resolved lifetimes.
2979 GenericParamDefKind::Lifetime => {
2980 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2981 self.ast_region_to_region(lifetime, None).into()
2990 // For RPIT (return position impl trait), only lifetimes
2991 // mentioned in the impl Trait predicate are captured by
2992 // the opaque type, so the lifetime parameters from the
2993 // parent item need to be replaced with `'static`.
2995 // For `impl Trait` in the types of statics, constants,
2996 // locals and type aliases. These capture all parent
2997 // lifetimes, so they can use their identity subst.
2998 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2999 tcx.lifetimes.re_static.into()
3001 _ => tcx.mk_param_from_def(param),
3005 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
3007 let ty = tcx.mk_opaque(def_id, substs);
3008 debug!("impl_trait_ty_to_ty: {}", ty);
3012 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
3014 hir::TyKind::Infer if expected_ty.is_some() => {
3015 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
3016 expected_ty.unwrap()
3018 _ => self.ast_ty_to_ty(ty),
3024 unsafety: hir::Unsafety,
3026 decl: &hir::FnDecl<'_>,
3027 generics: &hir::Generics<'_>,
3028 ident_span: Option<Span>,
3029 ) -> ty::PolyFnSig<'tcx> {
3032 let tcx = self.tcx();
3034 // We proactively collect all the inferred type params to emit a single error per fn def.
3035 let mut visitor = PlaceholderHirTyCollector::default();
3036 for ty in decl.inputs {
3037 visitor.visit_ty(ty);
3039 walk_generics(&mut visitor, generics);
3041 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
3042 let output_ty = match decl.output {
3043 hir::FnRetTy::Return(ref output) => {
3044 visitor.visit_ty(output);
3045 self.ast_ty_to_ty(output)
3047 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
3050 debug!("ty_of_fn: output_ty={:?}", output_ty);
3053 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
3055 if !self.allow_ty_infer() {
3056 // We always collect the spans for placeholder types when evaluating `fn`s, but we
3057 // only want to emit an error complaining about them if infer types (`_`) are not
3058 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
3059 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
3060 crate::collect::placeholder_type_error(
3062 ident_span.map(|sp| sp.shrink_to_hi()),
3063 &generics.params[..],
3069 // Find any late-bound regions declared in return type that do
3070 // not appear in the arguments. These are not well-formed.
3073 // for<'a> fn() -> &'a str <-- 'a is bad
3074 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3075 let inputs = bare_fn_ty.inputs();
3076 let late_bound_in_args =
3077 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
3078 let output = bare_fn_ty.output();
3079 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
3081 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3086 "return type references {}, which is not constrained by the fn input types",
3094 fn validate_late_bound_regions(
3096 constrained_regions: FxHashSet<ty::BoundRegion>,
3097 referenced_regions: FxHashSet<ty::BoundRegion>,
3098 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
3100 for br in referenced_regions.difference(&constrained_regions) {
3101 let br_name = match *br {
3102 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
3103 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
3106 let mut err = generate_err(&br_name);
3108 if let ty::BrAnon(_) = *br {
3109 // The only way for an anonymous lifetime to wind up
3110 // in the return type but **also** be unconstrained is
3111 // if it only appears in "associated types" in the
3112 // input. See #47511 and #62200 for examples. In this case,
3113 // though we can easily give a hint that ought to be
3116 "lifetimes appearing in an associated type are not considered constrained",
3124 /// Given the bounds on an object, determines what single region bound (if any) we can
3125 /// use to summarize this type. The basic idea is that we will use the bound the user
3126 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3127 /// for region bounds. It may be that we can derive no bound at all, in which case
3128 /// we return `None`.
3129 fn compute_object_lifetime_bound(
3132 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
3133 ) -> Option<ty::Region<'tcx>> // if None, use the default
3135 let tcx = self.tcx();
3137 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3139 // No explicit region bound specified. Therefore, examine trait
3140 // bounds and see if we can derive region bounds from those.
3141 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3143 // If there are no derived region bounds, then report back that we
3144 // can find no region bound. The caller will use the default.
3145 if derived_region_bounds.is_empty() {
3149 // If any of the derived region bounds are 'static, that is always
3151 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
3152 return Some(tcx.lifetimes.re_static);
3155 // Determine whether there is exactly one unique region in the set
3156 // of derived region bounds. If so, use that. Otherwise, report an
3158 let r = derived_region_bounds[0];
3159 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3164 "ambiguous lifetime bound, explicit lifetime bound required"
3172 /// Collects together a list of bounds that are applied to some type,
3173 /// after they've been converted into `ty` form (from the HIR
3174 /// representations). These lists of bounds occur in many places in
3178 /// trait Foo: Bar + Baz { }
3179 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
3181 /// fn foo<T: Bar + Baz>() { }
3182 /// ^^^^^^^^^ bounding the type parameter `T`
3184 /// impl dyn Bar + Baz
3185 /// ^^^^^^^^^ bounding the forgotten dynamic type
3188 /// Our representation is a bit mixed here -- in some cases, we
3189 /// include the self type (e.g., `trait_bounds`) but in others we do
3190 #[derive(Default, PartialEq, Eq, Clone, Debug)]
3191 pub struct Bounds<'tcx> {
3192 /// A list of region bounds on the (implicit) self type. So if you
3193 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
3194 /// the `T` is not explicitly included).
3195 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
3197 /// A list of trait bounds. So if you had `T: Debug` this would be
3198 /// `T: Debug`. Note that the self-type is explicit here.
3199 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>,
3201 /// A list of projection equality bounds. So if you had `T:
3202 /// Iterator<Item = u32>` this would include `<T as
3203 /// Iterator>::Item => u32`. Note that the self-type is explicit
3205 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
3207 /// `Some` if there is *no* `?Sized` predicate. The `span`
3208 /// is the location in the source of the `T` declaration which can
3209 /// be cited as the source of the `T: Sized` requirement.
3210 pub implicitly_sized: Option<Span>,
3213 impl<'tcx> Bounds<'tcx> {
3214 /// Converts a bounds list into a flat set of predicates (like
3215 /// where-clauses). Because some of our bounds listings (e.g.,
3216 /// regions) don't include the self-type, you must supply the
3217 /// self-type here (the `param_ty` parameter).
3222 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
3223 // If it could be sized, and is, add the `Sized` predicate.
3224 let sized_predicate = self.implicitly_sized.and_then(|span| {
3225 tcx.lang_items().sized_trait().map(|sized| {
3226 let trait_ref = ty::Binder::bind(ty::TraitRef {
3228 substs: tcx.mk_substs_trait(param_ty, &[]),
3230 (trait_ref.without_const().to_predicate(tcx), span)
3239 .map(|&(region_bound, span)| {
3240 // Account for the binder being introduced below; no need to shift `param_ty`
3241 // because, at present at least, it either only refers to early-bound regions,
3242 // or it's a generic associated type that deliberately has escaping bound vars.
3243 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
3244 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
3245 (ty::Binder::bind(outlives).to_predicate(tcx), span)
3247 .chain(self.trait_bounds.iter().map(|&(bound_trait_ref, span, constness)| {
3248 let predicate = bound_trait_ref.with_constness(constness).to_predicate(tcx);
3252 self.projection_bounds
3254 .map(|&(projection, span)| (projection.to_predicate(tcx), span)),