1 //! Conversion from AST representation of types to the `ty.rs` representation.
2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
3 //! instance of `AstConv`.
5 use errors::{Applicability, DiagnosticId};
6 use crate::hir::{self, GenericArg, GenericArgs, ExprKind};
7 use crate::hir::def::{CtorOf, Res, DefKind};
8 use crate::hir::def_id::DefId;
9 use crate::hir::HirVec;
10 use crate::hir::ptr::P;
12 use crate::middle::lang_items::SizedTraitLangItem;
13 use crate::middle::resolve_lifetime as rl;
14 use crate::namespace::Namespace;
15 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
17 use rustc::ty::{self, DefIdTree, Ty, TyCtxt, Const, ToPredicate, TypeFoldable};
18 use rustc::ty::{GenericParamDef, GenericParamDefKind};
19 use rustc::ty::subst::{self, Subst, InternalSubsts, SubstsRef};
20 use rustc::ty::wf::object_region_bounds;
21 use rustc_target::spec::abi;
22 use crate::require_c_abi_if_c_variadic;
23 use smallvec::SmallVec;
25 use syntax::errors::pluralize;
26 use syntax::feature_gate::{GateIssue, emit_feature_err};
27 use syntax::util::lev_distance::find_best_match_for_name;
28 use syntax::symbol::sym;
29 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
30 use crate::util::common::ErrorReported;
31 use crate::util::nodemap::FxHashMap;
33 use std::collections::BTreeSet;
37 use rustc_data_structures::fx::FxHashSet;
40 pub struct PathSeg(pub DefId, pub usize);
42 pub trait AstConv<'tcx> {
43 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
45 fn item_def_id(&self) -> Option<DefId>;
47 /// Returns predicates in scope of the form `X: Foo`, where `X` is
48 /// a type parameter `X` with the given id `def_id`. This is a
49 /// subset of the full set of predicates.
51 /// This is used for one specific purpose: resolving "short-hand"
52 /// associated type references like `T::Item`. In principle, we
53 /// would do that by first getting the full set of predicates in
54 /// scope and then filtering down to find those that apply to `T`,
55 /// but this can lead to cycle errors. The problem is that we have
56 /// to do this resolution *in order to create the predicates in
57 /// the first place*. Hence, we have this "special pass".
58 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
60 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
63 param: Option<&ty::GenericParamDef>,
66 -> Option<ty::Region<'tcx>>;
68 /// Returns the type to use when a type is omitted.
69 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
71 /// Returns the const to use when a const is omitted.
75 param: Option<&ty::GenericParamDef>,
77 ) -> &'tcx Const<'tcx>;
79 /// Projecting an associated type from a (potentially)
80 /// higher-ranked trait reference is more complicated, because of
81 /// the possibility of late-bound regions appearing in the
82 /// associated type binding. This is not legal in function
83 /// signatures for that reason. In a function body, we can always
84 /// handle it because we can use inference variables to remove the
85 /// late-bound regions.
86 fn projected_ty_from_poly_trait_ref(&self,
89 poly_trait_ref: ty::PolyTraitRef<'tcx>)
92 /// Normalize an associated type coming from the user.
93 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
95 /// Invoked when we encounter an error from some prior pass
96 /// (e.g., resolve) that is translated into a ty-error. This is
97 /// used to help suppress derived errors typeck might otherwise
99 fn set_tainted_by_errors(&self);
101 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
104 pub enum SizedByDefault {
109 struct ConvertedBinding<'a, 'tcx> {
110 item_name: ast::Ident,
111 kind: ConvertedBindingKind<'a, 'tcx>,
115 enum ConvertedBindingKind<'a, 'tcx> {
117 Constraint(&'a [hir::GenericBound]),
121 enum GenericArgPosition {
123 Value, // e.g., functions
127 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
128 pub fn ast_region_to_region(&self,
129 lifetime: &hir::Lifetime,
130 def: Option<&ty::GenericParamDef>)
133 let tcx = self.tcx();
134 let lifetime_name = |def_id| {
135 tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap())
138 let r = match tcx.named_region(lifetime.hir_id) {
139 Some(rl::Region::Static) => {
140 tcx.lifetimes.re_static
143 Some(rl::Region::LateBound(debruijn, id, _)) => {
144 let name = lifetime_name(id);
145 tcx.mk_region(ty::ReLateBound(debruijn,
146 ty::BrNamed(id, name)))
149 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
150 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
153 Some(rl::Region::EarlyBound(index, id, _)) => {
154 let name = lifetime_name(id);
155 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
162 Some(rl::Region::Free(scope, id)) => {
163 let name = lifetime_name(id);
164 tcx.mk_region(ty::ReFree(ty::FreeRegion {
166 bound_region: ty::BrNamed(id, name)
169 // (*) -- not late-bound, won't change
173 self.re_infer(def, lifetime.span)
175 // This indicates an illegal lifetime
176 // elision. `resolve_lifetime` should have
177 // reported an error in this case -- but if
178 // not, let's error out.
179 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
181 // Supply some dummy value. We don't have an
182 // `re_error`, annoyingly, so use `'static`.
183 tcx.lifetimes.re_static
188 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
195 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
196 /// returns an appropriate set of substitutions for this particular reference to `I`.
197 pub fn ast_path_substs_for_ty(&self,
200 item_segment: &hir::PathSegment)
203 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
206 item_segment.generic_args(),
207 item_segment.infer_args,
211 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
216 /// Report error if there is an explicit type parameter when using `impl Trait`.
219 seg: &hir::PathSegment,
220 generics: &ty::Generics,
222 let explicit = !seg.infer_args;
223 let impl_trait = generics.params.iter().any(|param| match param.kind {
224 ty::GenericParamDefKind::Type {
225 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
230 if explicit && impl_trait {
232 seg.generic_args().args
236 GenericArg::Type(_) => Some(arg.span()),
239 .collect::<Vec<_>>();
241 let mut err = struct_span_err! {
245 "cannot provide explicit generic arguments when `impl Trait` is \
246 used in argument position"
250 err.span_label(span, "explicit generic argument not allowed");
259 /// Checks that the correct number of generic arguments have been provided.
260 /// Used specifically for function calls.
261 pub fn check_generic_arg_count_for_call(
265 seg: &hir::PathSegment,
266 is_method_call: bool,
268 let empty_args = P(hir::GenericArgs {
269 args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
271 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
272 Self::check_generic_arg_count(
276 if let Some(ref args) = seg.args {
282 GenericArgPosition::MethodCall
284 GenericArgPosition::Value
286 def.parent.is_none() && def.has_self, // `has_self`
287 seg.infer_args || suppress_mismatch, // `infer_args`
291 /// Checks that the correct number of generic arguments have been provided.
292 /// This is used both for datatypes and function calls.
293 fn check_generic_arg_count(
297 args: &hir::GenericArgs,
298 position: GenericArgPosition,
301 ) -> (bool, Option<Vec<Span>>) {
302 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
303 // that lifetimes will proceed types. So it suffices to check the number of each generic
304 // arguments in order to validate them with respect to the generic parameters.
305 let param_counts = def.own_counts();
306 let arg_counts = args.own_counts();
307 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
309 let mut defaults: ty::GenericParamCount = Default::default();
310 for param in &def.params {
312 GenericParamDefKind::Lifetime => {}
313 GenericParamDefKind::Type { has_default, .. } => {
314 defaults.types += has_default as usize
316 GenericParamDefKind::Const => {
317 // FIXME(const_generics:defaults)
322 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
323 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
326 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
327 let mut reported_late_bound_region_err = None;
328 if !infer_lifetimes {
329 if let Some(span_late) = def.has_late_bound_regions {
330 let msg = "cannot specify lifetime arguments explicitly \
331 if late bound lifetime parameters are present";
332 let note = "the late bound lifetime parameter is introduced here";
333 let span = args.args[0].span();
334 if position == GenericArgPosition::Value
335 && arg_counts.lifetimes != param_counts.lifetimes {
336 let mut err = tcx.sess.struct_span_err(span, msg);
337 err.span_note(span_late, note);
339 reported_late_bound_region_err = Some(true);
341 let mut multispan = MultiSpan::from_span(span);
342 multispan.push_span_label(span_late, note.to_string());
343 tcx.lint_hir(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
344 args.args[0].id(), multispan, msg);
345 reported_late_bound_region_err = Some(false);
350 let check_kind_count = |kind, required, permitted, provided, offset| {
352 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
359 // We enforce the following: `required` <= `provided` <= `permitted`.
360 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
361 // For other kinds (i.e., types), `permitted` may be greater than `required`.
362 if required <= provided && provided <= permitted {
363 return (reported_late_bound_region_err.unwrap_or(false), None);
366 // Unfortunately lifetime and type parameter mismatches are typically styled
367 // differently in diagnostics, which means we have a few cases to consider here.
368 let (bound, quantifier) = if required != permitted {
369 if provided < required {
370 (required, "at least ")
371 } else { // provided > permitted
372 (permitted, "at most ")
378 let mut potential_assoc_types: Option<Vec<Span>> = None;
379 let (spans, label) = if required == permitted && provided > permitted {
380 // In the case when the user has provided too many arguments,
381 // we want to point to the unexpected arguments.
382 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
384 .map(|arg| arg.span())
386 potential_assoc_types = Some(spans.clone());
387 (spans, format!( "unexpected {} argument", kind))
389 (vec![span], format!(
390 "expected {}{} {} argument{}",
398 let mut err = tcx.sess.struct_span_err_with_code(
401 "wrong number of {} arguments: expected {}{}, found {}",
407 DiagnosticId::Error("E0107".into())
410 err.span_label(span, label.as_str());
415 provided > required, // `suppress_error`
416 potential_assoc_types,
420 if reported_late_bound_region_err.is_none()
421 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes) {
424 param_counts.lifetimes,
425 param_counts.lifetimes,
426 arg_counts.lifetimes,
430 // FIXME(const_generics:defaults)
431 if !infer_args || arg_counts.consts > param_counts.consts {
437 arg_counts.lifetimes + arg_counts.types,
440 // Note that type errors are currently be emitted *after* const errors.
442 || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
445 param_counts.types - defaults.types - has_self as usize,
446 param_counts.types - has_self as usize,
448 arg_counts.lifetimes,
451 (reported_late_bound_region_err.unwrap_or(false), None)
455 /// Creates the relevant generic argument substitutions
456 /// corresponding to a set of generic parameters. This is a
457 /// rather complex function. Let us try to explain the role
458 /// of each of its parameters:
460 /// To start, we are given the `def_id` of the thing we are
461 /// creating the substitutions for, and a partial set of
462 /// substitutions `parent_substs`. In general, the substitutions
463 /// for an item begin with substitutions for all the "parents" of
464 /// that item -- e.g., for a method it might include the
465 /// parameters from the impl.
467 /// Therefore, the method begins by walking down these parents,
468 /// starting with the outermost parent and proceed inwards until
469 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
470 /// first to see if the parent's substitutions are listed in there. If so,
471 /// we can append those and move on. Otherwise, it invokes the
472 /// three callback functions:
474 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
475 /// generic arguments that were given to that parent from within
476 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
477 /// might refer to the trait `Foo`, and the arguments might be
478 /// `[T]`. The boolean value indicates whether to infer values
479 /// for arguments whose values were not explicitly provided.
480 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
481 /// instantiate a `GenericArg`.
482 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
483 /// creates a suitable inference variable.
484 pub fn create_substs_for_generic_args<'b>(
487 parent_substs: &[subst::GenericArg<'tcx>],
489 self_ty: Option<Ty<'tcx>>,
490 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
491 provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> subst::GenericArg<'tcx>,
492 inferred_kind: impl Fn(Option<&[subst::GenericArg<'tcx>]>, &GenericParamDef, bool)
493 -> subst::GenericArg<'tcx>,
494 ) -> SubstsRef<'tcx> {
495 // Collect the segments of the path; we need to substitute arguments
496 // for parameters throughout the entire path (wherever there are
497 // generic parameters).
498 let mut parent_defs = tcx.generics_of(def_id);
499 let count = parent_defs.count();
500 let mut stack = vec![(def_id, parent_defs)];
501 while let Some(def_id) = parent_defs.parent {
502 parent_defs = tcx.generics_of(def_id);
503 stack.push((def_id, parent_defs));
506 // We manually build up the substitution, rather than using convenience
507 // methods in `subst.rs`, so that we can iterate over the arguments and
508 // parameters in lock-step linearly, instead of trying to match each pair.
509 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
511 // Iterate over each segment of the path.
512 while let Some((def_id, defs)) = stack.pop() {
513 let mut params = defs.params.iter().peekable();
515 // If we have already computed substitutions for parents, we can use those directly.
516 while let Some(¶m) = params.peek() {
517 if let Some(&kind) = parent_substs.get(param.index as usize) {
525 // `Self` is handled first, unless it's been handled in `parent_substs`.
527 if let Some(¶m) = params.peek() {
528 if param.index == 0 {
529 if let GenericParamDefKind::Type { .. } = param.kind {
530 substs.push(self_ty.map(|ty| ty.into())
531 .unwrap_or_else(|| inferred_kind(None, param, true)));
538 // Check whether this segment takes generic arguments and the user has provided any.
539 let (generic_args, infer_args) = args_for_def_id(def_id);
541 let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
545 // We're going to iterate through the generic arguments that the user
546 // provided, matching them with the generic parameters we expect.
547 // Mismatches can occur as a result of elided lifetimes, or for malformed
548 // input. We try to handle both sensibly.
549 match (args.peek(), params.peek()) {
550 (Some(&arg), Some(¶m)) => {
551 match (arg, ¶m.kind) {
552 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
553 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
554 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
555 substs.push(provided_kind(param, arg));
559 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
560 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
561 // We expected a lifetime argument, but got a type or const
562 // argument. That means we're inferring the lifetimes.
563 substs.push(inferred_kind(None, param, infer_args));
567 // We expected one kind of parameter, but the user provided
568 // another. This is an error, but we need to handle it
569 // gracefully so we can report sensible errors.
570 // In this case, we're simply going to infer this argument.
576 // We should never be able to reach this point with well-formed input.
577 // Getting to this point means the user supplied more arguments than
578 // there are parameters.
581 (None, Some(¶m)) => {
582 // If there are fewer arguments than parameters, it means
583 // we're inferring the remaining arguments.
584 substs.push(inferred_kind(Some(&substs), param, infer_args));
588 (None, None) => break,
593 tcx.intern_substs(&substs)
596 /// Given the type/lifetime/const arguments provided to some path (along with
597 /// an implicit `Self`, if this is a trait reference), returns the complete
598 /// set of substitutions. This may involve applying defaulted type parameters.
599 /// Also returns back constriants on associated types.
604 /// T: std::ops::Index<usize, Output = u32>
605 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
608 /// 1. The `self_ty` here would refer to the type `T`.
609 /// 2. The path in question is the path to the trait `std::ops::Index`,
610 /// which will have been resolved to a `def_id`
611 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
612 /// parameters are returned in the `SubstsRef`, the associated type bindings like
613 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
615 /// Note that the type listing given here is *exactly* what the user provided.
616 fn create_substs_for_ast_path<'a>(&self,
619 generic_args: &'a hir::GenericArgs,
621 self_ty: Option<Ty<'tcx>>)
622 -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>)
624 // If the type is parameterized by this region, then replace this
625 // region with the current anon region binding (in other words,
626 // whatever & would get replaced with).
627 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
629 def_id, self_ty, generic_args);
631 let tcx = self.tcx();
632 let generic_params = tcx.generics_of(def_id);
634 // If a self-type was declared, one should be provided.
635 assert_eq!(generic_params.has_self, self_ty.is_some());
637 let has_self = generic_params.has_self;
638 let (_, potential_assoc_types) = Self::check_generic_arg_count(
643 GenericArgPosition::Type,
648 let is_object = self_ty.map_or(false, |ty| {
649 ty == self.tcx().types.trait_object_dummy_self
651 let default_needs_object_self = |param: &ty::GenericParamDef| {
652 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
653 if is_object && has_default && has_self {
654 let self_param = tcx.types.self_param;
655 if tcx.at(span).type_of(param.def_id).walk().any(|ty| ty == self_param) {
656 // There is no suitable inference default for a type parameter
657 // that references self, in an object type.
666 let substs = Self::create_substs_for_generic_args(
672 // Provide the generic args, and whether types should be inferred.
673 |_| (Some(generic_args), infer_args),
674 // Provide substitutions for parameters for which (valid) arguments have been provided.
676 match (¶m.kind, arg) {
677 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
678 self.ast_region_to_region(<, Some(param)).into()
680 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
681 self.ast_ty_to_ty(&ty).into()
683 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
684 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
689 // Provide substitutions for parameters for which arguments are inferred.
690 |substs, param, infer_args| {
692 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
693 GenericParamDefKind::Type { has_default, .. } => {
694 if !infer_args && has_default {
695 // No type parameter provided, but a default exists.
697 // If we are converting an object type, then the
698 // `Self` parameter is unknown. However, some of the
699 // other type parameters may reference `Self` in their
700 // defaults. This will lead to an ICE if we are not
702 if default_needs_object_self(param) {
703 struct_span_err!(tcx.sess, span, E0393,
704 "the type parameter `{}` must be explicitly specified",
707 .span_label(span, format!(
708 "missing reference to `{}`", param.name))
710 "because of the default `Self` reference, type parameters \
711 must be specified on object types"))
715 // This is a default type parameter.
718 tcx.at(span).type_of(param.def_id)
719 .subst_spanned(tcx, substs.unwrap(), Some(span))
722 } else if infer_args {
723 // No type parameters were provided, we can infer all.
724 let param = if !default_needs_object_self(param) {
729 self.ty_infer(param, span).into()
731 // We've already errored above about the mismatch.
735 GenericParamDefKind::Const => {
736 // FIXME(const_generics:defaults)
738 // No const parameters were provided, we can infer all.
739 let ty = tcx.at(span).type_of(param.def_id);
740 self.ct_infer(ty, Some(param), span).into()
742 // We've already errored above about the mismatch.
743 tcx.consts.err.into()
750 // Convert associated-type bindings or constraints into a separate vector.
751 // Example: Given this:
753 // T: Iterator<Item = u32>
755 // The `T` is passed in as a self-type; the `Item = u32` is
756 // not a "type parameter" of the `Iterator` trait, but rather
757 // a restriction on `<T as Iterator>::Item`, so it is passed
759 let assoc_bindings = generic_args.bindings.iter()
761 let kind = match binding.kind {
762 hir::TypeBindingKind::Equality { ref ty } =>
763 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty)),
764 hir::TypeBindingKind::Constraint { ref bounds } =>
765 ConvertedBindingKind::Constraint(bounds),
768 item_name: binding.ident,
775 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
776 generic_params, self_ty, substs);
778 (substs, assoc_bindings, potential_assoc_types)
781 /// Instantiates the path for the given trait reference, assuming that it's
782 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
783 /// The type _cannot_ be a type other than a trait type.
785 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
786 /// are disallowed. Otherwise, they are pushed onto the vector given.
787 pub fn instantiate_mono_trait_ref(&self,
788 trait_ref: &hir::TraitRef,
790 ) -> ty::TraitRef<'tcx>
792 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
794 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
795 trait_ref.trait_def_id(),
797 trait_ref.path.segments.last().unwrap())
800 /// The given trait-ref must actually be a trait.
801 pub(super) fn instantiate_poly_trait_ref_inner(&self,
802 trait_ref: &hir::TraitRef,
805 bounds: &mut Bounds<'tcx>,
807 ) -> Option<Vec<Span>> {
808 let trait_def_id = trait_ref.trait_def_id();
810 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
812 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
814 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
818 trait_ref.path.segments.last().unwrap(),
820 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
822 bounds.trait_bounds.push((poly_trait_ref, span));
824 let mut dup_bindings = FxHashMap::default();
825 for binding in &assoc_bindings {
826 // Specify type to assert that error was already reported in `Err` case.
827 let _: Result<_, ErrorReported> =
828 self.add_predicates_for_ast_type_binding(
829 trait_ref.hir_ref_id,
836 // Okay to ignore `Err` because of `ErrorReported` (see above).
839 debug!("instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
840 trait_ref, bounds, poly_trait_ref);
841 potential_assoc_types
844 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
845 /// a full trait reference. The resulting trait reference is returned. This may also generate
846 /// auxiliary bounds, which are added to `bounds`.
851 /// poly_trait_ref = Iterator<Item = u32>
855 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
857 /// **A note on binders:** against our usual convention, there is an implied bounder around
858 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
859 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
860 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
861 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
863 pub fn instantiate_poly_trait_ref(&self,
864 poly_trait_ref: &hir::PolyTraitRef,
866 bounds: &mut Bounds<'tcx>,
867 ) -> Option<Vec<Span>> {
868 self.instantiate_poly_trait_ref_inner(
869 &poly_trait_ref.trait_ref,
877 fn ast_path_to_mono_trait_ref(&self,
881 trait_segment: &hir::PathSegment
882 ) -> ty::TraitRef<'tcx>
884 let (substs, assoc_bindings, _) =
885 self.create_substs_for_ast_trait_ref(span,
889 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
890 ty::TraitRef::new(trait_def_id, substs)
893 fn create_substs_for_ast_trait_ref<'a>(
898 trait_segment: &'a hir::PathSegment,
899 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
900 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
903 let trait_def = self.tcx().trait_def(trait_def_id);
905 if !self.tcx().features().unboxed_closures &&
906 trait_segment.generic_args().parenthesized != trait_def.paren_sugar
908 // For now, require that parenthetical notation be used only with `Fn()` etc.
909 let msg = if trait_def.paren_sugar {
910 "the precise format of `Fn`-family traits' type parameters is subject to change. \
911 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
913 "parenthetical notation is only stable when used with `Fn`-family traits"
915 emit_feature_err(&self.tcx().sess.parse_sess, sym::unboxed_closures,
916 span, GateIssue::Language, msg);
919 self.create_substs_for_ast_path(span,
921 trait_segment.generic_args(),
922 trait_segment.infer_args,
926 fn trait_defines_associated_type_named(&self,
928 assoc_name: ast::Ident)
931 self.tcx().associated_items(trait_def_id).any(|item| {
932 item.kind == ty::AssocKind::Type &&
933 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
937 // Returns `true` if a bounds list includes `?Sized`.
938 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound], span: Span) -> bool {
939 let tcx = self.tcx();
941 // Try to find an unbound in bounds.
942 let mut unbound = None;
943 for ab in ast_bounds {
944 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
945 if unbound.is_none() {
946 unbound = Some(&ptr.trait_ref);
952 "type parameter has more than one relaxed default \
953 bound, only one is supported"
959 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
962 // FIXME(#8559) currently requires the unbound to be built-in.
963 if let Ok(kind_id) = kind_id {
964 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
967 "default bound relaxed for a type parameter, but \
968 this does nothing because the given bound is not \
969 a default; only `?Sized` is supported",
974 _ if kind_id.is_ok() => {
977 // No lang item for `Sized`, so we can't add it as a bound.
984 /// This helper takes a *converted* parameter type (`param_ty`)
985 /// and an *unconverted* list of bounds:
989 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
991 /// `param_ty`, in ty form
994 /// It adds these `ast_bounds` into the `bounds` structure.
996 /// **A note on binders:** there is an implied binder around
997 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
998 /// for more details.
1001 ast_bounds: &[hir::GenericBound],
1002 bounds: &mut Bounds<'tcx>,
1004 let mut trait_bounds = Vec::new();
1005 let mut region_bounds = Vec::new();
1007 for ast_bound in ast_bounds {
1009 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) =>
1010 trait_bounds.push(b),
1011 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1012 hir::GenericBound::Outlives(ref l) =>
1013 region_bounds.push(l),
1017 for bound in trait_bounds {
1018 let _ = self.instantiate_poly_trait_ref(
1025 bounds.region_bounds.extend(region_bounds
1027 .map(|r| (self.ast_region_to_region(r, None), r.span))
1031 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1032 /// The self-type for the bounds is given by `param_ty`.
1037 /// fn foo<T: Bar + Baz>() { }
1038 /// ^ ^^^^^^^^^ ast_bounds
1042 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1043 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1044 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1046 /// `span` should be the declaration size of the parameter.
1047 pub fn compute_bounds(&self,
1049 ast_bounds: &[hir::GenericBound],
1050 sized_by_default: SizedByDefault,
1053 let mut bounds = Bounds::default();
1055 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1056 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1058 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1059 if !self.is_unsized(ast_bounds, span) {
1071 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1074 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1075 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1076 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1077 fn add_predicates_for_ast_type_binding(
1079 hir_ref_id: hir::HirId,
1080 trait_ref: ty::PolyTraitRef<'tcx>,
1081 binding: &ConvertedBinding<'_, 'tcx>,
1082 bounds: &mut Bounds<'tcx>,
1084 dup_bindings: &mut FxHashMap<DefId, Span>,
1085 ) -> Result<(), ErrorReported> {
1086 let tcx = self.tcx();
1089 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1090 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1091 // subtle in the event that `T` is defined in a supertrait of
1092 // `SomeTrait`, because in that case we need to upcast.
1094 // That is, consider this case:
1097 // trait SubTrait: SuperTrait<int> { }
1098 // trait SuperTrait<A> { type T; }
1100 // ... B: SubTrait<T = foo> ...
1103 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1105 // Find any late-bound regions declared in `ty` that are not
1106 // declared in the trait-ref. These are not well-formed.
1110 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1111 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1112 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1113 let late_bound_in_trait_ref =
1114 tcx.collect_constrained_late_bound_regions(&trait_ref);
1115 let late_bound_in_ty =
1116 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1117 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1118 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1119 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1120 let br_name = match *br {
1121 ty::BrNamed(_, name) => name,
1125 "anonymous bound region {:?} in binding but not trait ref",
1129 struct_span_err!(tcx.sess,
1132 "binding for associated type `{}` references lifetime `{}`, \
1133 which does not appear in the trait input types",
1134 binding.item_name, br_name)
1140 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
1141 binding.item_name) {
1142 // Simple case: X is defined in the current trait.
1145 // Otherwise, we have to walk through the supertraits to find
1147 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
1148 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
1150 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
1151 binding.item_name, binding.span)
1154 let (assoc_ident, def_scope) =
1155 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1156 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
1157 i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident
1158 }).expect("missing associated type");
1160 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1161 let msg = format!("associated type `{}` is private", binding.item_name);
1162 tcx.sess.span_err(binding.span, &msg);
1164 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1167 dup_bindings.entry(assoc_ty.def_id)
1168 .and_modify(|prev_span| {
1169 struct_span_err!(self.tcx().sess, binding.span, E0719,
1170 "the value of the associated type `{}` (from the trait `{}`) \
1171 is already specified",
1173 tcx.def_path_str(assoc_ty.container.id()))
1174 .span_label(binding.span, "re-bound here")
1175 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1178 .or_insert(binding.span);
1181 match binding.kind {
1182 ConvertedBindingKind::Equality(ref ty) => {
1183 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1184 // the "projection predicate" for:
1186 // `<T as Iterator>::Item = u32`
1187 bounds.projection_bounds.push((candidate.map_bound(|trait_ref| {
1188 ty::ProjectionPredicate {
1189 projection_ty: ty::ProjectionTy::from_ref_and_name(
1198 ConvertedBindingKind::Constraint(ast_bounds) => {
1199 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1201 // `<T as Iterator>::Item: Debug`
1203 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1204 // parameter to have a skipped binder.
1205 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1206 self.add_bounds(param_ty, ast_bounds, bounds);
1212 fn ast_path_to_ty(&self,
1215 item_segment: &hir::PathSegment)
1218 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1221 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
1225 /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1226 /// removing the dummy `Self` type (`trait_object_dummy_self`).
1227 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
1228 -> ty::ExistentialTraitRef<'tcx> {
1229 if trait_ref.self_ty() != self.tcx().types.trait_object_dummy_self {
1230 bug!("trait_ref_to_existential called on {:?} with non-dummy Self", trait_ref);
1232 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
1235 fn conv_object_ty_poly_trait_ref(&self,
1237 trait_bounds: &[hir::PolyTraitRef],
1238 lifetime: &hir::Lifetime)
1241 let tcx = self.tcx();
1243 let mut bounds = Bounds::default();
1244 let mut potential_assoc_types = Vec::new();
1245 let dummy_self = self.tcx().types.trait_object_dummy_self;
1246 for trait_bound in trait_bounds.iter().rev() {
1247 let cur_potential_assoc_types = self.instantiate_poly_trait_ref(
1252 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1255 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1256 // is used and no 'maybe' bounds are used.
1257 let expanded_traits =
1258 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1259 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1260 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1261 if regular_traits.len() > 1 {
1262 let first_trait = ®ular_traits[0];
1263 let additional_trait = ®ular_traits[1];
1264 let mut err = struct_span_err!(tcx.sess, additional_trait.bottom().1, E0225,
1265 "only auto traits can be used as additional traits in a trait object"
1267 additional_trait.label_with_exp_info(&mut err,
1268 "additional non-auto trait", "additional use");
1269 first_trait.label_with_exp_info(&mut err,
1270 "first non-auto trait", "first use");
1274 if regular_traits.is_empty() && auto_traits.is_empty() {
1275 span_err!(tcx.sess, span, E0224,
1276 "at least one trait is required for an object type");
1277 return tcx.types.err;
1280 // Check that there are no gross object safety violations;
1281 // most importantly, that the supertraits don't contain `Self`,
1283 for item in ®ular_traits {
1284 let object_safety_violations =
1285 tcx.astconv_object_safety_violations(item.trait_ref().def_id());
1286 if !object_safety_violations.is_empty() {
1287 tcx.report_object_safety_error(
1289 item.trait_ref().def_id(),
1290 object_safety_violations
1292 return tcx.types.err;
1296 // Use a `BTreeSet` to keep output in a more consistent order.
1297 let mut associated_types = BTreeSet::default();
1299 let regular_traits_refs = bounds.trait_bounds
1301 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()))
1302 .map(|(trait_ref, _)| trait_ref);
1303 for trait_ref in traits::elaborate_trait_refs(tcx, regular_traits_refs) {
1304 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", trait_ref);
1306 ty::Predicate::Trait(pred) => {
1308 .extend(tcx.associated_items(pred.def_id())
1309 .filter(|item| item.kind == ty::AssocKind::Type)
1310 .map(|item| item.def_id));
1312 ty::Predicate::Projection(pred) => {
1313 // A `Self` within the original bound will be substituted with a
1314 // `trait_object_dummy_self`, so check for that.
1315 let references_self =
1316 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1318 // If the projection output contains `Self`, force the user to
1319 // elaborate it explicitly to avoid a lot of complexity.
1321 // The "classicaly useful" case is the following:
1323 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1328 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1329 // but actually supporting that would "expand" to an infinitely-long type
1330 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1332 // Instead, we force the user to write `dyn MyTrait<MyOutput = X, Output = X>`,
1333 // which is uglier but works. See the discussion in #56288 for alternatives.
1334 if !references_self {
1335 // Include projections defined on supertraits.
1336 bounds.projection_bounds.push((pred, DUMMY_SP))
1343 for (projection_bound, _) in &bounds.projection_bounds {
1344 associated_types.remove(&projection_bound.projection_def_id());
1347 if !associated_types.is_empty() {
1348 let names = associated_types.iter().map(|item_def_id| {
1349 let assoc_item = tcx.associated_item(*item_def_id);
1350 let trait_def_id = assoc_item.container.id();
1352 "`{}` (from the trait `{}`)",
1354 tcx.def_path_str(trait_def_id),
1356 }).collect::<Vec<_>>().join(", ");
1357 let mut err = struct_span_err!(
1361 "the value of the associated type{} {} must be specified",
1362 pluralize!(associated_types.len()),
1365 let (suggest, potential_assoc_types_spans) =
1366 if potential_assoc_types.len() == associated_types.len() {
1367 // Only suggest when the amount of missing associated types equals the number of
1368 // extra type arguments present, as that gives us a relatively high confidence
1369 // that the user forgot to give the associtated type's name. The canonical
1370 // example would be trying to use `Iterator<isize>` instead of
1371 // `Iterator<Item = isize>`.
1372 (true, potential_assoc_types)
1376 let mut suggestions = Vec::new();
1377 for (i, item_def_id) in associated_types.iter().enumerate() {
1378 let assoc_item = tcx.associated_item(*item_def_id);
1381 format!("associated type `{}` must be specified", assoc_item.ident),
1383 if let Some(sp) = tcx.hir().span_if_local(*item_def_id) {
1384 err.span_label(sp, format!("`{}` defined here", assoc_item.ident));
1387 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1388 potential_assoc_types_spans[i],
1391 potential_assoc_types_spans[i],
1392 format!("{} = {}", assoc_item.ident, snippet),
1397 if !suggestions.is_empty() {
1398 let msg = format!("if you meant to specify the associated {}, write",
1399 if suggestions.len() == 1 { "type" } else { "types" });
1400 err.multipart_suggestion(
1403 Applicability::MaybeIncorrect,
1409 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1410 // `dyn Trait + Send`.
1411 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1412 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1413 debug!("regular_traits: {:?}", regular_traits);
1414 debug!("auto_traits: {:?}", auto_traits);
1416 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1417 let existential_trait_refs = regular_traits.iter().map(|i| {
1418 i.trait_ref().map_bound(|trait_ref| self.trait_ref_to_existential(trait_ref))
1420 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1421 bound.map_bound(|b| {
1422 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1423 ty::ExistentialProjection {
1425 item_def_id: b.projection_ty.item_def_id,
1426 substs: trait_ref.substs,
1431 // Calling `skip_binder` is okay because the predicates are re-bound.
1432 let regular_trait_predicates = existential_trait_refs.map(
1433 |trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1434 let auto_trait_predicates = auto_traits.into_iter().map(
1435 |trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1437 regular_trait_predicates
1438 .chain(auto_trait_predicates)
1439 .chain(existential_projections
1440 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1441 .collect::<SmallVec<[_; 8]>>();
1442 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1444 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1446 // Use explicitly-specified region bound.
1447 let region_bound = if !lifetime.is_elided() {
1448 self.ast_region_to_region(lifetime, None)
1450 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1451 if tcx.named_region(lifetime.hir_id).is_some() {
1452 self.ast_region_to_region(lifetime, None)
1454 self.re_infer(None, span).unwrap_or_else(|| {
1455 span_err!(tcx.sess, span, E0228,
1456 "the lifetime bound for this object type cannot be deduced \
1457 from context; please supply an explicit bound");
1458 tcx.lifetimes.re_static
1463 debug!("region_bound: {:?}", region_bound);
1465 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1466 debug!("trait_object_type: {:?}", ty);
1470 fn report_ambiguous_associated_type(
1477 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1478 if let (Some(_), Ok(snippet)) = (
1479 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1480 self.tcx().sess.source_map().span_to_snippet(span),
1482 err.span_suggestion(
1484 "you are looking for the module in `std`, not the primitive type",
1485 format!("std::{}", snippet),
1486 Applicability::MachineApplicable,
1489 err.span_suggestion(
1491 "use fully-qualified syntax",
1492 format!("<{} as {}>::{}", type_str, trait_str, name),
1493 Applicability::HasPlaceholders
1499 // Search for a bound on a type parameter which includes the associated item
1500 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1501 // This function will fail if there are no suitable bounds or there is
1503 fn find_bound_for_assoc_item(&self,
1504 ty_param_def_id: DefId,
1505 assoc_name: ast::Ident,
1507 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1509 let tcx = self.tcx();
1512 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1518 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1520 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1522 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1524 // Check that there is exactly one way to find an associated type with the
1526 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1527 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1529 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1530 let param_name = tcx.hir().ty_param_name(param_hir_id);
1531 self.one_bound_for_assoc_type(suitable_bounds,
1532 ¶m_name.as_str(),
1537 // Checks that `bounds` contains exactly one element and reports appropriate
1538 // errors otherwise.
1539 fn one_bound_for_assoc_type<I>(&self,
1541 ty_param_name: &str,
1542 assoc_name: ast::Ident,
1544 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1545 where I: Iterator<Item = ty::PolyTraitRef<'tcx>>
1547 let bound = match bounds.next() {
1548 Some(bound) => bound,
1550 struct_span_err!(self.tcx().sess, span, E0220,
1551 "associated type `{}` not found for `{}`",
1554 .span_label(span, format!("associated type `{}` not found", assoc_name))
1556 return Err(ErrorReported);
1560 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1562 if let Some(bound2) = bounds.next() {
1563 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1565 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1566 let mut err = struct_span_err!(
1567 self.tcx().sess, span, E0221,
1568 "ambiguous associated type `{}` in bounds of `{}`",
1571 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1573 for bound in bounds {
1574 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1575 item.kind == ty::AssocKind::Type &&
1576 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1578 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1580 if let Some(span) = bound_span {
1581 err.span_label(span, format!("ambiguous `{}` from `{}`",
1585 span_note!(&mut err, span,
1586 "associated type `{}` could derive from `{}`",
1597 // Create a type from a path to an associated type.
1598 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1599 // and item_segment is the path segment for `D`. We return a type and a def for
1601 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1602 // parameter or `Self`.
1603 pub fn associated_path_to_ty(
1605 hir_ref_id: hir::HirId,
1609 assoc_segment: &hir::PathSegment,
1610 permit_variants: bool,
1611 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1612 let tcx = self.tcx();
1613 let assoc_ident = assoc_segment.ident;
1615 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1617 self.prohibit_generics(slice::from_ref(assoc_segment));
1619 // Check if we have an enum variant.
1620 let mut variant_resolution = None;
1621 if let ty::Adt(adt_def, _) = qself_ty.kind {
1622 if adt_def.is_enum() {
1623 let variant_def = adt_def.variants.iter().find(|vd| {
1624 tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1626 if let Some(variant_def) = variant_def {
1627 if permit_variants {
1628 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1629 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1631 variant_resolution = Some(variant_def.def_id);
1637 // Find the type of the associated item, and the trait where the associated
1638 // item is declared.
1639 let bound = match (&qself_ty.kind, qself_res) {
1640 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
1641 // `Self` in an impl of a trait -- we have a concrete self type and a
1643 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1644 Some(trait_ref) => trait_ref,
1646 // A cycle error occurred, most likely.
1647 return Err(ErrorReported);
1651 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1652 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1654 self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span)?
1656 (&ty::Param(_), Res::SelfTy(Some(param_did), None)) |
1657 (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
1658 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
1661 if variant_resolution.is_some() {
1662 // Variant in type position
1663 let msg = format!("expected type, found variant `{}`", assoc_ident);
1664 tcx.sess.span_err(span, &msg);
1665 } else if qself_ty.is_enum() {
1666 let mut err = tcx.sess.struct_span_err(
1668 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
1671 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1672 if let Some(suggested_name) = find_best_match_for_name(
1673 adt_def.variants.iter().map(|variant| &variant.ident.name),
1674 &assoc_ident.as_str(),
1677 err.span_suggestion(
1679 "there is a variant with a similar name",
1680 suggested_name.to_string(),
1681 Applicability::MaybeIncorrect,
1686 format!("variant not found in `{}`", qself_ty),
1690 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1691 let sp = tcx.sess.source_map().def_span(sp);
1692 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1696 } else if !qself_ty.references_error() {
1697 // Don't print `TyErr` to the user.
1698 self.report_ambiguous_associated_type(
1700 &qself_ty.to_string(),
1705 return Err(ErrorReported);
1709 let trait_did = bound.def_id();
1710 let (assoc_ident, def_scope) =
1711 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1712 let item = tcx.associated_items(trait_did).find(|i| {
1713 Namespace::from(i.kind) == Namespace::Type &&
1714 i.ident.modern() == assoc_ident
1715 }).expect("missing associated type");
1717 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1718 let ty = self.normalize_ty(span, ty);
1720 let kind = DefKind::AssocTy;
1721 if !item.vis.is_accessible_from(def_scope, tcx) {
1722 let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
1723 tcx.sess.span_err(span, &msg);
1725 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1727 if let Some(variant_def_id) = variant_resolution {
1728 let mut err = tcx.struct_span_lint_hir(
1729 AMBIGUOUS_ASSOCIATED_ITEMS,
1732 "ambiguous associated item",
1735 let mut could_refer_to = |kind: DefKind, def_id, also| {
1736 let note_msg = format!("`{}` could{} refer to {} defined here",
1737 assoc_ident, also, kind.descr(def_id));
1738 err.span_note(tcx.def_span(def_id), ¬e_msg);
1740 could_refer_to(DefKind::Variant, variant_def_id, "");
1741 could_refer_to(kind, item.def_id, " also");
1743 err.span_suggestion(
1745 "use fully-qualified syntax",
1746 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1747 Applicability::MachineApplicable,
1751 Ok((ty, kind, item.def_id))
1754 fn qpath_to_ty(&self,
1756 opt_self_ty: Option<Ty<'tcx>>,
1758 trait_segment: &hir::PathSegment,
1759 item_segment: &hir::PathSegment)
1762 let tcx = self.tcx();
1764 let trait_def_id = tcx.parent(item_def_id).unwrap();
1766 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1768 self.prohibit_generics(slice::from_ref(item_segment));
1770 let self_ty = if let Some(ty) = opt_self_ty {
1773 let path_str = tcx.def_path_str(trait_def_id);
1775 let def_id = self.item_def_id();
1777 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1779 let parent_def_id = def_id.and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
1780 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
1782 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1784 // If the trait in segment is the same as the trait defining the item,
1785 // use the `<Self as ..>` syntax in the error.
1786 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1787 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1789 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1795 self.report_ambiguous_associated_type(
1799 item_segment.ident.name,
1801 return tcx.types.err;
1804 debug!("qpath_to_ty: self_type={:?}", self_ty);
1806 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1811 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1813 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1816 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1817 &self, segments: T) -> bool {
1818 let mut has_err = false;
1819 for segment in segments {
1820 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1821 for arg in &segment.generic_args().args {
1822 let (span, kind) = match arg {
1823 hir::GenericArg::Lifetime(lt) => {
1824 if err_for_lt { continue }
1827 (lt.span, "lifetime")
1829 hir::GenericArg::Type(ty) => {
1830 if err_for_ty { continue }
1835 hir::GenericArg::Const(ct) => {
1836 if err_for_ct { continue }
1841 let mut err = struct_span_err!(
1845 "{} arguments are not allowed for this type",
1848 err.span_label(span, format!("{} argument not allowed", kind));
1850 if err_for_lt && err_for_ty && err_for_ct {
1854 for binding in &segment.generic_args().bindings {
1856 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1863 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
1864 let mut err = struct_span_err!(tcx.sess, span, E0229,
1865 "associated type bindings are not allowed here");
1866 err.span_label(span, "associated type not allowed here").emit();
1869 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1870 pub fn def_ids_for_value_path_segments(
1872 segments: &[hir::PathSegment],
1873 self_ty: Option<Ty<'tcx>>,
1877 // We need to extract the type parameters supplied by the user in
1878 // the path `path`. Due to the current setup, this is a bit of a
1879 // tricky-process; the problem is that resolve only tells us the
1880 // end-point of the path resolution, and not the intermediate steps.
1881 // Luckily, we can (at least for now) deduce the intermediate steps
1882 // just from the end-point.
1884 // There are basically five cases to consider:
1886 // 1. Reference to a constructor of a struct:
1888 // struct Foo<T>(...)
1890 // In this case, the parameters are declared in the type space.
1892 // 2. Reference to a constructor of an enum variant:
1894 // enum E<T> { Foo(...) }
1896 // In this case, the parameters are defined in the type space,
1897 // but may be specified either on the type or the variant.
1899 // 3. Reference to a fn item or a free constant:
1903 // In this case, the path will again always have the form
1904 // `a::b::foo::<T>` where only the final segment should have
1905 // type parameters. However, in this case, those parameters are
1906 // declared on a value, and hence are in the `FnSpace`.
1908 // 4. Reference to a method or an associated constant:
1910 // impl<A> SomeStruct<A> {
1914 // Here we can have a path like
1915 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1916 // may appear in two places. The penultimate segment,
1917 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1918 // final segment, `foo::<B>` contains parameters in fn space.
1920 // The first step then is to categorize the segments appropriately.
1922 let tcx = self.tcx();
1924 assert!(!segments.is_empty());
1925 let last = segments.len() - 1;
1927 let mut path_segs = vec![];
1930 // Case 1. Reference to a struct constructor.
1931 DefKind::Ctor(CtorOf::Struct, ..) => {
1932 // Everything but the final segment should have no
1933 // parameters at all.
1934 let generics = tcx.generics_of(def_id);
1935 // Variant and struct constructors use the
1936 // generics of their parent type definition.
1937 let generics_def_id = generics.parent.unwrap_or(def_id);
1938 path_segs.push(PathSeg(generics_def_id, last));
1941 // Case 2. Reference to a variant constructor.
1942 DefKind::Ctor(CtorOf::Variant, ..)
1943 | DefKind::Variant => {
1944 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1945 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1946 debug_assert!(adt_def.is_enum());
1948 } else if last >= 1 && segments[last - 1].args.is_some() {
1949 // Everything but the penultimate segment should have no
1950 // parameters at all.
1951 let mut def_id = def_id;
1953 // `DefKind::Ctor` -> `DefKind::Variant`
1954 if let DefKind::Ctor(..) = kind {
1955 def_id = tcx.parent(def_id).unwrap()
1958 // `DefKind::Variant` -> `DefKind::Enum`
1959 let enum_def_id = tcx.parent(def_id).unwrap();
1960 (enum_def_id, last - 1)
1962 // FIXME: lint here recommending `Enum::<...>::Variant` form
1963 // instead of `Enum::Variant::<...>` form.
1965 // Everything but the final segment should have no
1966 // parameters at all.
1967 let generics = tcx.generics_of(def_id);
1968 // Variant and struct constructors use the
1969 // generics of their parent type definition.
1970 (generics.parent.unwrap_or(def_id), last)
1972 path_segs.push(PathSeg(generics_def_id, index));
1975 // Case 3. Reference to a top-level value.
1978 | DefKind::ConstParam
1979 | DefKind::Static => {
1980 path_segs.push(PathSeg(def_id, last));
1983 // Case 4. Reference to a method or associated const.
1985 | DefKind::AssocConst => {
1986 if segments.len() >= 2 {
1987 let generics = tcx.generics_of(def_id);
1988 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1990 path_segs.push(PathSeg(def_id, last));
1993 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1996 debug!("path_segs = {:?}", path_segs);
2001 // Check a type `Path` and convert it to a `Ty`.
2002 pub fn res_to_ty(&self,
2003 opt_self_ty: Option<Ty<'tcx>>,
2005 permit_variants: bool)
2007 let tcx = self.tcx();
2009 debug!("res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2010 path.res, opt_self_ty, path.segments);
2012 let span = path.span;
2014 Res::Def(DefKind::OpaqueTy, did) => {
2015 // Check for desugared `impl Trait`.
2016 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2017 let item_segment = path.segments.split_last().unwrap();
2018 self.prohibit_generics(item_segment.1);
2019 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2022 tcx.mk_opaque(did, substs),
2025 Res::Def(DefKind::Enum, did)
2026 | Res::Def(DefKind::TyAlias, did)
2027 | Res::Def(DefKind::Struct, did)
2028 | Res::Def(DefKind::Union, did)
2029 | Res::Def(DefKind::ForeignTy, did) => {
2030 assert_eq!(opt_self_ty, None);
2031 self.prohibit_generics(path.segments.split_last().unwrap().1);
2032 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2034 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2035 // Convert "variant type" as if it were a real type.
2036 // The resulting `Ty` is type of the variant's enum for now.
2037 assert_eq!(opt_self_ty, None);
2040 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2041 let generic_segs: FxHashSet<_> =
2042 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2043 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
2044 if !generic_segs.contains(&index) {
2051 let PathSeg(def_id, index) = path_segs.last().unwrap();
2052 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2054 Res::Def(DefKind::TyParam, def_id) => {
2055 assert_eq!(opt_self_ty, None);
2056 self.prohibit_generics(&path.segments);
2058 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2059 let item_id = tcx.hir().get_parent_node(hir_id);
2060 let item_def_id = tcx.hir().local_def_id(item_id);
2061 let generics = tcx.generics_of(item_def_id);
2062 let index = generics.param_def_id_to_index[&def_id];
2063 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2065 Res::SelfTy(Some(_), None) => {
2066 // `Self` in trait or type alias.
2067 assert_eq!(opt_self_ty, None);
2068 self.prohibit_generics(&path.segments);
2069 tcx.types.self_param
2071 Res::SelfTy(_, Some(def_id)) => {
2072 // `Self` in impl (we know the concrete type).
2073 assert_eq!(opt_self_ty, None);
2074 self.prohibit_generics(&path.segments);
2075 // Try to evaluate any array length constants.
2076 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2078 Res::Def(DefKind::AssocTy, def_id) => {
2079 debug_assert!(path.segments.len() >= 2);
2080 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2081 self.qpath_to_ty(span,
2084 &path.segments[path.segments.len() - 2],
2085 path.segments.last().unwrap())
2087 Res::PrimTy(prim_ty) => {
2088 assert_eq!(opt_self_ty, None);
2089 self.prohibit_generics(&path.segments);
2091 hir::Bool => tcx.types.bool,
2092 hir::Char => tcx.types.char,
2093 hir::Int(it) => tcx.mk_mach_int(it),
2094 hir::Uint(uit) => tcx.mk_mach_uint(uit),
2095 hir::Float(ft) => tcx.mk_mach_float(ft),
2096 hir::Str => tcx.mk_str()
2100 self.set_tainted_by_errors();
2101 return self.tcx().types.err;
2103 _ => span_bug!(span, "unexpected resolution: {:?}", path.res)
2107 /// Parses the programmer's textual representation of a type into our
2108 /// internal notion of a type.
2109 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
2110 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
2111 ast_ty.hir_id, ast_ty, ast_ty.kind);
2113 let tcx = self.tcx();
2115 let result_ty = match ast_ty.kind {
2116 hir::TyKind::Slice(ref ty) => {
2117 tcx.mk_slice(self.ast_ty_to_ty(&ty))
2119 hir::TyKind::Ptr(ref mt) => {
2120 tcx.mk_ptr(ty::TypeAndMut {
2121 ty: self.ast_ty_to_ty(&mt.ty),
2125 hir::TyKind::Rptr(ref region, ref mt) => {
2126 let r = self.ast_region_to_region(region, None);
2127 debug!("ast_ty_to_ty: r={:?}", r);
2128 let t = self.ast_ty_to_ty(&mt.ty);
2129 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
2131 hir::TyKind::Never => {
2134 hir::TyKind::Tup(ref fields) => {
2135 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2137 hir::TyKind::BareFn(ref bf) => {
2138 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2139 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
2141 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2142 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2144 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2145 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2146 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
2147 self.ast_ty_to_ty(qself)
2149 self.res_to_ty(opt_self_ty, path, false)
2151 hir::TyKind::Def(item_id, ref lifetimes) => {
2152 let did = tcx.hir().local_def_id(item_id.id);
2153 self.impl_trait_ty_to_ty(did, lifetimes)
2155 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2156 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2157 let ty = self.ast_ty_to_ty(qself);
2159 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2164 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2165 .map(|(ty, _, _)| ty).unwrap_or(tcx.types.err)
2167 hir::TyKind::Array(ref ty, ref length) => {
2168 let length = self.ast_const_to_const(length, tcx.types.usize);
2169 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2170 self.normalize_ty(ast_ty.span, array_ty)
2172 hir::TyKind::Typeof(ref _e) => {
2173 struct_span_err!(tcx.sess, ast_ty.span, E0516,
2174 "`typeof` is a reserved keyword but unimplemented")
2175 .span_label(ast_ty.span, "reserved keyword")
2180 hir::TyKind::Infer => {
2181 // Infer also appears as the type of arguments or return
2182 // values in a ExprKind::Closure, or as
2183 // the type of local variables. Both of these cases are
2184 // handled specially and will not descend into this routine.
2185 self.ty_infer(None, ast_ty.span)
2187 hir::TyKind::Err => {
2192 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2194 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2198 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2199 pub fn const_param_def_id(&self, expr: &hir::Expr) -> Option<DefId> {
2200 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2201 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2202 let expr = match &expr.kind {
2203 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() =>
2204 block.expr.as_ref().unwrap(),
2209 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2210 Res::Def(DefKind::ConstParam, did) => Some(did),
2217 pub fn ast_const_to_const(
2219 ast_const: &hir::AnonConst,
2221 ) -> &'tcx ty::Const<'tcx> {
2222 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2224 let tcx = self.tcx();
2225 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2227 let mut const_ = ty::Const {
2228 val: ty::ConstKind::Unevaluated(
2230 InternalSubsts::identity_for_item(tcx, def_id),
2235 let expr = &tcx.hir().body(ast_const.body).value;
2236 if let Some(def_id) = self.const_param_def_id(expr) {
2237 // Find the name and index of the const parameter by indexing the generics of the
2238 // parent item and construct a `ParamConst`.
2239 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2240 let item_id = tcx.hir().get_parent_node(hir_id);
2241 let item_def_id = tcx.hir().local_def_id(item_id);
2242 let generics = tcx.generics_of(item_def_id);
2243 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2244 let name = tcx.hir().name(hir_id);
2245 const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2248 tcx.mk_const(const_)
2251 pub fn impl_trait_ty_to_ty(
2254 lifetimes: &[hir::GenericArg],
2256 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2257 let tcx = self.tcx();
2259 let generics = tcx.generics_of(def_id);
2261 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2262 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2263 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2264 // Our own parameters are the resolved lifetimes.
2266 GenericParamDefKind::Lifetime => {
2267 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2268 self.ast_region_to_region(lifetime, None).into()
2276 // Replace all parent lifetimes with `'static`.
2278 GenericParamDefKind::Lifetime => {
2279 tcx.lifetimes.re_static.into()
2281 _ => tcx.mk_param_from_def(param)
2285 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2287 let ty = tcx.mk_opaque(def_id, substs);
2288 debug!("impl_trait_ty_to_ty: {}", ty);
2292 pub fn ty_of_arg(&self,
2294 expected_ty: Option<Ty<'tcx>>)
2298 hir::TyKind::Infer if expected_ty.is_some() => {
2299 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2300 expected_ty.unwrap()
2302 _ => self.ast_ty_to_ty(ty),
2306 pub fn ty_of_fn(&self,
2307 unsafety: hir::Unsafety,
2310 -> ty::PolyFnSig<'tcx> {
2313 let tcx = self.tcx();
2315 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2317 let output_ty = match decl.output {
2318 hir::Return(ref output) => self.ast_ty_to_ty(output),
2319 hir::DefaultReturn(..) => tcx.mk_unit(),
2322 debug!("ty_of_fn: output_ty={:?}", output_ty);
2324 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
2332 // Find any late-bound regions declared in return type that do
2333 // not appear in the arguments. These are not well-formed.
2336 // for<'a> fn() -> &'a str <-- 'a is bad
2337 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2338 let inputs = bare_fn_ty.inputs();
2339 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
2340 &inputs.map_bound(|i| i.to_owned()));
2341 let output = bare_fn_ty.output();
2342 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2343 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2344 let lifetime_name = match *br {
2345 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2346 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2348 let mut err = struct_span_err!(tcx.sess,
2351 "return type references {} \
2352 which is not constrained by the fn input types",
2354 if let ty::BrAnon(_) = *br {
2355 // The only way for an anonymous lifetime to wind up
2356 // in the return type but **also** be unconstrained is
2357 // if it only appears in "associated types" in the
2358 // input. See #47511 for an example. In this case,
2359 // though we can easily give a hint that ought to be
2361 err.note("lifetimes appearing in an associated type \
2362 are not considered constrained");
2370 /// Given the bounds on an object, determines what single region bound (if any) we can
2371 /// use to summarize this type. The basic idea is that we will use the bound the user
2372 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2373 /// for region bounds. It may be that we can derive no bound at all, in which case
2374 /// we return `None`.
2375 fn compute_object_lifetime_bound(&self,
2377 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
2378 -> Option<ty::Region<'tcx>> // if None, use the default
2380 let tcx = self.tcx();
2382 debug!("compute_opt_region_bound(existential_predicates={:?})",
2383 existential_predicates);
2385 // No explicit region bound specified. Therefore, examine trait
2386 // bounds and see if we can derive region bounds from those.
2387 let derived_region_bounds =
2388 object_region_bounds(tcx, existential_predicates);
2390 // If there are no derived region bounds, then report back that we
2391 // can find no region bound. The caller will use the default.
2392 if derived_region_bounds.is_empty() {
2396 // If any of the derived region bounds are 'static, that is always
2398 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2399 return Some(tcx.lifetimes.re_static);
2402 // Determine whether there is exactly one unique region in the set
2403 // of derived region bounds. If so, use that. Otherwise, report an
2405 let r = derived_region_bounds[0];
2406 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2407 span_err!(tcx.sess, span, E0227,
2408 "ambiguous lifetime bound, explicit lifetime bound required");
2414 /// Collects together a list of bounds that are applied to some type,
2415 /// after they've been converted into `ty` form (from the HIR
2416 /// representations). These lists of bounds occur in many places in
2420 /// trait Foo: Bar + Baz { }
2421 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2423 /// fn foo<T: Bar + Baz>() { }
2424 /// ^^^^^^^^^ bounding the type parameter `T`
2426 /// impl dyn Bar + Baz
2427 /// ^^^^^^^^^ bounding the forgotten dynamic type
2430 /// Our representation is a bit mixed here -- in some cases, we
2431 /// include the self type (e.g., `trait_bounds`) but in others we do
2432 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2433 pub struct Bounds<'tcx> {
2434 /// A list of region bounds on the (implicit) self type. So if you
2435 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2436 /// the `T` is not explicitly included).
2437 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2439 /// A list of trait bounds. So if you had `T: Debug` this would be
2440 /// `T: Debug`. Note that the self-type is explicit here.
2441 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2443 /// A list of projection equality bounds. So if you had `T:
2444 /// Iterator<Item = u32>` this would include `<T as
2445 /// Iterator>::Item => u32`. Note that the self-type is explicit
2447 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2449 /// `Some` if there is *no* `?Sized` predicate. The `span`
2450 /// is the location in the source of the `T` declaration which can
2451 /// be cited as the source of the `T: Sized` requirement.
2452 pub implicitly_sized: Option<Span>,
2455 impl<'tcx> Bounds<'tcx> {
2456 /// Converts a bounds list into a flat set of predicates (like
2457 /// where-clauses). Because some of our bounds listings (e.g.,
2458 /// regions) don't include the self-type, you must supply the
2459 /// self-type here (the `param_ty` parameter).
2464 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2465 // If it could be sized, and is, add the `Sized` predicate.
2466 let sized_predicate = self.implicitly_sized.and_then(|span| {
2467 tcx.lang_items().sized_trait().map(|sized| {
2468 let trait_ref = ty::TraitRef {
2470 substs: tcx.mk_substs_trait(param_ty, &[])
2472 (trait_ref.to_predicate(), span)
2476 sized_predicate.into_iter().chain(
2477 self.region_bounds.iter().map(|&(region_bound, span)| {
2478 // Account for the binder being introduced below; no need to shift `param_ty`
2479 // because, at present at least, it can only refer to early-bound regions.
2480 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2481 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2482 (ty::Binder::dummy(outlives).to_predicate(), span)
2484 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2485 (bound_trait_ref.to_predicate(), span)
2488 self.projection_bounds.iter().map(|&(projection, span)| {
2489 (projection.to_predicate(), span)