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;
12 use rustc_ast::util::lev_distance::find_best_match_for_name;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_errors::ErrorReported;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError};
17 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
18 use rustc_hir::def_id::{DefId, LocalDefId};
19 use rustc_hir::intravisit::{walk_generics, Visitor as _};
20 use rustc_hir::lang_items::SizedTraitLangItem;
21 use rustc_hir::{Constness, GenericArg, GenericArgs};
22 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
23 use rustc_middle::ty::{
24 self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
26 use rustc_middle::ty::{GenericParamDef, GenericParamDefKind};
27 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS};
28 use rustc_session::parse::feature_err;
29 use rustc_session::Session;
30 use rustc_span::symbol::{sym, Ident, Symbol};
31 use rustc_span::{MultiSpan, Span, DUMMY_SP};
32 use rustc_target::spec::abi;
33 use rustc_trait_selection::traits;
34 use rustc_trait_selection::traits::astconv_object_safety_violations;
35 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
36 use rustc_trait_selection::traits::wf::object_region_bounds;
38 use smallvec::SmallVec;
39 use std::collections::BTreeSet;
44 pub struct PathSeg(pub DefId, pub usize);
46 pub trait AstConv<'tcx> {
47 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
49 fn item_def_id(&self) -> Option<DefId>;
51 fn default_constness_for_trait_bounds(&self) -> Constness;
53 /// Returns predicates in scope of the form `X: Foo`, where `X` is
54 /// a type parameter `X` with the given id `def_id`. This is a
55 /// subset of the full set of predicates.
57 /// This is used for one specific purpose: resolving "short-hand"
58 /// associated type references like `T::Item`. In principle, we
59 /// would do that by first getting the full set of predicates in
60 /// scope and then filtering down to find those that apply to `T`,
61 /// but this can lead to cycle errors. The problem is that we have
62 /// to do this resolution *in order to create the predicates in
63 /// the first place*. Hence, we have this "special pass".
64 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
66 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
67 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
68 -> Option<ty::Region<'tcx>>;
70 /// Returns the type to use when a type is omitted.
71 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
73 /// Returns `true` if `_` is allowed in type signatures in the current context.
74 fn allow_ty_infer(&self) -> bool;
76 /// Returns the const to use when a const is omitted.
80 param: Option<&ty::GenericParamDef>,
82 ) -> &'tcx Const<'tcx>;
84 /// Projecting an associated type from a (potentially)
85 /// higher-ranked trait reference is more complicated, because of
86 /// the possibility of late-bound regions appearing in the
87 /// associated type binding. This is not legal in function
88 /// signatures for that reason. In a function body, we can always
89 /// handle it because we can use inference variables to remove the
90 /// late-bound regions.
91 fn projected_ty_from_poly_trait_ref(
95 item_segment: &hir::PathSegment<'_>,
96 poly_trait_ref: ty::PolyTraitRef<'tcx>,
99 /// Normalize an associated type coming from the user.
100 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
102 /// Invoked when we encounter an error from some prior pass
103 /// (e.g., resolve) that is translated into a ty-error. This is
104 /// used to help suppress derived errors typeck might otherwise
106 fn set_tainted_by_errors(&self);
108 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
111 pub enum SizedByDefault {
116 struct ConvertedBinding<'a, 'tcx> {
118 kind: ConvertedBindingKind<'a, 'tcx>,
122 enum ConvertedBindingKind<'a, 'tcx> {
124 Constraint(&'a [hir::GenericBound<'a>]),
127 /// New-typed boolean indicating whether explicit late-bound lifetimes
128 /// are present in a set of generic arguments.
130 /// For example if we have some method `fn f<'a>(&'a self)` implemented
131 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
132 /// is late-bound so should not be provided explicitly. Thus, if `f` is
133 /// instantiated with some generic arguments providing `'a` explicitly,
134 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
135 /// can provide an appropriate diagnostic later.
136 #[derive(Copy, Clone, PartialEq)]
137 pub enum ExplicitLateBound {
142 #[derive(Copy, Clone, PartialEq)]
143 enum GenericArgPosition {
145 Value, // e.g., functions
149 /// A marker denoting that the generic arguments that were
150 /// provided did not match the respective generic parameters.
151 #[derive(Clone, Default)]
152 pub struct GenericArgCountMismatch {
153 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
154 pub reported: Option<ErrorReported>,
155 /// A list of spans of arguments provided that were not valid.
156 pub invalid_args: Vec<Span>,
159 /// Decorates the result of a generic argument count mismatch
160 /// check with whether explicit late bounds were provided.
162 pub struct GenericArgCountResult {
163 pub explicit_late_bound: ExplicitLateBound,
164 pub correct: Result<(), GenericArgCountMismatch>,
167 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
168 pub fn ast_region_to_region(
170 lifetime: &hir::Lifetime,
171 def: Option<&ty::GenericParamDef>,
172 ) -> ty::Region<'tcx> {
173 let tcx = self.tcx();
174 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id));
176 let r = match tcx.named_region(lifetime.hir_id) {
177 Some(rl::Region::Static) => tcx.lifetimes.re_static,
179 Some(rl::Region::LateBound(debruijn, id, _)) => {
180 let name = lifetime_name(id.expect_local());
181 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
184 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
185 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
188 Some(rl::Region::EarlyBound(index, id, _)) => {
189 let name = lifetime_name(id.expect_local());
190 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
193 Some(rl::Region::Free(scope, id)) => {
194 let name = lifetime_name(id.expect_local());
195 tcx.mk_region(ty::ReFree(ty::FreeRegion {
197 bound_region: ty::BrNamed(id, name),
200 // (*) -- not late-bound, won't change
204 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
205 // This indicates an illegal lifetime
206 // elision. `resolve_lifetime` should have
207 // reported an error in this case -- but if
208 // not, let's error out.
209 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
211 // Supply some dummy value. We don't have an
212 // `re_error`, annoyingly, so use `'static`.
213 tcx.lifetimes.re_static
218 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
223 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
224 /// returns an appropriate set of substitutions for this particular reference to `I`.
225 pub fn ast_path_substs_for_ty(
229 item_segment: &hir::PathSegment<'_>,
230 ) -> SubstsRef<'tcx> {
231 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
235 item_segment.generic_args(),
236 item_segment.infer_args,
240 if let Some(b) = assoc_bindings.first() {
241 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
247 /// Report error if there is an explicit type parameter when using `impl Trait`.
250 seg: &hir::PathSegment<'_>,
251 generics: &ty::Generics,
253 let explicit = !seg.infer_args;
254 let impl_trait = generics.params.iter().any(|param| match param.kind {
255 ty::GenericParamDefKind::Type {
256 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
262 if explicit && impl_trait {
267 .filter_map(|arg| match arg {
268 GenericArg::Type(_) => Some(arg.span()),
271 .collect::<Vec<_>>();
273 let mut err = struct_span_err! {
277 "cannot provide explicit generic arguments when `impl Trait` is \
278 used in argument position"
282 err.span_label(span, "explicit generic argument not allowed");
291 /// Checks that the correct number of generic arguments have been provided.
292 /// Used specifically for function calls.
293 pub fn check_generic_arg_count_for_call(
297 seg: &hir::PathSegment<'_>,
298 is_method_call: bool,
299 ) -> GenericArgCountResult {
300 let empty_args = hir::GenericArgs::none();
301 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
302 Self::check_generic_arg_count(
306 if let Some(ref args) = seg.args { args } else { &empty_args },
307 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
308 def.parent.is_none() && def.has_self, // `has_self`
309 seg.infer_args || suppress_mismatch, // `infer_args`
313 /// Checks that the correct number of generic arguments have been provided.
314 /// This is used both for datatypes and function calls.
315 fn check_generic_arg_count(
319 args: &hir::GenericArgs<'_>,
320 position: GenericArgPosition,
323 ) -> GenericArgCountResult {
324 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
325 // that lifetimes will proceed types. So it suffices to check the number of each generic
326 // arguments in order to validate them with respect to the generic parameters.
327 let param_counts = def.own_counts();
328 let arg_counts = args.own_counts();
329 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
331 let mut defaults: ty::GenericParamCount = Default::default();
332 for param in &def.params {
334 GenericParamDefKind::Lifetime => {}
335 GenericParamDefKind::Type { has_default, .. } => {
336 defaults.types += has_default as usize
338 GenericParamDefKind::Const => {
339 // FIXME(const_generics:defaults)
344 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
345 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
348 let explicit_late_bound =
349 Self::prohibit_explicit_late_bound_lifetimes(tcx, def, args, position);
351 let check_kind_count = |kind,
356 unexpected_spans: &mut Vec<Span>,
359 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
360 kind, required, permitted, provided, offset
362 // We enforce the following: `required` <= `provided` <= `permitted`.
363 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
364 // For other kinds (i.e., types), `permitted` may be greater than `required`.
365 if required <= provided && provided <= permitted {
373 // Unfortunately lifetime and type parameter mismatches are typically styled
374 // differently in diagnostics, which means we have a few cases to consider here.
375 let (bound, quantifier) = if required != permitted {
376 if provided < required {
377 (required, "at least ")
379 // provided > permitted
380 (permitted, "at most ")
386 let (spans, label) = if required == permitted && provided > permitted {
387 // In the case when the user has provided too many arguments,
388 // we want to point to the unexpected arguments.
389 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
391 .map(|arg| arg.span())
393 unexpected_spans.extend(spans.clone());
394 (spans, format!("unexpected {} argument", kind))
399 "expected {}{} {} argument{}",
408 let mut err = tcx.sess.struct_span_err_with_code(
411 "wrong number of {} arguments: expected {}{}, found {}",
412 kind, quantifier, bound, provided,
414 DiagnosticId::Error("E0107".into()),
417 err.span_label(span, label.as_str());
424 let mut arg_count_correct = Ok(());
425 let mut unexpected_spans = vec![];
427 if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
428 arg_count_correct = check_kind_count(
430 param_counts.lifetimes,
431 param_counts.lifetimes,
432 arg_counts.lifetimes,
434 &mut unexpected_spans,
435 explicit_late_bound == ExplicitLateBound::Yes,
437 .and(arg_count_correct);
439 // FIXME(const_generics:defaults)
440 if !infer_args || arg_counts.consts > param_counts.consts {
441 arg_count_correct = check_kind_count(
446 arg_counts.lifetimes + arg_counts.types,
447 &mut unexpected_spans,
450 .and(arg_count_correct);
452 // Note that type errors are currently be emitted *after* const errors.
453 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
455 arg_count_correct = check_kind_count(
457 param_counts.types - defaults.types - has_self as usize,
458 param_counts.types - has_self as usize,
460 arg_counts.lifetimes,
461 &mut unexpected_spans,
464 .and(arg_count_correct);
467 GenericArgCountResult {
469 correct: arg_count_correct.map_err(|reported_err| GenericArgCountMismatch {
470 reported: if reported_err { Some(ErrorReported) } else { None },
471 invalid_args: unexpected_spans,
476 /// Report an error that a generic argument did not match the generic parameter that was
478 fn generic_arg_mismatch_err(sess: &Session, arg: &GenericArg<'_>, kind: &'static str) {
479 let mut err = struct_span_err!(
483 "{} provided when a {} was expected",
488 let kind_ord = match kind {
489 "lifetime" => ParamKindOrd::Lifetime,
490 "type" => ParamKindOrd::Type,
491 "constant" => ParamKindOrd::Const,
492 // It's more concise to match on the string representation, though it means
493 // the match is non-exhaustive.
494 _ => bug!("invalid generic parameter kind {}", kind),
496 let arg_ord = match arg {
497 GenericArg::Lifetime(_) => ParamKindOrd::Lifetime,
498 GenericArg::Type(_) => ParamKindOrd::Type,
499 GenericArg::Const(_) => ParamKindOrd::Const,
502 // This note will be true as long as generic parameters are strictly ordered by their kind.
504 if kind_ord < arg_ord { (kind, arg.descr()) } else { (arg.descr(), kind) };
505 err.note(&format!("{} arguments must be provided before {} arguments", first, last));
509 /// Creates the relevant generic argument substitutions
510 /// corresponding to a set of generic parameters. This is a
511 /// rather complex function. Let us try to explain the role
512 /// of each of its parameters:
514 /// To start, we are given the `def_id` of the thing we are
515 /// creating the substitutions for, and a partial set of
516 /// substitutions `parent_substs`. In general, the substitutions
517 /// for an item begin with substitutions for all the "parents" of
518 /// that item -- e.g., for a method it might include the
519 /// parameters from the impl.
521 /// Therefore, the method begins by walking down these parents,
522 /// starting with the outermost parent and proceed inwards until
523 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
524 /// first to see if the parent's substitutions are listed in there. If so,
525 /// we can append those and move on. Otherwise, it invokes the
526 /// three callback functions:
528 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
529 /// generic arguments that were given to that parent from within
530 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
531 /// might refer to the trait `Foo`, and the arguments might be
532 /// `[T]`. The boolean value indicates whether to infer values
533 /// for arguments whose values were not explicitly provided.
534 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
535 /// instantiate a `GenericArg`.
536 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
537 /// creates a suitable inference variable.
538 pub fn create_substs_for_generic_args<'b>(
541 parent_substs: &[subst::GenericArg<'tcx>],
543 self_ty: Option<Ty<'tcx>>,
544 arg_count: GenericArgCountResult,
545 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
546 mut provided_kind: impl FnMut(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
547 mut inferred_kind: impl FnMut(
548 Option<&[subst::GenericArg<'tcx>]>,
551 ) -> subst::GenericArg<'tcx>,
552 ) -> SubstsRef<'tcx> {
553 // Collect the segments of the path; we need to substitute arguments
554 // for parameters throughout the entire path (wherever there are
555 // generic parameters).
556 let mut parent_defs = tcx.generics_of(def_id);
557 let count = parent_defs.count();
558 let mut stack = vec![(def_id, parent_defs)];
559 while let Some(def_id) = parent_defs.parent {
560 parent_defs = tcx.generics_of(def_id);
561 stack.push((def_id, parent_defs));
564 // We manually build up the substitution, rather than using convenience
565 // methods in `subst.rs`, so that we can iterate over the arguments and
566 // parameters in lock-step linearly, instead of trying to match each pair.
567 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
568 // Iterate over each segment of the path.
569 while let Some((def_id, defs)) = stack.pop() {
570 let mut params = defs.params.iter().peekable();
572 // If we have already computed substitutions for parents, we can use those directly.
573 while let Some(¶m) = params.peek() {
574 if let Some(&kind) = parent_substs.get(param.index as usize) {
582 // `Self` is handled first, unless it's been handled in `parent_substs`.
584 if let Some(¶m) = params.peek() {
585 if param.index == 0 {
586 if let GenericParamDefKind::Type { .. } = param.kind {
590 .unwrap_or_else(|| inferred_kind(None, param, true)),
598 // Check whether this segment takes generic arguments and the user has provided any.
599 let (generic_args, infer_args) = args_for_def_id(def_id);
602 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
604 // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
605 // If we later encounter a lifetime, we know that the arguments were provided in the
606 // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
607 // inferred, so we can use it for diagnostics later.
608 let mut force_infer_lt = None;
611 // We're going to iterate through the generic arguments that the user
612 // provided, matching them with the generic parameters we expect.
613 // Mismatches can occur as a result of elided lifetimes, or for malformed
614 // input. We try to handle both sensibly.
615 match (args.peek(), params.peek()) {
616 (Some(&arg), Some(¶m)) => {
617 match (arg, ¶m.kind, arg_count.explicit_late_bound) {
618 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
619 | (GenericArg::Type(_), GenericParamDefKind::Type { .. }, _)
620 | (GenericArg::Const(_), GenericParamDefKind::Const, _) => {
621 substs.push(provided_kind(param, arg));
626 GenericArg::Type(_) | GenericArg::Const(_),
627 GenericParamDefKind::Lifetime,
630 // We expected a lifetime argument, but got a type or const
631 // argument. That means we're inferring the lifetimes.
632 substs.push(inferred_kind(None, param, infer_args));
633 force_infer_lt = Some(arg);
636 (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
637 // We've come across a lifetime when we expected something else in
638 // the presence of explicit late bounds. This is most likely
639 // due to the presence of the explicit bound so we're just going to
644 // We expected one kind of parameter, but the user provided
645 // another. This is an error. However, if we already know that
646 // the arguments don't match up with the parameters, we won't issue
647 // an additional error, as the user already knows what's wrong.
648 if arg_count.correct.is_ok()
649 && arg_count.explicit_late_bound == ExplicitLateBound::No
651 Self::generic_arg_mismatch_err(tcx.sess, arg, kind.descr());
654 // We've reported the error, but we want to make sure that this
655 // problem doesn't bubble down and create additional, irrelevant
656 // errors. In this case, we're simply going to ignore the argument
657 // and any following arguments. The rest of the parameters will be
659 while args.next().is_some() {}
664 (Some(&arg), None) => {
665 // We should never be able to reach this point with well-formed input.
666 // There are three situations in which we can encounter this issue.
668 // 1. The number of arguments is incorrect. In this case, an error
669 // will already have been emitted, and we can ignore it.
670 // 2. There are late-bound lifetime parameters present, yet the
671 // lifetime arguments have also been explicitly specified by the
673 // 3. We've inferred some lifetimes, which have been provided later (i.e.
674 // after a type or const). We want to throw an error in this case.
676 if arg_count.correct.is_ok()
677 && arg_count.explicit_late_bound == ExplicitLateBound::No
679 let kind = arg.descr();
680 assert_eq!(kind, "lifetime");
682 force_infer_lt.expect("lifetimes ought to have been inferred");
683 Self::generic_arg_mismatch_err(tcx.sess, provided, kind);
689 (None, Some(¶m)) => {
690 // If there are fewer arguments than parameters, it means
691 // we're inferring the remaining arguments.
692 substs.push(inferred_kind(Some(&substs), param, infer_args));
696 (None, None) => break,
701 tcx.intern_substs(&substs)
704 /// Given the type/lifetime/const arguments provided to some path (along with
705 /// an implicit `Self`, if this is a trait reference), returns the complete
706 /// set of substitutions. This may involve applying defaulted type parameters.
707 /// Also returns back constraints on associated types.
712 /// T: std::ops::Index<usize, Output = u32>
713 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
716 /// 1. The `self_ty` here would refer to the type `T`.
717 /// 2. The path in question is the path to the trait `std::ops::Index`,
718 /// which will have been resolved to a `def_id`
719 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
720 /// parameters are returned in the `SubstsRef`, the associated type bindings like
721 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
723 /// Note that the type listing given here is *exactly* what the user provided.
725 /// For (generic) associated types
728 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
731 /// We have the parent substs are the substs for the parent trait:
732 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
733 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
734 /// lists: `[Vec<u8>, u8, 'a]`.
735 fn create_substs_for_ast_path<'a>(
739 parent_substs: &[subst::GenericArg<'tcx>],
740 generic_args: &'a hir::GenericArgs<'_>,
742 self_ty: Option<Ty<'tcx>>,
743 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
744 // If the type is parameterized by this region, then replace this
745 // region with the current anon region binding (in other words,
746 // whatever & would get replaced with).
748 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
750 def_id, self_ty, generic_args
753 let tcx = self.tcx();
754 let generic_params = tcx.generics_of(def_id);
756 if generic_params.has_self {
757 if generic_params.parent.is_some() {
758 // The parent is a trait so it should have at least one subst
759 // for the `Self` type.
760 assert!(!parent_substs.is_empty())
762 // This item (presumably a trait) needs a self-type.
763 assert!(self_ty.is_some());
766 assert!(self_ty.is_none() && parent_substs.is_empty());
769 let arg_count = Self::check_generic_arg_count(
774 GenericArgPosition::Type,
779 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
780 let default_needs_object_self = |param: &ty::GenericParamDef| {
781 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
782 if is_object && has_default {
783 let default_ty = tcx.at(span).type_of(param.def_id);
784 let self_param = tcx.types.self_param;
785 if default_ty.walk().any(|arg| arg == self_param.into()) {
786 // There is no suitable inference default for a type parameter
787 // that references self, in an object type.
796 let mut missing_type_params = vec![];
797 let mut inferred_params = vec![];
798 let substs = Self::create_substs_for_generic_args(
805 // Provide the generic args, and whether types should be inferred.
808 (Some(generic_args), infer_args)
810 // The last component of this tuple is unimportant.
814 // Provide substitutions for parameters for which (valid) arguments have been provided.
815 |param, arg| match (¶m.kind, arg) {
816 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
817 self.ast_region_to_region(<, Some(param)).into()
819 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
820 if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
821 inferred_params.push(ty.span);
824 self.ast_ty_to_ty(&ty).into()
827 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
828 let ct_def_id = tcx.hir().local_def_id(ct.value.hir_id);
829 ty::Const::from_anon_const(tcx, ct_def_id).into()
833 // Provide substitutions for parameters for which arguments are inferred.
834 |substs, param, infer_args| {
836 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
837 GenericParamDefKind::Type { has_default, .. } => {
838 if !infer_args && has_default {
839 // No type parameter provided, but a default exists.
841 // If we are converting an object type, then the
842 // `Self` parameter is unknown. However, some of the
843 // other type parameters may reference `Self` in their
844 // defaults. This will lead to an ICE if we are not
846 if default_needs_object_self(param) {
847 missing_type_params.push(param.name.to_string());
850 // This is a default type parameter.
853 tcx.at(span).type_of(param.def_id).subst_spanned(
861 } else if infer_args {
862 // No type parameters were provided, we can infer all.
864 if !default_needs_object_self(param) { Some(param) } else { None };
865 self.ty_infer(param, span).into()
867 // We've already errored above about the mismatch.
871 GenericParamDefKind::Const => {
872 let ty = tcx.at(span).type_of(param.def_id);
873 // FIXME(const_generics:defaults)
875 // No const parameters were provided, we can infer all.
876 self.ct_infer(ty, Some(param), span).into()
878 // We've already errored above about the mismatch.
879 tcx.mk_const(ty::Const { val: ty::ConstKind::Error, ty }).into()
886 self.complain_about_missing_type_params(
890 generic_args.args.is_empty(),
893 // Convert associated-type bindings or constraints into a separate vector.
894 // Example: Given this:
896 // T: Iterator<Item = u32>
898 // The `T` is passed in as a self-type; the `Item = u32` is
899 // not a "type parameter" of the `Iterator` trait, but rather
900 // a restriction on `<T as Iterator>::Item`, so it is passed
902 let assoc_bindings = generic_args
906 let kind = match binding.kind {
907 hir::TypeBindingKind::Equality { ref ty } => {
908 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
910 hir::TypeBindingKind::Constraint { ref bounds } => {
911 ConvertedBindingKind::Constraint(bounds)
914 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
919 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
920 generic_params, self_ty, substs
923 (substs, assoc_bindings, arg_count)
926 crate fn create_substs_for_associated_item(
931 item_segment: &hir::PathSegment<'_>,
932 parent_substs: SubstsRef<'tcx>,
933 ) -> SubstsRef<'tcx> {
934 if tcx.generics_of(item_def_id).params.is_empty() {
935 self.prohibit_generics(slice::from_ref(item_segment));
939 self.create_substs_for_ast_path(
943 item_segment.generic_args(),
944 item_segment.infer_args,
951 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
952 /// the type parameter's name as a placeholder.
953 fn complain_about_missing_type_params(
955 missing_type_params: Vec<String>,
958 empty_generic_args: bool,
960 if missing_type_params.is_empty() {
964 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
965 let mut err = struct_span_err!(
969 "the type parameter{} {} must be explicitly specified",
970 pluralize!(missing_type_params.len()),
974 self.tcx().def_span(def_id),
976 "type parameter{} {} must be specified for this",
977 pluralize!(missing_type_params.len()),
981 let mut suggested = false;
982 if let (Ok(snippet), true) = (
983 self.tcx().sess.source_map().span_to_snippet(span),
984 // Don't suggest setting the type params if there are some already: the order is
985 // tricky to get right and the user will already know what the syntax is.
988 if snippet.ends_with('>') {
989 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
990 // we would have to preserve the right order. For now, as clearly the user is
991 // aware of the syntax, we do nothing.
993 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
994 // least we can clue them to the correct syntax `Iterator<Type>`.
998 "set the type parameter{plural} to the desired type{plural}",
999 plural = pluralize!(missing_type_params.len()),
1001 format!("{}<{}>", snippet, missing_type_params.join(", ")),
1002 Applicability::HasPlaceholders,
1011 "missing reference{} to {}",
1012 pluralize!(missing_type_params.len()),
1018 "because of the default `Self` reference, type parameters must be \
1019 specified on object types",
1024 /// Instantiates the path for the given trait reference, assuming that it's
1025 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
1026 /// The type _cannot_ be a type other than a trait type.
1028 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
1029 /// are disallowed. Otherwise, they are pushed onto the vector given.
1030 pub fn instantiate_mono_trait_ref(
1032 trait_ref: &hir::TraitRef<'_>,
1034 ) -> ty::TraitRef<'tcx> {
1035 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1037 self.ast_path_to_mono_trait_ref(
1038 trait_ref.path.span,
1039 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
1041 trait_ref.path.segments.last().unwrap(),
1045 /// The given trait-ref must actually be a trait.
1046 pub(super) fn instantiate_poly_trait_ref_inner(
1048 trait_ref: &hir::TraitRef<'_>,
1050 constness: Constness,
1052 bounds: &mut Bounds<'tcx>,
1054 ) -> GenericArgCountResult {
1055 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
1057 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
1059 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1061 let (substs, assoc_bindings, arg_count) = self.create_substs_for_ast_trait_ref(
1062 trait_ref.path.span,
1065 trait_ref.path.segments.last().unwrap(),
1067 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
1069 bounds.trait_bounds.push((poly_trait_ref, span, constness));
1071 let mut dup_bindings = FxHashMap::default();
1072 for binding in &assoc_bindings {
1073 // Specify type to assert that error was already reported in `Err` case.
1074 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
1075 trait_ref.hir_ref_id,
1083 // Okay to ignore `Err` because of `ErrorReported` (see above).
1087 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
1088 trait_ref, bounds, poly_trait_ref
1094 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
1095 /// a full trait reference. The resulting trait reference is returned. This may also generate
1096 /// auxiliary bounds, which are added to `bounds`.
1101 /// poly_trait_ref = Iterator<Item = u32>
1105 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
1107 /// **A note on binders:** against our usual convention, there is an implied bounder around
1108 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
1109 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
1110 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
1111 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
1113 pub fn instantiate_poly_trait_ref(
1115 poly_trait_ref: &hir::PolyTraitRef<'_>,
1116 constness: Constness,
1118 bounds: &mut Bounds<'tcx>,
1119 ) -> GenericArgCountResult {
1120 self.instantiate_poly_trait_ref_inner(
1121 &poly_trait_ref.trait_ref,
1122 poly_trait_ref.span,
1130 fn ast_path_to_mono_trait_ref(
1133 trait_def_id: DefId,
1135 trait_segment: &hir::PathSegment<'_>,
1136 ) -> ty::TraitRef<'tcx> {
1137 let (substs, assoc_bindings, _) =
1138 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1139 if let Some(b) = assoc_bindings.first() {
1140 AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span);
1142 ty::TraitRef::new(trait_def_id, substs)
1145 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1146 /// an error and attempt to build a reasonable structured suggestion.
1147 fn complain_about_internal_fn_trait(
1150 trait_def_id: DefId,
1151 trait_segment: &'a hir::PathSegment<'a>,
1153 let trait_def = self.tcx().trait_def(trait_def_id);
1155 if !self.tcx().features().unboxed_closures
1156 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1158 let sess = &self.tcx().sess.parse_sess;
1159 // For now, require that parenthetical notation be used only with `Fn()` etc.
1160 let (msg, sugg) = if trait_def.paren_sugar {
1162 "the precise format of `Fn`-family traits' type parameters is subject to \
1166 trait_segment.ident,
1170 .and_then(|args| args.args.get(0))
1171 .and_then(|arg| match arg {
1172 hir::GenericArg::Type(ty) => match ty.kind {
1173 hir::TyKind::Tup(t) => t
1175 .map(|e| sess.source_map().span_to_snippet(e.span))
1176 .collect::<Result<Vec<_>, _>>()
1177 .map(|a| a.join(", ")),
1178 _ => sess.source_map().span_to_snippet(ty.span),
1180 .map(|s| format!("({})", s))
1184 .unwrap_or_else(|| "()".to_string()),
1189 .find_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1190 (true, hir::TypeBindingKind::Equality { ty }) => {
1191 sess.source_map().span_to_snippet(ty.span).ok()
1195 .unwrap_or_else(|| "()".to_string()),
1199 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1201 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1202 if let Some(sugg) = sugg {
1203 let msg = "use parenthetical notation instead";
1204 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1210 fn create_substs_for_ast_trait_ref<'a>(
1213 trait_def_id: DefId,
1215 trait_segment: &'a hir::PathSegment<'a>,
1216 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
1217 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1219 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1221 self.create_substs_for_ast_path(
1225 trait_segment.generic_args(),
1226 trait_segment.infer_args,
1231 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
1233 .associated_items(trait_def_id)
1234 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
1238 // Returns `true` if a bounds list includes `?Sized`.
1239 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1240 let tcx = self.tcx();
1242 // Try to find an unbound in bounds.
1243 let mut unbound = None;
1244 for ab in ast_bounds {
1245 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1246 if unbound.is_none() {
1247 unbound = Some(&ptr.trait_ref);
1253 "type parameter has more than one relaxed default \
1254 bound, only one is supported"
1261 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1264 // FIXME(#8559) currently requires the unbound to be built-in.
1265 if let Ok(kind_id) = kind_id {
1266 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1269 "default bound relaxed for a type parameter, but \
1270 this does nothing because the given bound is not \
1271 a default; only `?Sized` is supported",
1276 _ if kind_id.is_ok() => {
1279 // No lang item for `Sized`, so we can't add it as a bound.
1286 /// This helper takes a *converted* parameter type (`param_ty`)
1287 /// and an *unconverted* list of bounds:
1290 /// fn foo<T: Debug>
1291 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1293 /// `param_ty`, in ty form
1296 /// It adds these `ast_bounds` into the `bounds` structure.
1298 /// **A note on binders:** there is an implied binder around
1299 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1300 /// for more details.
1304 ast_bounds: &[hir::GenericBound<'_>],
1305 bounds: &mut Bounds<'tcx>,
1307 let mut trait_bounds = Vec::new();
1308 let mut region_bounds = Vec::new();
1310 let constness = self.default_constness_for_trait_bounds();
1311 for ast_bound in ast_bounds {
1313 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1314 trait_bounds.push((b, constness))
1316 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
1317 trait_bounds.push((b, Constness::NotConst))
1319 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1320 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1324 for (bound, constness) in trait_bounds {
1325 let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
1328 bounds.region_bounds.extend(
1329 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1333 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1334 /// The self-type for the bounds is given by `param_ty`.
1339 /// fn foo<T: Bar + Baz>() { }
1340 /// ^ ^^^^^^^^^ ast_bounds
1344 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1345 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1346 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1348 /// `span` should be the declaration size of the parameter.
1349 pub fn compute_bounds(
1352 ast_bounds: &[hir::GenericBound<'_>],
1353 sized_by_default: SizedByDefault,
1356 let mut bounds = Bounds::default();
1358 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1359 bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
1361 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1362 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1370 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1373 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1374 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1375 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1376 fn add_predicates_for_ast_type_binding(
1378 hir_ref_id: hir::HirId,
1379 trait_ref: ty::PolyTraitRef<'tcx>,
1380 binding: &ConvertedBinding<'_, 'tcx>,
1381 bounds: &mut Bounds<'tcx>,
1383 dup_bindings: &mut FxHashMap<DefId, Span>,
1385 ) -> Result<(), ErrorReported> {
1386 let tcx = self.tcx();
1389 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1390 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1391 // subtle in the event that `T` is defined in a supertrait of
1392 // `SomeTrait`, because in that case we need to upcast.
1394 // That is, consider this case:
1397 // trait SubTrait: SuperTrait<int> { }
1398 // trait SuperTrait<A> { type T; }
1400 // ... B: SubTrait<T = foo> ...
1403 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1405 // Find any late-bound regions declared in `ty` that are not
1406 // declared in the trait-ref. These are not well-formed.
1410 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1411 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1412 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1413 let late_bound_in_trait_ref =
1414 tcx.collect_constrained_late_bound_regions(&trait_ref);
1415 let late_bound_in_ty =
1416 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1417 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1418 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1419 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1420 let br_name = match *br {
1421 ty::BrNamed(_, name) => name,
1425 "anonymous bound region {:?} in binding but not trait ref",
1430 // FIXME: point at the type params that don't have appropriate lifetimes:
1431 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1432 // ---- ---- ^^^^^^^
1437 "binding for associated type `{}` references lifetime `{}`, \
1438 which does not appear in the trait input types",
1448 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1449 // Simple case: X is defined in the current trait.
1452 // Otherwise, we have to walk through the supertraits to find
1454 self.one_bound_for_assoc_type(
1455 || traits::supertraits(tcx, trait_ref),
1456 || trait_ref.print_only_trait_path().to_string(),
1459 || match binding.kind {
1460 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1466 let (assoc_ident, def_scope) =
1467 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1469 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1470 // of calling `filter_by_name_and_kind`.
1472 .associated_items(candidate.def_id())
1473 .filter_by_name_unhygienic(assoc_ident.name)
1475 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1477 .expect("missing associated type");
1479 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1483 &format!("associated type `{}` is private", binding.item_name),
1485 .span_label(binding.span, "private associated type")
1488 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1492 .entry(assoc_ty.def_id)
1493 .and_modify(|prev_span| {
1498 "the value of the associated type `{}` (from trait `{}`) \
1499 is already specified",
1501 tcx.def_path_str(assoc_ty.container.id())
1503 .span_label(binding.span, "re-bound here")
1504 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1507 .or_insert(binding.span);
1510 match binding.kind {
1511 ConvertedBindingKind::Equality(ref ty) => {
1512 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1513 // the "projection predicate" for:
1515 // `<T as Iterator>::Item = u32`
1516 bounds.projection_bounds.push((
1517 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1518 projection_ty: ty::ProjectionTy::from_ref_and_name(
1528 ConvertedBindingKind::Constraint(ast_bounds) => {
1529 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1531 // `<T as Iterator>::Item: Debug`
1533 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1534 // parameter to have a skipped binder.
1535 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1536 self.add_bounds(param_ty, ast_bounds, bounds);
1546 item_segment: &hir::PathSegment<'_>,
1548 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1549 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1552 fn conv_object_ty_poly_trait_ref(
1555 trait_bounds: &[hir::PolyTraitRef<'_>],
1556 lifetime: &hir::Lifetime,
1558 let tcx = self.tcx();
1560 let mut bounds = Bounds::default();
1561 let mut potential_assoc_types = Vec::new();
1562 let dummy_self = self.tcx().types.trait_object_dummy_self;
1563 for trait_bound in trait_bounds.iter().rev() {
1564 if let GenericArgCountResult {
1566 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1568 } = self.instantiate_poly_trait_ref(
1570 Constness::NotConst,
1574 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1578 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1579 // is used and no 'maybe' bounds are used.
1580 let expanded_traits =
1581 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1582 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1583 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1584 if regular_traits.len() > 1 {
1585 let first_trait = ®ular_traits[0];
1586 let additional_trait = ®ular_traits[1];
1587 let mut err = struct_span_err!(
1589 additional_trait.bottom().1,
1591 "only auto traits can be used as additional traits in a trait object"
1593 additional_trait.label_with_exp_info(
1595 "additional non-auto trait",
1598 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1602 if regular_traits.is_empty() && auto_traits.is_empty() {
1607 "at least one trait is required for an object type"
1610 return tcx.types.err;
1613 // Check that there are no gross object safety violations;
1614 // most importantly, that the supertraits don't contain `Self`,
1616 for item in ®ular_traits {
1617 let object_safety_violations =
1618 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1619 if !object_safety_violations.is_empty() {
1620 report_object_safety_error(
1623 item.trait_ref().def_id(),
1624 &object_safety_violations[..],
1627 return tcx.types.err;
1631 // Use a `BTreeSet` to keep output in a more consistent order.
1632 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1634 let regular_traits_refs_spans = bounds
1637 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1639 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1640 assert_eq!(constness, Constness::NotConst);
1642 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1644 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1645 obligation.predicate
1647 match obligation.predicate.kind() {
1648 ty::PredicateKind::Trait(pred, _) => {
1649 associated_types.entry(span).or_default().extend(
1650 tcx.associated_items(pred.def_id())
1651 .in_definition_order()
1652 .filter(|item| item.kind == ty::AssocKind::Type)
1653 .map(|item| item.def_id),
1656 &ty::PredicateKind::Projection(pred) => {
1657 // A `Self` within the original bound will be substituted with a
1658 // `trait_object_dummy_self`, so check for that.
1659 let references_self =
1660 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1662 // If the projection output contains `Self`, force the user to
1663 // elaborate it explicitly to avoid a lot of complexity.
1665 // The "classicaly useful" case is the following:
1667 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1672 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1673 // but actually supporting that would "expand" to an infinitely-long type
1674 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1676 // Instead, we force the user to write
1677 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1678 // the discussion in #56288 for alternatives.
1679 if !references_self {
1680 // Include projections defined on supertraits.
1681 bounds.projection_bounds.push((pred, span));
1689 for (projection_bound, _) in &bounds.projection_bounds {
1690 for def_ids in associated_types.values_mut() {
1691 def_ids.remove(&projection_bound.projection_def_id());
1695 self.complain_about_missing_associated_types(
1697 potential_assoc_types,
1701 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1702 // `dyn Trait + Send`.
1703 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1704 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1705 debug!("regular_traits: {:?}", regular_traits);
1706 debug!("auto_traits: {:?}", auto_traits);
1708 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1709 // removing the dummy `Self` type (`trait_object_dummy_self`).
1710 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1711 if trait_ref.self_ty() != dummy_self {
1712 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1713 // which picks up non-supertraits where clauses - but also, the object safety
1714 // completely ignores trait aliases, which could be object safety hazards. We
1715 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1716 // disabled. (#66420)
1717 tcx.sess.delay_span_bug(
1720 "trait_ref_to_existential called on {:?} with non-dummy Self",
1725 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1728 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1729 let existential_trait_refs =
1730 regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1731 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1732 bound.map_bound(|b| {
1733 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1734 ty::ExistentialProjection {
1736 item_def_id: b.projection_ty.item_def_id,
1737 substs: trait_ref.substs,
1742 // Calling `skip_binder` is okay because the predicates are re-bound.
1743 let regular_trait_predicates = existential_trait_refs
1744 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1745 let auto_trait_predicates = auto_traits
1747 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1748 let mut v = regular_trait_predicates
1749 .chain(auto_trait_predicates)
1751 existential_projections
1752 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1754 .collect::<SmallVec<[_; 8]>>();
1755 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1757 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1759 // Use explicitly-specified region bound.
1760 let region_bound = if !lifetime.is_elided() {
1761 self.ast_region_to_region(lifetime, None)
1763 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1764 if tcx.named_region(lifetime.hir_id).is_some() {
1765 self.ast_region_to_region(lifetime, None)
1767 self.re_infer(None, span).unwrap_or_else(|| {
1768 // FIXME: these can be redundant with E0106, but not always.
1773 "the lifetime bound for this object type cannot be deduced \
1774 from context; please supply an explicit bound"
1777 tcx.lifetimes.re_static
1782 debug!("region_bound: {:?}", region_bound);
1784 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1785 debug!("trait_object_type: {:?}", ty);
1789 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1790 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1791 /// same trait bound have the same name (as they come from different super-traits), we instead
1792 /// emit a generic note suggesting using a `where` clause to constraint instead.
1793 fn complain_about_missing_associated_types(
1795 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1796 potential_assoc_types: Vec<Span>,
1797 trait_bounds: &[hir::PolyTraitRef<'_>],
1799 if associated_types.values().all(|v| v.is_empty()) {
1802 let tcx = self.tcx();
1803 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1804 // appropriate one, but this should be handled earlier in the span assignment.
1805 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1807 .map(|(span, def_ids)| {
1808 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1811 let mut names = vec![];
1813 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1814 // `issue-22560.rs`.
1815 let mut trait_bound_spans: Vec<Span> = vec![];
1816 for (span, items) in &associated_types {
1817 if !items.is_empty() {
1818 trait_bound_spans.push(*span);
1820 for assoc_item in items {
1821 let trait_def_id = assoc_item.container.id();
1823 "`{}` (from trait `{}`)",
1825 tcx.def_path_str(trait_def_id),
1829 if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
1830 match &bound.trait_ref.path.segments[..] {
1831 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1832 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1833 // around that bug here, even though it should be fixed elsewhere.
1834 // This would otherwise cause an invalid suggestion. For an example, look at
1835 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1837 // error[E0191]: the value of the associated type `Output`
1838 // (from trait `std::ops::BitXor`) must be specified
1839 // --> $DIR/issue-28344.rs:4:17
1841 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1842 // | ^^^^^^ help: specify the associated type:
1843 // | `BitXor<Output = Type>`
1847 // error[E0191]: the value of the associated type `Output`
1848 // (from trait `std::ops::BitXor`) must be specified
1849 // --> $DIR/issue-28344.rs:4:17
1851 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1852 // | ^^^^^^^^^^^^^ help: specify the associated type:
1853 // | `BitXor::bitor<Output = Type>`
1854 [segment] if segment.args.is_none() => {
1855 trait_bound_spans = vec![segment.ident.span];
1856 associated_types = associated_types
1858 .map(|(_, items)| (segment.ident.span, items))
1865 trait_bound_spans.sort();
1866 let mut err = struct_span_err!(
1870 "the value of the associated type{} {} must be specified",
1871 pluralize!(names.len()),
1874 let mut suggestions = vec![];
1875 let mut types_count = 0;
1876 let mut where_constraints = vec![];
1877 for (span, assoc_items) in &associated_types {
1878 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1879 for item in assoc_items {
1881 *names.entry(item.ident.name).or_insert(0) += 1;
1883 let mut dupes = false;
1884 for item in assoc_items {
1885 let prefix = if names[&item.ident.name] > 1 {
1886 let trait_def_id = item.container.id();
1888 format!("{}::", tcx.def_path_str(trait_def_id))
1892 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1893 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1896 if potential_assoc_types.len() == assoc_items.len() {
1897 // Only suggest when the amount of missing associated types equals the number of
1898 // extra type arguments present, as that gives us a relatively high confidence
1899 // that the user forgot to give the associtated type's name. The canonical
1900 // example would be trying to use `Iterator<isize>` instead of
1901 // `Iterator<Item = isize>`.
1902 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1903 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1904 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1907 } else if let (Ok(snippet), false) =
1908 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1911 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1912 let code = if snippet.ends_with('>') {
1913 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1914 // suggest, but at least we can clue them to the correct syntax
1915 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1917 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1919 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1920 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1921 format!("{}<{}>", snippet, types.join(", "))
1923 suggestions.push((*span, code));
1925 where_constraints.push(*span);
1928 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1929 using the fully-qualified path to the associated types";
1930 if !where_constraints.is_empty() && suggestions.is_empty() {
1931 // If there are duplicates associated type names and a single trait bound do not
1932 // use structured suggestion, it means that there are multiple super-traits with
1933 // the same associated type name.
1934 err.help(where_msg);
1936 if suggestions.len() != 1 {
1937 // We don't need this label if there's an inline suggestion, show otherwise.
1938 for (span, assoc_items) in &associated_types {
1939 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1940 for item in assoc_items {
1942 *names.entry(item.ident.name).or_insert(0) += 1;
1944 let mut label = vec![];
1945 for item in assoc_items {
1946 let postfix = if names[&item.ident.name] > 1 {
1947 let trait_def_id = item.container.id();
1948 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1952 label.push(format!("`{}`{}", item.ident, postfix));
1954 if !label.is_empty() {
1958 "associated type{} {} must be specified",
1959 pluralize!(label.len()),
1966 if !suggestions.is_empty() {
1967 err.multipart_suggestion(
1968 &format!("specify the associated type{}", pluralize!(types_count)),
1970 Applicability::HasPlaceholders,
1972 if !where_constraints.is_empty() {
1973 err.span_help(where_constraints, where_msg);
1979 fn report_ambiguous_associated_type(
1986 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1987 if let (Some(_), Ok(snippet)) = (
1988 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1989 self.tcx().sess.source_map().span_to_snippet(span),
1991 err.span_suggestion(
1993 "you are looking for the module in `std`, not the primitive type",
1994 format!("std::{}", snippet),
1995 Applicability::MachineApplicable,
1998 err.span_suggestion(
2000 "use fully-qualified syntax",
2001 format!("<{} as {}>::{}", type_str, trait_str, name),
2002 Applicability::HasPlaceholders,
2008 // Search for a bound on a type parameter which includes the associated item
2009 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
2010 // This function will fail if there are no suitable bounds or there is
2012 fn find_bound_for_assoc_item(
2014 ty_param_def_id: LocalDefId,
2017 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
2018 let tcx = self.tcx();
2021 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
2022 ty_param_def_id, assoc_name, span,
2026 &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
2028 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
2030 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id);
2031 let param_name = tcx.hir().ty_param_name(param_hir_id);
2032 self.one_bound_for_assoc_type(
2034 traits::transitive_bounds(
2036 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
2039 || param_name.to_string(),
2046 // Checks that `bounds` contains exactly one element and reports appropriate
2047 // errors otherwise.
2048 fn one_bound_for_assoc_type<I>(
2050 all_candidates: impl Fn() -> I,
2051 ty_param_name: impl Fn() -> String,
2054 is_equality: impl Fn() -> Option<String>,
2055 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
2057 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2059 let mut matching_candidates = all_candidates()
2060 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
2062 let bound = match matching_candidates.next() {
2063 Some(bound) => bound,
2065 self.complain_about_assoc_type_not_found(
2071 return Err(ErrorReported);
2075 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
2077 if let Some(bound2) = matching_candidates.next() {
2078 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
2080 let is_equality = is_equality();
2081 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
2082 let mut err = if is_equality.is_some() {
2083 // More specific Error Index entry.
2088 "ambiguous associated type `{}` in bounds of `{}`",
2097 "ambiguous associated type `{}` in bounds of `{}`",
2102 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
2104 let mut where_bounds = vec![];
2105 for bound in bounds {
2106 let bound_id = bound.def_id();
2107 let bound_span = self
2109 .associated_items(bound_id)
2110 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
2111 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
2113 if let Some(bound_span) = bound_span {
2117 "ambiguous `{}` from `{}`",
2119 bound.print_only_trait_path(),
2122 if let Some(constraint) = &is_equality {
2123 where_bounds.push(format!(
2124 " T: {trait}::{assoc} = {constraint}",
2125 trait=bound.print_only_trait_path(),
2127 constraint=constraint,
2130 err.span_suggestion(
2132 "use fully qualified syntax to disambiguate",
2136 bound.print_only_trait_path(),
2139 Applicability::MaybeIncorrect,
2144 "associated type `{}` could derive from `{}`",
2146 bound.print_only_trait_path(),
2150 if !where_bounds.is_empty() {
2152 "consider introducing a new type parameter `T` and adding `where` constraints:\
2153 \n where\n T: {},\n{}",
2155 where_bounds.join(",\n"),
2159 if !where_bounds.is_empty() {
2160 return Err(ErrorReported);
2166 fn complain_about_assoc_type_not_found<I>(
2168 all_candidates: impl Fn() -> I,
2169 ty_param_name: &str,
2173 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2175 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2176 // valid span, so we point at the whole path segment instead.
2177 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2178 let mut err = struct_span_err!(
2182 "associated type `{}` not found for `{}`",
2187 let all_candidate_names: Vec<_> = all_candidates()
2188 .map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
2191 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2195 if let (Some(suggested_name), true) = (
2196 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2197 assoc_name.span != DUMMY_SP,
2199 err.span_suggestion(
2201 "there is an associated type with a similar name",
2202 suggested_name.to_string(),
2203 Applicability::MaybeIncorrect,
2206 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2212 // Create a type from a path to an associated type.
2213 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2214 // and item_segment is the path segment for `D`. We return a type and a def for
2216 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2217 // parameter or `Self`.
2218 pub fn associated_path_to_ty(
2220 hir_ref_id: hir::HirId,
2224 assoc_segment: &hir::PathSegment<'_>,
2225 permit_variants: bool,
2226 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2227 let tcx = self.tcx();
2228 let assoc_ident = assoc_segment.ident;
2230 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2232 // Check if we have an enum variant.
2233 let mut variant_resolution = None;
2234 if let ty::Adt(adt_def, _) = qself_ty.kind {
2235 if adt_def.is_enum() {
2236 let variant_def = adt_def
2239 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2240 if let Some(variant_def) = variant_def {
2241 if permit_variants {
2242 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2243 self.prohibit_generics(slice::from_ref(assoc_segment));
2244 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2246 variant_resolution = Some(variant_def.def_id);
2252 // Find the type of the associated item, and the trait where the associated
2253 // item is declared.
2254 let bound = match (&qself_ty.kind, qself_res) {
2255 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2256 // `Self` in an impl of a trait -- we have a concrete self type and a
2258 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2259 Some(trait_ref) => trait_ref,
2261 // A cycle error occurred, most likely.
2262 return Err(ErrorReported);
2266 self.one_bound_for_assoc_type(
2267 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2268 || "Self".to_string(),
2276 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
2277 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2279 if variant_resolution.is_some() {
2280 // Variant in type position
2281 let msg = format!("expected type, found variant `{}`", assoc_ident);
2282 tcx.sess.span_err(span, &msg);
2283 } else if qself_ty.is_enum() {
2284 let mut err = struct_span_err!(
2288 "no variant named `{}` found for enum `{}`",
2293 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2294 if let Some(suggested_name) = find_best_match_for_name(
2295 adt_def.variants.iter().map(|variant| &variant.ident.name),
2296 &assoc_ident.as_str(),
2299 err.span_suggestion(
2301 "there is a variant with a similar name",
2302 suggested_name.to_string(),
2303 Applicability::MaybeIncorrect,
2308 format!("variant not found in `{}`", qself_ty),
2312 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2313 let sp = tcx.sess.source_map().guess_head_span(sp);
2314 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2318 } else if !qself_ty.references_error() {
2319 // Don't print `TyErr` to the user.
2320 self.report_ambiguous_associated_type(
2322 &qself_ty.to_string(),
2327 return Err(ErrorReported);
2331 let trait_did = bound.def_id();
2332 let (assoc_ident, def_scope) =
2333 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2335 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2336 // of calling `filter_by_name_and_kind`.
2338 .associated_items(trait_did)
2339 .in_definition_order()
2341 i.kind.namespace() == Namespace::TypeNS
2342 && i.ident.normalize_to_macros_2_0() == assoc_ident
2344 .expect("missing associated type");
2346 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2347 let ty = self.normalize_ty(span, ty);
2349 let kind = DefKind::AssocTy;
2350 if !item.vis.is_accessible_from(def_scope, tcx) {
2351 let kind = kind.descr(item.def_id);
2352 let msg = format!("{} `{}` is private", kind, assoc_ident);
2354 .struct_span_err(span, &msg)
2355 .span_label(span, &format!("private {}", kind))
2358 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2360 if let Some(variant_def_id) = variant_resolution {
2361 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2362 let mut err = lint.build("ambiguous associated item");
2363 let mut could_refer_to = |kind: DefKind, def_id, also| {
2364 let note_msg = format!(
2365 "`{}` could{} refer to the {} defined here",
2370 err.span_note(tcx.def_span(def_id), ¬e_msg);
2373 could_refer_to(DefKind::Variant, variant_def_id, "");
2374 could_refer_to(kind, item.def_id, " also");
2376 err.span_suggestion(
2378 "use fully-qualified syntax",
2379 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2380 Applicability::MachineApplicable,
2386 Ok((ty, kind, item.def_id))
2392 opt_self_ty: Option<Ty<'tcx>>,
2394 trait_segment: &hir::PathSegment<'_>,
2395 item_segment: &hir::PathSegment<'_>,
2397 let tcx = self.tcx();
2399 let trait_def_id = tcx.parent(item_def_id).unwrap();
2401 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2403 let self_ty = if let Some(ty) = opt_self_ty {
2406 let path_str = tcx.def_path_str(trait_def_id);
2408 let def_id = self.item_def_id();
2410 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2412 let parent_def_id = def_id
2413 .and_then(|def_id| {
2414 def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id))
2416 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
2418 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2420 // If the trait in segment is the same as the trait defining the item,
2421 // use the `<Self as ..>` syntax in the error.
2422 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2423 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2425 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2431 self.report_ambiguous_associated_type(
2435 item_segment.ident.name,
2437 return tcx.types.err;
2440 debug!("qpath_to_ty: self_type={:?}", self_ty);
2442 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2444 let item_substs = self.create_substs_for_associated_item(
2452 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2454 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2457 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2461 let mut has_err = false;
2462 for segment in segments {
2463 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2464 for arg in segment.generic_args().args {
2465 let (span, kind) = match arg {
2466 hir::GenericArg::Lifetime(lt) => {
2472 (lt.span, "lifetime")
2474 hir::GenericArg::Type(ty) => {
2482 hir::GenericArg::Const(ct) => {
2491 let mut err = struct_span_err!(
2495 "{} arguments are not allowed for this type",
2498 err.span_label(span, format!("{} argument not allowed", kind));
2500 if err_for_lt && err_for_ty && err_for_ct {
2505 // Only emit the first error to avoid overloading the user with error messages.
2506 if let [binding, ..] = segment.generic_args().bindings {
2508 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2514 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2515 let mut err = struct_span_err!(
2519 "associated type bindings are not allowed here"
2521 err.span_label(span, "associated type not allowed here").emit();
2524 /// Prohibits explicit lifetime arguments if late-bound lifetime parameters
2525 /// are present. This is used both for datatypes and function calls.
2526 fn prohibit_explicit_late_bound_lifetimes(
2529 args: &hir::GenericArgs<'_>,
2530 position: GenericArgPosition,
2531 ) -> ExplicitLateBound {
2532 let param_counts = def.own_counts();
2533 let arg_counts = args.own_counts();
2534 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
2536 if infer_lifetimes {
2537 ExplicitLateBound::No
2538 } else if let Some(span_late) = def.has_late_bound_regions {
2539 let msg = "cannot specify lifetime arguments explicitly \
2540 if late bound lifetime parameters are present";
2541 let note = "the late bound lifetime parameter is introduced here";
2542 let span = args.args[0].span();
2543 if position == GenericArgPosition::Value
2544 && arg_counts.lifetimes != param_counts.lifetimes
2546 let mut err = tcx.sess.struct_span_err(span, msg);
2547 err.span_note(span_late, note);
2550 let mut multispan = MultiSpan::from_span(span);
2551 multispan.push_span_label(span_late, note.to_string());
2552 tcx.struct_span_lint_hir(
2553 LATE_BOUND_LIFETIME_ARGUMENTS,
2556 |lint| lint.build(msg).emit(),
2559 ExplicitLateBound::Yes
2561 ExplicitLateBound::No
2565 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2566 pub fn def_ids_for_value_path_segments(
2568 segments: &[hir::PathSegment<'_>],
2569 self_ty: Option<Ty<'tcx>>,
2573 // We need to extract the type parameters supplied by the user in
2574 // the path `path`. Due to the current setup, this is a bit of a
2575 // tricky-process; the problem is that resolve only tells us the
2576 // end-point of the path resolution, and not the intermediate steps.
2577 // Luckily, we can (at least for now) deduce the intermediate steps
2578 // just from the end-point.
2580 // There are basically five cases to consider:
2582 // 1. Reference to a constructor of a struct:
2584 // struct Foo<T>(...)
2586 // In this case, the parameters are declared in the type space.
2588 // 2. Reference to a constructor of an enum variant:
2590 // enum E<T> { Foo(...) }
2592 // In this case, the parameters are defined in the type space,
2593 // but may be specified either on the type or the variant.
2595 // 3. Reference to a fn item or a free constant:
2599 // In this case, the path will again always have the form
2600 // `a::b::foo::<T>` where only the final segment should have
2601 // type parameters. However, in this case, those parameters are
2602 // declared on a value, and hence are in the `FnSpace`.
2604 // 4. Reference to a method or an associated constant:
2606 // impl<A> SomeStruct<A> {
2610 // Here we can have a path like
2611 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2612 // may appear in two places. The penultimate segment,
2613 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2614 // final segment, `foo::<B>` contains parameters in fn space.
2616 // The first step then is to categorize the segments appropriately.
2618 let tcx = self.tcx();
2620 assert!(!segments.is_empty());
2621 let last = segments.len() - 1;
2623 let mut path_segs = vec![];
2626 // Case 1. Reference to a struct constructor.
2627 DefKind::Ctor(CtorOf::Struct, ..) => {
2628 // Everything but the final segment should have no
2629 // parameters at all.
2630 let generics = tcx.generics_of(def_id);
2631 // Variant and struct constructors use the
2632 // generics of their parent type definition.
2633 let generics_def_id = generics.parent.unwrap_or(def_id);
2634 path_segs.push(PathSeg(generics_def_id, last));
2637 // Case 2. Reference to a variant constructor.
2638 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2639 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2640 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2641 debug_assert!(adt_def.is_enum());
2643 } else if last >= 1 && segments[last - 1].args.is_some() {
2644 // Everything but the penultimate segment should have no
2645 // parameters at all.
2646 let mut def_id = def_id;
2648 // `DefKind::Ctor` -> `DefKind::Variant`
2649 if let DefKind::Ctor(..) = kind {
2650 def_id = tcx.parent(def_id).unwrap()
2653 // `DefKind::Variant` -> `DefKind::Enum`
2654 let enum_def_id = tcx.parent(def_id).unwrap();
2655 (enum_def_id, last - 1)
2657 // FIXME: lint here recommending `Enum::<...>::Variant` form
2658 // instead of `Enum::Variant::<...>` form.
2660 // Everything but the final segment should have no
2661 // parameters at all.
2662 let generics = tcx.generics_of(def_id);
2663 // Variant and struct constructors use the
2664 // generics of their parent type definition.
2665 (generics.parent.unwrap_or(def_id), last)
2667 path_segs.push(PathSeg(generics_def_id, index));
2670 // Case 3. Reference to a top-level value.
2671 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2672 path_segs.push(PathSeg(def_id, last));
2675 // Case 4. Reference to a method or associated const.
2676 DefKind::AssocFn | DefKind::AssocConst => {
2677 if segments.len() >= 2 {
2678 let generics = tcx.generics_of(def_id);
2679 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2681 path_segs.push(PathSeg(def_id, last));
2684 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2687 debug!("path_segs = {:?}", path_segs);
2692 // Check a type `Path` and convert it to a `Ty`.
2695 opt_self_ty: Option<Ty<'tcx>>,
2696 path: &hir::Path<'_>,
2697 permit_variants: bool,
2699 let tcx = self.tcx();
2702 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2703 path.res, opt_self_ty, path.segments
2706 let span = path.span;
2708 Res::Def(DefKind::OpaqueTy, did) => {
2709 // Check for desugared `impl Trait`.
2710 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2711 let item_segment = path.segments.split_last().unwrap();
2712 self.prohibit_generics(item_segment.1);
2713 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2714 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2721 | DefKind::ForeignTy,
2724 assert_eq!(opt_self_ty, None);
2725 self.prohibit_generics(path.segments.split_last().unwrap().1);
2726 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2728 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2729 // Convert "variant type" as if it were a real type.
2730 // The resulting `Ty` is type of the variant's enum for now.
2731 assert_eq!(opt_self_ty, None);
2734 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2735 let generic_segs: FxHashSet<_> =
2736 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2737 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2739 if !generic_segs.contains(&index) { Some(seg) } else { None }
2743 let PathSeg(def_id, index) = path_segs.last().unwrap();
2744 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2746 Res::Def(DefKind::TyParam, def_id) => {
2747 assert_eq!(opt_self_ty, None);
2748 self.prohibit_generics(path.segments);
2750 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
2751 let item_id = tcx.hir().get_parent_node(hir_id);
2752 let item_def_id = tcx.hir().local_def_id(item_id);
2753 let generics = tcx.generics_of(item_def_id);
2754 let index = generics.param_def_id_to_index[&def_id];
2755 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2757 Res::SelfTy(Some(_), None) => {
2758 // `Self` in trait or type alias.
2759 assert_eq!(opt_self_ty, None);
2760 self.prohibit_generics(path.segments);
2761 tcx.types.self_param
2763 Res::SelfTy(_, Some(def_id)) => {
2764 // `Self` in impl (we know the concrete type).
2765 assert_eq!(opt_self_ty, None);
2766 self.prohibit_generics(path.segments);
2767 // Try to evaluate any array length constants.
2768 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2770 Res::Def(DefKind::AssocTy, def_id) => {
2771 debug_assert!(path.segments.len() >= 2);
2772 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2777 &path.segments[path.segments.len() - 2],
2778 path.segments.last().unwrap(),
2781 Res::PrimTy(prim_ty) => {
2782 assert_eq!(opt_self_ty, None);
2783 self.prohibit_generics(path.segments);
2785 hir::PrimTy::Bool => tcx.types.bool,
2786 hir::PrimTy::Char => tcx.types.char,
2787 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2788 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2789 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2790 hir::PrimTy::Str => tcx.mk_str(),
2794 self.set_tainted_by_errors();
2795 self.tcx().types.err
2797 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2801 /// Parses the programmer's textual representation of a type into our
2802 /// internal notion of a type.
2803 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2804 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2806 let tcx = self.tcx();
2808 let result_ty = match ast_ty.kind {
2809 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2810 hir::TyKind::Ptr(ref mt) => {
2811 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2813 hir::TyKind::Rptr(ref region, ref mt) => {
2814 let r = self.ast_region_to_region(region, None);
2815 debug!("ast_ty_to_ty: r={:?}", r);
2816 let t = self.ast_ty_to_ty(&mt.ty);
2817 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2819 hir::TyKind::Never => tcx.types.never,
2820 hir::TyKind::Tup(ref fields) => {
2821 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2823 hir::TyKind::BareFn(ref bf) => {
2824 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2825 tcx.mk_fn_ptr(self.ty_of_fn(
2829 &hir::Generics::empty(),
2833 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2834 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2836 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2837 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2838 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2839 self.res_to_ty(opt_self_ty, path, false)
2841 hir::TyKind::OpaqueDef(item_id, ref lifetimes) => {
2842 let opaque_ty = tcx.hir().expect_item(item_id.id);
2843 let def_id = tcx.hir().local_def_id(item_id.id).to_def_id();
2845 match opaque_ty.kind {
2846 // RPIT (return position impl trait)
2847 // Only lifetimes mentioned in the impl Trait predicate are
2848 // captured by the opaque type, so the lifetime parameters
2849 // from the parent item need to be replaced with `'static`.
2850 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {
2851 self.impl_trait_ty_to_ty(def_id, lifetimes)
2853 // This arm is for `impl Trait` in the types of statics,
2854 // constants, locals and type aliases. These capture all
2855 // parent lifetimes, so they can use their identity subst.
2856 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => {
2857 let substs = InternalSubsts::identity_for_item(tcx, def_id);
2858 tcx.mk_opaque(def_id, substs)
2860 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2863 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2864 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2865 let ty = self.ast_ty_to_ty(qself);
2867 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2872 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2873 .map(|(ty, _, _)| ty)
2874 .unwrap_or(tcx.types.err)
2876 hir::TyKind::Array(ref ty, ref length) => {
2877 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2878 let length = ty::Const::from_anon_const(tcx, length_def_id);
2879 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2880 self.normalize_ty(ast_ty.span, array_ty)
2882 hir::TyKind::Typeof(ref _e) => {
2887 "`typeof` is a reserved keyword but unimplemented"
2889 .span_label(ast_ty.span, "reserved keyword")
2894 hir::TyKind::Infer => {
2895 // Infer also appears as the type of arguments or return
2896 // values in a ExprKind::Closure, or as
2897 // the type of local variables. Both of these cases are
2898 // handled specially and will not descend into this routine.
2899 self.ty_infer(None, ast_ty.span)
2901 hir::TyKind::Err => tcx.types.err,
2904 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2906 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2910 pub fn impl_trait_ty_to_ty(
2913 lifetimes: &[hir::GenericArg<'_>],
2915 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2916 let tcx = self.tcx();
2918 let generics = tcx.generics_of(def_id);
2920 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2921 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2922 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2923 // Our own parameters are the resolved lifetimes.
2925 GenericParamDefKind::Lifetime => {
2926 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2927 self.ast_region_to_region(lifetime, None).into()
2935 // Replace all parent lifetimes with `'static`.
2937 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2938 _ => tcx.mk_param_from_def(param),
2942 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2944 let ty = tcx.mk_opaque(def_id, substs);
2945 debug!("impl_trait_ty_to_ty: {}", ty);
2949 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2951 hir::TyKind::Infer if expected_ty.is_some() => {
2952 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2953 expected_ty.unwrap()
2955 _ => self.ast_ty_to_ty(ty),
2961 unsafety: hir::Unsafety,
2963 decl: &hir::FnDecl<'_>,
2964 generics: &hir::Generics<'_>,
2965 ident_span: Option<Span>,
2966 ) -> ty::PolyFnSig<'tcx> {
2969 let tcx = self.tcx();
2971 // We proactively collect all the inferred type params to emit a single error per fn def.
2972 let mut visitor = PlaceholderHirTyCollector::default();
2973 for ty in decl.inputs {
2974 visitor.visit_ty(ty);
2976 walk_generics(&mut visitor, generics);
2978 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2979 let output_ty = match decl.output {
2980 hir::FnRetTy::Return(ref output) => {
2981 visitor.visit_ty(output);
2982 self.ast_ty_to_ty(output)
2984 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2987 debug!("ty_of_fn: output_ty={:?}", output_ty);
2990 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2992 if let (false, Some(ident_span)) = (self.allow_ty_infer(), ident_span) {
2993 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2994 // only want to emit an error complaining about them if infer types (`_`) are not
2995 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2996 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2997 crate::collect::placeholder_type_error(
2999 ident_span.shrink_to_hi(),
3000 &generics.params[..],
3006 // Find any late-bound regions declared in return type that do
3007 // not appear in the arguments. These are not well-formed.
3010 // for<'a> fn() -> &'a str <-- 'a is bad
3011 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3012 let inputs = bare_fn_ty.inputs();
3013 let late_bound_in_args =
3014 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
3015 let output = bare_fn_ty.output();
3016 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
3017 for br in late_bound_in_ret.difference(&late_bound_in_args) {
3018 let lifetime_name = match *br {
3019 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
3020 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
3022 let mut err = struct_span_err!(
3026 "return type references {} which is not constrained by the fn input types",
3029 if let ty::BrAnon(_) = *br {
3030 // The only way for an anonymous lifetime to wind up
3031 // in the return type but **also** be unconstrained is
3032 // if it only appears in "associated types" in the
3033 // input. See #47511 for an example. In this case,
3034 // though we can easily give a hint that ought to be
3037 "lifetimes appearing in an associated type are not considered constrained",
3046 /// Given the bounds on an object, determines what single region bound (if any) we can
3047 /// use to summarize this type. The basic idea is that we will use the bound the user
3048 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3049 /// for region bounds. It may be that we can derive no bound at all, in which case
3050 /// we return `None`.
3051 fn compute_object_lifetime_bound(
3054 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
3055 ) -> Option<ty::Region<'tcx>> // if None, use the default
3057 let tcx = self.tcx();
3059 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3061 // No explicit region bound specified. Therefore, examine trait
3062 // bounds and see if we can derive region bounds from those.
3063 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3065 // If there are no derived region bounds, then report back that we
3066 // can find no region bound. The caller will use the default.
3067 if derived_region_bounds.is_empty() {
3071 // If any of the derived region bounds are 'static, that is always
3073 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
3074 return Some(tcx.lifetimes.re_static);
3077 // Determine whether there is exactly one unique region in the set
3078 // of derived region bounds. If so, use that. Otherwise, report an
3080 let r = derived_region_bounds[0];
3081 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3086 "ambiguous lifetime bound, explicit lifetime bound required"
3094 /// Collects together a list of bounds that are applied to some type,
3095 /// after they've been converted into `ty` form (from the HIR
3096 /// representations). These lists of bounds occur in many places in
3100 /// trait Foo: Bar + Baz { }
3101 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
3103 /// fn foo<T: Bar + Baz>() { }
3104 /// ^^^^^^^^^ bounding the type parameter `T`
3106 /// impl dyn Bar + Baz
3107 /// ^^^^^^^^^ bounding the forgotten dynamic type
3110 /// Our representation is a bit mixed here -- in some cases, we
3111 /// include the self type (e.g., `trait_bounds`) but in others we do
3112 #[derive(Default, PartialEq, Eq, Clone, Debug)]
3113 pub struct Bounds<'tcx> {
3114 /// A list of region bounds on the (implicit) self type. So if you
3115 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
3116 /// the `T` is not explicitly included).
3117 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
3119 /// A list of trait bounds. So if you had `T: Debug` this would be
3120 /// `T: Debug`. Note that the self-type is explicit here.
3121 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>,
3123 /// A list of projection equality bounds. So if you had `T:
3124 /// Iterator<Item = u32>` this would include `<T as
3125 /// Iterator>::Item => u32`. Note that the self-type is explicit
3127 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
3129 /// `Some` if there is *no* `?Sized` predicate. The `span`
3130 /// is the location in the source of the `T` declaration which can
3131 /// be cited as the source of the `T: Sized` requirement.
3132 pub implicitly_sized: Option<Span>,
3135 impl<'tcx> Bounds<'tcx> {
3136 /// Converts a bounds list into a flat set of predicates (like
3137 /// where-clauses). Because some of our bounds listings (e.g.,
3138 /// regions) don't include the self-type, you must supply the
3139 /// self-type here (the `param_ty` parameter).
3144 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
3145 // If it could be sized, and is, add the `Sized` predicate.
3146 let sized_predicate = self.implicitly_sized.and_then(|span| {
3147 tcx.lang_items().sized_trait().map(|sized| {
3148 let trait_ref = ty::Binder::bind(ty::TraitRef {
3150 substs: tcx.mk_substs_trait(param_ty, &[]),
3152 (trait_ref.without_const().to_predicate(tcx), span)
3161 .map(|&(region_bound, span)| {
3162 // Account for the binder being introduced below; no need to shift `param_ty`
3163 // because, at present at least, it either only refers to early-bound regions,
3164 // or it's a generic associated type that deliberately has escaping bound vars.
3165 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
3166 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
3167 (ty::Binder::bind(outlives).to_predicate(tcx), span)
3169 .chain(self.trait_bounds.iter().map(|&(bound_trait_ref, span, constness)| {
3170 let predicate = bound_trait_ref.with_constness(constness).to_predicate(tcx);
3174 self.projection_bounds
3176 .map(|&(projection, span)| (projection.to_predicate(tcx), span)),