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;
39 use rustc_error_codes::*;
42 pub struct PathSeg(pub DefId, pub usize);
44 pub trait AstConv<'tcx> {
45 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
47 fn item_def_id(&self) -> Option<DefId>;
49 /// Returns predicates in scope of the form `X: Foo`, where `X` is
50 /// a type parameter `X` with the given id `def_id`. This is a
51 /// subset of the full set of predicates.
53 /// This is used for one specific purpose: resolving "short-hand"
54 /// associated type references like `T::Item`. In principle, we
55 /// would do that by first getting the full set of predicates in
56 /// scope and then filtering down to find those that apply to `T`,
57 /// but this can lead to cycle errors. The problem is that we have
58 /// to do this resolution *in order to create the predicates in
59 /// the first place*. Hence, we have this "special pass".
60 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
62 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
65 param: Option<&ty::GenericParamDef>,
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 the const to use when a const is omitted.
77 param: Option<&ty::GenericParamDef>,
79 ) -> &'tcx Const<'tcx>;
81 /// Projecting an associated type from a (potentially)
82 /// higher-ranked trait reference is more complicated, because of
83 /// the possibility of late-bound regions appearing in the
84 /// associated type binding. This is not legal in function
85 /// signatures for that reason. In a function body, we can always
86 /// handle it because we can use inference variables to remove the
87 /// late-bound regions.
88 fn projected_ty_from_poly_trait_ref(&self,
91 poly_trait_ref: ty::PolyTraitRef<'tcx>)
94 /// Normalize an associated type coming from the user.
95 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
97 /// Invoked when we encounter an error from some prior pass
98 /// (e.g., resolve) that is translated into a ty-error. This is
99 /// used to help suppress derived errors typeck might otherwise
101 fn set_tainted_by_errors(&self);
103 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
106 pub enum SizedByDefault {
111 struct ConvertedBinding<'a, 'tcx> {
112 item_name: ast::Ident,
113 kind: ConvertedBindingKind<'a, 'tcx>,
117 enum ConvertedBindingKind<'a, 'tcx> {
119 Constraint(&'a [hir::GenericBound]),
123 enum GenericArgPosition {
125 Value, // e.g., functions
129 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
130 pub fn ast_region_to_region(&self,
131 lifetime: &hir::Lifetime,
132 def: Option<&ty::GenericParamDef>)
135 let tcx = self.tcx();
136 let lifetime_name = |def_id| {
137 tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap())
140 let r = match tcx.named_region(lifetime.hir_id) {
141 Some(rl::Region::Static) => {
142 tcx.lifetimes.re_static
145 Some(rl::Region::LateBound(debruijn, id, _)) => {
146 let name = lifetime_name(id);
147 tcx.mk_region(ty::ReLateBound(debruijn,
148 ty::BrNamed(id, name)))
151 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
152 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
155 Some(rl::Region::EarlyBound(index, id, _)) => {
156 let name = lifetime_name(id);
157 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
164 Some(rl::Region::Free(scope, id)) => {
165 let name = lifetime_name(id);
166 tcx.mk_region(ty::ReFree(ty::FreeRegion {
168 bound_region: ty::BrNamed(id, name)
171 // (*) -- not late-bound, won't change
175 self.re_infer(def, lifetime.span)
177 // This indicates an illegal lifetime
178 // elision. `resolve_lifetime` should have
179 // reported an error in this case -- but if
180 // not, let's error out.
181 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
183 // Supply some dummy value. We don't have an
184 // `re_error`, annoyingly, so use `'static`.
185 tcx.lifetimes.re_static
190 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
197 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
198 /// returns an appropriate set of substitutions for this particular reference to `I`.
199 pub fn ast_path_substs_for_ty(&self,
202 item_segment: &hir::PathSegment)
205 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
208 item_segment.generic_args(),
209 item_segment.infer_args,
213 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
218 /// Report error if there is an explicit type parameter when using `impl Trait`.
221 seg: &hir::PathSegment,
222 generics: &ty::Generics,
224 let explicit = !seg.infer_args;
225 let impl_trait = generics.params.iter().any(|param| match param.kind {
226 ty::GenericParamDefKind::Type {
227 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
232 if explicit && impl_trait {
234 seg.generic_args().args
238 GenericArg::Type(_) => Some(arg.span()),
241 .collect::<Vec<_>>();
243 let mut err = struct_span_err! {
247 "cannot provide explicit generic arguments when `impl Trait` is \
248 used in argument position"
252 err.span_label(span, "explicit generic argument not allowed");
261 /// Checks that the correct number of generic arguments have been provided.
262 /// Used specifically for function calls.
263 pub fn check_generic_arg_count_for_call(
267 seg: &hir::PathSegment,
268 is_method_call: bool,
270 let empty_args = P(hir::GenericArgs {
271 args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
273 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
274 Self::check_generic_arg_count(
278 if let Some(ref args) = seg.args {
284 GenericArgPosition::MethodCall
286 GenericArgPosition::Value
288 def.parent.is_none() && def.has_self, // `has_self`
289 seg.infer_args || suppress_mismatch, // `infer_args`
293 /// Checks that the correct number of generic arguments have been provided.
294 /// This is used both for datatypes and function calls.
295 fn check_generic_arg_count(
299 args: &hir::GenericArgs,
300 position: GenericArgPosition,
303 ) -> (bool, Option<Vec<Span>>) {
304 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
305 // that lifetimes will proceed types. So it suffices to check the number of each generic
306 // arguments in order to validate them with respect to the generic parameters.
307 let param_counts = def.own_counts();
308 let arg_counts = args.own_counts();
309 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
311 let mut defaults: ty::GenericParamCount = Default::default();
312 for param in &def.params {
314 GenericParamDefKind::Lifetime => {}
315 GenericParamDefKind::Type { has_default, .. } => {
316 defaults.types += has_default as usize
318 GenericParamDefKind::Const => {
319 // FIXME(const_generics:defaults)
324 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
325 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
328 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
329 let mut reported_late_bound_region_err = None;
330 if !infer_lifetimes {
331 if let Some(span_late) = def.has_late_bound_regions {
332 let msg = "cannot specify lifetime arguments explicitly \
333 if late bound lifetime parameters are present";
334 let note = "the late bound lifetime parameter is introduced here";
335 let span = args.args[0].span();
336 if position == GenericArgPosition::Value
337 && arg_counts.lifetimes != param_counts.lifetimes {
338 let mut err = tcx.sess.struct_span_err(span, msg);
339 err.span_note(span_late, note);
341 reported_late_bound_region_err = Some(true);
343 let mut multispan = MultiSpan::from_span(span);
344 multispan.push_span_label(span_late, note.to_string());
345 tcx.lint_hir(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
346 args.args[0].id(), multispan, msg);
347 reported_late_bound_region_err = Some(false);
352 let check_kind_count = |kind, required, permitted, provided, offset| {
354 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
361 // We enforce the following: `required` <= `provided` <= `permitted`.
362 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
363 // For other kinds (i.e., types), `permitted` may be greater than `required`.
364 if required <= provided && provided <= permitted {
365 return (reported_late_bound_region_err.unwrap_or(false), None);
368 // Unfortunately lifetime and type parameter mismatches are typically styled
369 // differently in diagnostics, which means we have a few cases to consider here.
370 let (bound, quantifier) = if required != permitted {
371 if provided < required {
372 (required, "at least ")
373 } else { // provided > permitted
374 (permitted, "at most ")
380 let mut potential_assoc_types: Option<Vec<Span>> = None;
381 let (spans, label) = if required == permitted && provided > permitted {
382 // In the case when the user has provided too many arguments,
383 // we want to point to the unexpected arguments.
384 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
386 .map(|arg| arg.span())
388 potential_assoc_types = Some(spans.clone());
389 (spans, format!( "unexpected {} argument", kind))
391 (vec![span], format!(
392 "expected {}{} {} argument{}",
400 let mut err = tcx.sess.struct_span_err_with_code(
403 "wrong number of {} arguments: expected {}{}, found {}",
409 DiagnosticId::Error("E0107".into())
412 err.span_label(span, label.as_str());
417 provided > required, // `suppress_error`
418 potential_assoc_types,
422 if reported_late_bound_region_err.is_none()
423 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes) {
426 param_counts.lifetimes,
427 param_counts.lifetimes,
428 arg_counts.lifetimes,
432 // FIXME(const_generics:defaults)
433 if !infer_args || arg_counts.consts > param_counts.consts {
439 arg_counts.lifetimes + arg_counts.types,
442 // Note that type errors are currently be emitted *after* const errors.
444 || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
447 param_counts.types - defaults.types - has_self as usize,
448 param_counts.types - has_self as usize,
450 arg_counts.lifetimes,
453 (reported_late_bound_region_err.unwrap_or(false), None)
457 /// Creates the relevant generic argument substitutions
458 /// corresponding to a set of generic parameters. This is a
459 /// rather complex function. Let us try to explain the role
460 /// of each of its parameters:
462 /// To start, we are given the `def_id` of the thing we are
463 /// creating the substitutions for, and a partial set of
464 /// substitutions `parent_substs`. In general, the substitutions
465 /// for an item begin with substitutions for all the "parents" of
466 /// that item -- e.g., for a method it might include the
467 /// parameters from the impl.
469 /// Therefore, the method begins by walking down these parents,
470 /// starting with the outermost parent and proceed inwards until
471 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
472 /// first to see if the parent's substitutions are listed in there. If so,
473 /// we can append those and move on. Otherwise, it invokes the
474 /// three callback functions:
476 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
477 /// generic arguments that were given to that parent from within
478 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
479 /// might refer to the trait `Foo`, and the arguments might be
480 /// `[T]`. The boolean value indicates whether to infer values
481 /// for arguments whose values were not explicitly provided.
482 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
483 /// instantiate a `GenericArg`.
484 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
485 /// creates a suitable inference variable.
486 pub fn create_substs_for_generic_args<'b>(
489 parent_substs: &[subst::GenericArg<'tcx>],
491 self_ty: Option<Ty<'tcx>>,
492 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
493 provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> subst::GenericArg<'tcx>,
494 inferred_kind: impl Fn(Option<&[subst::GenericArg<'tcx>]>, &GenericParamDef, bool)
495 -> subst::GenericArg<'tcx>,
496 ) -> SubstsRef<'tcx> {
497 // Collect the segments of the path; we need to substitute arguments
498 // for parameters throughout the entire path (wherever there are
499 // generic parameters).
500 let mut parent_defs = tcx.generics_of(def_id);
501 let count = parent_defs.count();
502 let mut stack = vec![(def_id, parent_defs)];
503 while let Some(def_id) = parent_defs.parent {
504 parent_defs = tcx.generics_of(def_id);
505 stack.push((def_id, parent_defs));
508 // We manually build up the substitution, rather than using convenience
509 // methods in `subst.rs`, so that we can iterate over the arguments and
510 // parameters in lock-step linearly, instead of trying to match each pair.
511 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
513 // Iterate over each segment of the path.
514 while let Some((def_id, defs)) = stack.pop() {
515 let mut params = defs.params.iter().peekable();
517 // If we have already computed substitutions for parents, we can use those directly.
518 while let Some(¶m) = params.peek() {
519 if let Some(&kind) = parent_substs.get(param.index as usize) {
527 // `Self` is handled first, unless it's been handled in `parent_substs`.
529 if let Some(¶m) = params.peek() {
530 if param.index == 0 {
531 if let GenericParamDefKind::Type { .. } = param.kind {
532 substs.push(self_ty.map(|ty| ty.into())
533 .unwrap_or_else(|| inferred_kind(None, param, true)));
540 // Check whether this segment takes generic arguments and the user has provided any.
541 let (generic_args, infer_args) = args_for_def_id(def_id);
543 let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
547 // We're going to iterate through the generic arguments that the user
548 // provided, matching them with the generic parameters we expect.
549 // Mismatches can occur as a result of elided lifetimes, or for malformed
550 // input. We try to handle both sensibly.
551 match (args.peek(), params.peek()) {
552 (Some(&arg), Some(¶m)) => {
553 match (arg, ¶m.kind) {
554 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
555 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
556 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
557 substs.push(provided_kind(param, arg));
561 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
562 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
563 // We expected a lifetime argument, but got a type or const
564 // argument. That means we're inferring the lifetimes.
565 substs.push(inferred_kind(None, param, infer_args));
569 // We expected one kind of parameter, but the user provided
570 // another. This is an error, but we need to handle it
571 // gracefully so we can report sensible errors.
572 // In this case, we're simply going to infer this argument.
578 // We should never be able to reach this point with well-formed input.
579 // Getting to this point means the user supplied more arguments than
580 // there are parameters.
583 (None, Some(¶m)) => {
584 // If there are fewer arguments than parameters, it means
585 // we're inferring the remaining arguments.
586 substs.push(inferred_kind(Some(&substs), param, infer_args));
590 (None, None) => break,
595 tcx.intern_substs(&substs)
598 /// Given the type/lifetime/const arguments provided to some path (along with
599 /// an implicit `Self`, if this is a trait reference), returns the complete
600 /// set of substitutions. This may involve applying defaulted type parameters.
601 /// Also returns back constriants on associated types.
606 /// T: std::ops::Index<usize, Output = u32>
607 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
610 /// 1. The `self_ty` here would refer to the type `T`.
611 /// 2. The path in question is the path to the trait `std::ops::Index`,
612 /// which will have been resolved to a `def_id`
613 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
614 /// parameters are returned in the `SubstsRef`, the associated type bindings like
615 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
617 /// Note that the type listing given here is *exactly* what the user provided.
618 fn create_substs_for_ast_path<'a>(&self,
621 generic_args: &'a hir::GenericArgs,
623 self_ty: Option<Ty<'tcx>>)
624 -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>)
626 // If the type is parameterized by this region, then replace this
627 // region with the current anon region binding (in other words,
628 // whatever & would get replaced with).
629 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
631 def_id, self_ty, generic_args);
633 let tcx = self.tcx();
634 let generic_params = tcx.generics_of(def_id);
636 // If a self-type was declared, one should be provided.
637 assert_eq!(generic_params.has_self, self_ty.is_some());
639 let has_self = generic_params.has_self;
640 let (_, potential_assoc_types) = Self::check_generic_arg_count(
645 GenericArgPosition::Type,
650 let is_object = self_ty.map_or(false, |ty| {
651 ty == self.tcx().types.trait_object_dummy_self
653 let default_needs_object_self = |param: &ty::GenericParamDef| {
654 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
655 if is_object && has_default && has_self {
656 let self_param = tcx.types.self_param;
657 if tcx.at(span).type_of(param.def_id).walk().any(|ty| ty == self_param) {
658 // There is no suitable inference default for a type parameter
659 // that references self, in an object type.
668 let substs = Self::create_substs_for_generic_args(
674 // Provide the generic args, and whether types should be inferred.
675 |_| (Some(generic_args), infer_args),
676 // Provide substitutions for parameters for which (valid) arguments have been provided.
678 match (¶m.kind, arg) {
679 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
680 self.ast_region_to_region(<, Some(param)).into()
682 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
683 self.ast_ty_to_ty(&ty).into()
685 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
686 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
691 // Provide substitutions for parameters for which arguments are inferred.
692 |substs, param, infer_args| {
694 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
695 GenericParamDefKind::Type { has_default, .. } => {
696 if !infer_args && has_default {
697 // No type parameter provided, but a default exists.
699 // If we are converting an object type, then the
700 // `Self` parameter is unknown. However, some of the
701 // other type parameters may reference `Self` in their
702 // defaults. This will lead to an ICE if we are not
704 if default_needs_object_self(param) {
705 struct_span_err!(tcx.sess, span, E0393,
706 "the type parameter `{}` must be explicitly specified",
709 .span_label(span, format!(
710 "missing reference to `{}`", param.name))
712 "because of the default `Self` reference, type parameters \
713 must be specified on object types"))
717 // This is a default type parameter.
720 tcx.at(span).type_of(param.def_id)
721 .subst_spanned(tcx, substs.unwrap(), Some(span))
724 } else if infer_args {
725 // No type parameters were provided, we can infer all.
726 let param = if !default_needs_object_self(param) {
731 self.ty_infer(param, span).into()
733 // We've already errored above about the mismatch.
737 GenericParamDefKind::Const => {
738 // FIXME(const_generics:defaults)
740 // No const parameters were provided, we can infer all.
741 let ty = tcx.at(span).type_of(param.def_id);
742 self.ct_infer(ty, Some(param), span).into()
744 // We've already errored above about the mismatch.
745 tcx.consts.err.into()
752 // Convert associated-type bindings or constraints into a separate vector.
753 // Example: Given this:
755 // T: Iterator<Item = u32>
757 // The `T` is passed in as a self-type; the `Item = u32` is
758 // not a "type parameter" of the `Iterator` trait, but rather
759 // a restriction on `<T as Iterator>::Item`, so it is passed
761 let assoc_bindings = generic_args.bindings.iter()
763 let kind = match binding.kind {
764 hir::TypeBindingKind::Equality { ref ty } =>
765 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty)),
766 hir::TypeBindingKind::Constraint { ref bounds } =>
767 ConvertedBindingKind::Constraint(bounds),
770 item_name: binding.ident,
777 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
778 generic_params, self_ty, substs);
780 (substs, assoc_bindings, potential_assoc_types)
783 /// Instantiates the path for the given trait reference, assuming that it's
784 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
785 /// The type _cannot_ be a type other than a trait type.
787 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
788 /// are disallowed. Otherwise, they are pushed onto the vector given.
789 pub fn instantiate_mono_trait_ref(&self,
790 trait_ref: &hir::TraitRef,
792 ) -> ty::TraitRef<'tcx>
794 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
796 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
797 trait_ref.trait_def_id(),
799 trait_ref.path.segments.last().unwrap())
802 /// The given trait-ref must actually be a trait.
803 pub(super) fn instantiate_poly_trait_ref_inner(&self,
804 trait_ref: &hir::TraitRef,
807 bounds: &mut Bounds<'tcx>,
809 ) -> Option<Vec<Span>> {
810 let trait_def_id = trait_ref.trait_def_id();
812 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
814 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
816 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
820 trait_ref.path.segments.last().unwrap(),
822 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
824 bounds.trait_bounds.push((poly_trait_ref, span));
826 let mut dup_bindings = FxHashMap::default();
827 for binding in &assoc_bindings {
828 // Specify type to assert that error was already reported in `Err` case.
829 let _: Result<_, ErrorReported> =
830 self.add_predicates_for_ast_type_binding(
831 trait_ref.hir_ref_id,
838 // Okay to ignore `Err` because of `ErrorReported` (see above).
841 debug!("instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
842 trait_ref, bounds, poly_trait_ref);
843 potential_assoc_types
846 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
847 /// a full trait reference. The resulting trait reference is returned. This may also generate
848 /// auxiliary bounds, which are added to `bounds`.
853 /// poly_trait_ref = Iterator<Item = u32>
857 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
859 /// **A note on binders:** against our usual convention, there is an implied bounder around
860 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
861 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
862 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
863 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
865 pub fn instantiate_poly_trait_ref(&self,
866 poly_trait_ref: &hir::PolyTraitRef,
868 bounds: &mut Bounds<'tcx>,
869 ) -> Option<Vec<Span>> {
870 self.instantiate_poly_trait_ref_inner(
871 &poly_trait_ref.trait_ref,
879 fn ast_path_to_mono_trait_ref(&self,
883 trait_segment: &hir::PathSegment
884 ) -> ty::TraitRef<'tcx>
886 let (substs, assoc_bindings, _) =
887 self.create_substs_for_ast_trait_ref(span,
891 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
892 ty::TraitRef::new(trait_def_id, substs)
895 fn create_substs_for_ast_trait_ref<'a>(
900 trait_segment: &'a hir::PathSegment,
901 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
902 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
905 let trait_def = self.tcx().trait_def(trait_def_id);
907 if !self.tcx().features().unboxed_closures &&
908 trait_segment.generic_args().parenthesized != trait_def.paren_sugar
910 // For now, require that parenthetical notation be used only with `Fn()` etc.
911 let msg = if trait_def.paren_sugar {
912 "the precise format of `Fn`-family traits' type parameters is subject to change. \
913 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
915 "parenthetical notation is only stable when used with `Fn`-family traits"
917 emit_feature_err(&self.tcx().sess.parse_sess, sym::unboxed_closures,
918 span, GateIssue::Language, msg);
921 self.create_substs_for_ast_path(span,
923 trait_segment.generic_args(),
924 trait_segment.infer_args,
928 fn trait_defines_associated_type_named(&self,
930 assoc_name: ast::Ident)
933 self.tcx().associated_items(trait_def_id).any(|item| {
934 item.kind == ty::AssocKind::Type &&
935 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
939 // Returns `true` if a bounds list includes `?Sized`.
940 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound], span: Span) -> bool {
941 let tcx = self.tcx();
943 // Try to find an unbound in bounds.
944 let mut unbound = None;
945 for ab in ast_bounds {
946 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
947 if unbound.is_none() {
948 unbound = Some(&ptr.trait_ref);
954 "type parameter has more than one relaxed default \
955 bound, only one is supported"
961 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
964 // FIXME(#8559) currently requires the unbound to be built-in.
965 if let Ok(kind_id) = kind_id {
966 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
969 "default bound relaxed for a type parameter, but \
970 this does nothing because the given bound is not \
971 a default; only `?Sized` is supported",
976 _ if kind_id.is_ok() => {
979 // No lang item for `Sized`, so we can't add it as a bound.
986 /// This helper takes a *converted* parameter type (`param_ty`)
987 /// and an *unconverted* list of bounds:
991 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
993 /// `param_ty`, in ty form
996 /// It adds these `ast_bounds` into the `bounds` structure.
998 /// **A note on binders:** there is an implied binder around
999 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1000 /// for more details.
1001 fn add_bounds(&self,
1003 ast_bounds: &[hir::GenericBound],
1004 bounds: &mut Bounds<'tcx>,
1006 let mut trait_bounds = Vec::new();
1007 let mut region_bounds = Vec::new();
1009 for ast_bound in ast_bounds {
1011 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) =>
1012 trait_bounds.push(b),
1013 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1014 hir::GenericBound::Outlives(ref l) =>
1015 region_bounds.push(l),
1019 for bound in trait_bounds {
1020 let _ = self.instantiate_poly_trait_ref(
1027 bounds.region_bounds.extend(region_bounds
1029 .map(|r| (self.ast_region_to_region(r, None), r.span))
1033 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1034 /// The self-type for the bounds is given by `param_ty`.
1039 /// fn foo<T: Bar + Baz>() { }
1040 /// ^ ^^^^^^^^^ ast_bounds
1044 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1045 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1046 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1048 /// `span` should be the declaration size of the parameter.
1049 pub fn compute_bounds(&self,
1051 ast_bounds: &[hir::GenericBound],
1052 sized_by_default: SizedByDefault,
1055 let mut bounds = Bounds::default();
1057 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1058 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1060 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1061 if !self.is_unsized(ast_bounds, span) {
1073 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1076 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1077 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1078 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1079 fn add_predicates_for_ast_type_binding(
1081 hir_ref_id: hir::HirId,
1082 trait_ref: ty::PolyTraitRef<'tcx>,
1083 binding: &ConvertedBinding<'_, 'tcx>,
1084 bounds: &mut Bounds<'tcx>,
1086 dup_bindings: &mut FxHashMap<DefId, Span>,
1087 ) -> Result<(), ErrorReported> {
1088 let tcx = self.tcx();
1091 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1092 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1093 // subtle in the event that `T` is defined in a supertrait of
1094 // `SomeTrait`, because in that case we need to upcast.
1096 // That is, consider this case:
1099 // trait SubTrait: SuperTrait<int> { }
1100 // trait SuperTrait<A> { type T; }
1102 // ... B: SubTrait<T = foo> ...
1105 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1107 // Find any late-bound regions declared in `ty` that are not
1108 // declared in the trait-ref. These are not well-formed.
1112 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1113 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1114 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1115 let late_bound_in_trait_ref =
1116 tcx.collect_constrained_late_bound_regions(&trait_ref);
1117 let late_bound_in_ty =
1118 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1119 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1120 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1121 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1122 let br_name = match *br {
1123 ty::BrNamed(_, name) => name,
1127 "anonymous bound region {:?} in binding but not trait ref",
1131 struct_span_err!(tcx.sess,
1134 "binding for associated type `{}` references lifetime `{}`, \
1135 which does not appear in the trait input types",
1136 binding.item_name, br_name)
1142 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
1143 binding.item_name) {
1144 // Simple case: X is defined in the current trait.
1147 // Otherwise, we have to walk through the supertraits to find
1149 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
1150 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
1152 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
1153 binding.item_name, binding.span)
1156 let (assoc_ident, def_scope) =
1157 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1158 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
1159 i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident
1160 }).expect("missing associated type");
1162 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1163 let msg = format!("associated type `{}` is private", binding.item_name);
1164 tcx.sess.span_err(binding.span, &msg);
1166 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1169 dup_bindings.entry(assoc_ty.def_id)
1170 .and_modify(|prev_span| {
1171 struct_span_err!(self.tcx().sess, binding.span, E0719,
1172 "the value of the associated type `{}` (from the trait `{}`) \
1173 is already specified",
1175 tcx.def_path_str(assoc_ty.container.id()))
1176 .span_label(binding.span, "re-bound here")
1177 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1180 .or_insert(binding.span);
1183 match binding.kind {
1184 ConvertedBindingKind::Equality(ref ty) => {
1185 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1186 // the "projection predicate" for:
1188 // `<T as Iterator>::Item = u32`
1189 bounds.projection_bounds.push((candidate.map_bound(|trait_ref| {
1190 ty::ProjectionPredicate {
1191 projection_ty: ty::ProjectionTy::from_ref_and_name(
1200 ConvertedBindingKind::Constraint(ast_bounds) => {
1201 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1203 // `<T as Iterator>::Item: Debug`
1205 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1206 // parameter to have a skipped binder.
1207 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1208 self.add_bounds(param_ty, ast_bounds, bounds);
1214 fn ast_path_to_ty(&self,
1217 item_segment: &hir::PathSegment)
1220 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1223 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
1227 fn conv_object_ty_poly_trait_ref(&self,
1229 trait_bounds: &[hir::PolyTraitRef],
1230 lifetime: &hir::Lifetime)
1233 let tcx = self.tcx();
1235 let mut bounds = Bounds::default();
1236 let mut potential_assoc_types = Vec::new();
1237 let dummy_self = self.tcx().types.trait_object_dummy_self;
1238 for trait_bound in trait_bounds.iter().rev() {
1239 let cur_potential_assoc_types = self.instantiate_poly_trait_ref(
1244 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1247 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1248 // is used and no 'maybe' bounds are used.
1249 let expanded_traits =
1250 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1251 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1252 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1253 if regular_traits.len() > 1 {
1254 let first_trait = ®ular_traits[0];
1255 let additional_trait = ®ular_traits[1];
1256 let mut err = struct_span_err!(tcx.sess, additional_trait.bottom().1, E0225,
1257 "only auto traits can be used as additional traits in a trait object"
1259 additional_trait.label_with_exp_info(&mut err,
1260 "additional non-auto trait", "additional use");
1261 first_trait.label_with_exp_info(&mut err,
1262 "first non-auto trait", "first use");
1266 if regular_traits.is_empty() && auto_traits.is_empty() {
1267 span_err!(tcx.sess, span, E0224,
1268 "at least one trait is required for an object type");
1269 return tcx.types.err;
1272 // Check that there are no gross object safety violations;
1273 // most importantly, that the supertraits don't contain `Self`,
1275 for item in ®ular_traits {
1276 let object_safety_violations =
1277 tcx.astconv_object_safety_violations(item.trait_ref().def_id());
1278 if !object_safety_violations.is_empty() {
1279 tcx.report_object_safety_error(
1281 item.trait_ref().def_id(),
1282 object_safety_violations
1284 return tcx.types.err;
1288 // Use a `BTreeSet` to keep output in a more consistent order.
1289 let mut associated_types = BTreeSet::default();
1291 let regular_traits_refs = bounds.trait_bounds
1293 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()))
1294 .map(|(trait_ref, _)| trait_ref);
1295 for trait_ref in traits::elaborate_trait_refs(tcx, regular_traits_refs) {
1296 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", trait_ref);
1298 ty::Predicate::Trait(pred) => {
1300 .extend(tcx.associated_items(pred.def_id())
1301 .filter(|item| item.kind == ty::AssocKind::Type)
1302 .map(|item| item.def_id));
1304 ty::Predicate::Projection(pred) => {
1305 // A `Self` within the original bound will be substituted with a
1306 // `trait_object_dummy_self`, so check for that.
1307 let references_self =
1308 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1310 // If the projection output contains `Self`, force the user to
1311 // elaborate it explicitly to avoid a lot of complexity.
1313 // The "classicaly useful" case is the following:
1315 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1320 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1321 // but actually supporting that would "expand" to an infinitely-long type
1322 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1324 // Instead, we force the user to write `dyn MyTrait<MyOutput = X, Output = X>`,
1325 // which is uglier but works. See the discussion in #56288 for alternatives.
1326 if !references_self {
1327 // Include projections defined on supertraits.
1328 bounds.projection_bounds.push((pred, DUMMY_SP))
1335 for (projection_bound, _) in &bounds.projection_bounds {
1336 associated_types.remove(&projection_bound.projection_def_id());
1339 if !associated_types.is_empty() {
1340 let names = associated_types.iter().map(|item_def_id| {
1341 let assoc_item = tcx.associated_item(*item_def_id);
1342 let trait_def_id = assoc_item.container.id();
1344 "`{}` (from the trait `{}`)",
1346 tcx.def_path_str(trait_def_id),
1348 }).collect::<Vec<_>>().join(", ");
1349 let mut err = struct_span_err!(
1353 "the value of the associated type{} {} must be specified",
1354 pluralize!(associated_types.len()),
1357 let (suggest, potential_assoc_types_spans) =
1358 if potential_assoc_types.len() == associated_types.len() {
1359 // Only suggest when the amount of missing associated types equals the number of
1360 // extra type arguments present, as that gives us a relatively high confidence
1361 // that the user forgot to give the associtated type's name. The canonical
1362 // example would be trying to use `Iterator<isize>` instead of
1363 // `Iterator<Item = isize>`.
1364 (true, potential_assoc_types)
1368 let mut suggestions = Vec::new();
1369 for (i, item_def_id) in associated_types.iter().enumerate() {
1370 let assoc_item = tcx.associated_item(*item_def_id);
1373 format!("associated type `{}` must be specified", assoc_item.ident),
1375 if let Some(sp) = tcx.hir().span_if_local(*item_def_id) {
1376 err.span_label(sp, format!("`{}` defined here", assoc_item.ident));
1379 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1380 potential_assoc_types_spans[i],
1383 potential_assoc_types_spans[i],
1384 format!("{} = {}", assoc_item.ident, snippet),
1389 if !suggestions.is_empty() {
1390 let msg = format!("if you meant to specify the associated {}, write",
1391 if suggestions.len() == 1 { "type" } else { "types" });
1392 err.multipart_suggestion(
1395 Applicability::MaybeIncorrect,
1401 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1402 // `dyn Trait + Send`.
1403 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1404 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1405 debug!("regular_traits: {:?}", regular_traits);
1406 debug!("auto_traits: {:?}", auto_traits);
1408 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1409 // removing the dummy `Self` type (`trait_object_dummy_self`).
1410 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1411 if trait_ref.self_ty() != dummy_self {
1412 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1413 // which picks up non-supertraits where clauses - but also, the object safety
1414 // completely ignores trait aliases, which could be object safety hazards. We
1415 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1416 // disabled. (#66420)
1417 tcx.sess.delay_span_bug(DUMMY_SP, &format!(
1418 "trait_ref_to_existential called on {:?} with non-dummy Self",
1422 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1425 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1426 let existential_trait_refs = regular_traits.iter().map(|i| {
1427 i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref))
1429 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1430 bound.map_bound(|b| {
1431 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1432 ty::ExistentialProjection {
1434 item_def_id: b.projection_ty.item_def_id,
1435 substs: trait_ref.substs,
1440 // Calling `skip_binder` is okay because the predicates are re-bound.
1441 let regular_trait_predicates = existential_trait_refs.map(
1442 |trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1443 let auto_trait_predicates = auto_traits.into_iter().map(
1444 |trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1446 regular_trait_predicates
1447 .chain(auto_trait_predicates)
1448 .chain(existential_projections
1449 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1450 .collect::<SmallVec<[_; 8]>>();
1451 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1453 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1455 // Use explicitly-specified region bound.
1456 let region_bound = if !lifetime.is_elided() {
1457 self.ast_region_to_region(lifetime, None)
1459 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1460 if tcx.named_region(lifetime.hir_id).is_some() {
1461 self.ast_region_to_region(lifetime, None)
1463 self.re_infer(None, span).unwrap_or_else(|| {
1464 span_err!(tcx.sess, span, E0228,
1465 "the lifetime bound for this object type cannot be deduced \
1466 from context; please supply an explicit bound");
1467 tcx.lifetimes.re_static
1472 debug!("region_bound: {:?}", region_bound);
1474 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1475 debug!("trait_object_type: {:?}", ty);
1479 fn report_ambiguous_associated_type(
1486 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1487 if let (Some(_), Ok(snippet)) = (
1488 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1489 self.tcx().sess.source_map().span_to_snippet(span),
1491 err.span_suggestion(
1493 "you are looking for the module in `std`, not the primitive type",
1494 format!("std::{}", snippet),
1495 Applicability::MachineApplicable,
1498 err.span_suggestion(
1500 "use fully-qualified syntax",
1501 format!("<{} as {}>::{}", type_str, trait_str, name),
1502 Applicability::HasPlaceholders
1508 // Search for a bound on a type parameter which includes the associated item
1509 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1510 // This function will fail if there are no suitable bounds or there is
1512 fn find_bound_for_assoc_item(&self,
1513 ty_param_def_id: DefId,
1514 assoc_name: ast::Ident,
1516 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1518 let tcx = self.tcx();
1521 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1527 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1529 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1531 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1533 // Check that there is exactly one way to find an associated type with the
1535 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1536 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1538 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1539 let param_name = tcx.hir().ty_param_name(param_hir_id);
1540 self.one_bound_for_assoc_type(suitable_bounds,
1541 ¶m_name.as_str(),
1546 // Checks that `bounds` contains exactly one element and reports appropriate
1547 // errors otherwise.
1548 fn one_bound_for_assoc_type<I>(&self,
1550 ty_param_name: &str,
1551 assoc_name: ast::Ident,
1553 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1554 where I: Iterator<Item = ty::PolyTraitRef<'tcx>>
1556 let bound = match bounds.next() {
1557 Some(bound) => bound,
1559 struct_span_err!(self.tcx().sess, span, E0220,
1560 "associated type `{}` not found for `{}`",
1563 .span_label(span, format!("associated type `{}` not found", assoc_name))
1565 return Err(ErrorReported);
1569 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1571 if let Some(bound2) = bounds.next() {
1572 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1574 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1575 let mut err = struct_span_err!(
1576 self.tcx().sess, span, E0221,
1577 "ambiguous associated type `{}` in bounds of `{}`",
1580 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1582 for bound in bounds {
1583 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1584 item.kind == ty::AssocKind::Type &&
1585 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1587 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1589 if let Some(span) = bound_span {
1590 err.span_label(span, format!("ambiguous `{}` from `{}`",
1594 span_note!(&mut err, span,
1595 "associated type `{}` could derive from `{}`",
1606 // Create a type from a path to an associated type.
1607 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1608 // and item_segment is the path segment for `D`. We return a type and a def for
1610 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1611 // parameter or `Self`.
1612 pub fn associated_path_to_ty(
1614 hir_ref_id: hir::HirId,
1618 assoc_segment: &hir::PathSegment,
1619 permit_variants: bool,
1620 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1621 let tcx = self.tcx();
1622 let assoc_ident = assoc_segment.ident;
1624 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1626 self.prohibit_generics(slice::from_ref(assoc_segment));
1628 // Check if we have an enum variant.
1629 let mut variant_resolution = None;
1630 if let ty::Adt(adt_def, _) = qself_ty.kind {
1631 if adt_def.is_enum() {
1632 let variant_def = adt_def.variants.iter().find(|vd| {
1633 tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1635 if let Some(variant_def) = variant_def {
1636 if permit_variants {
1637 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1638 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1640 variant_resolution = Some(variant_def.def_id);
1646 // Find the type of the associated item, and the trait where the associated
1647 // item is declared.
1648 let bound = match (&qself_ty.kind, qself_res) {
1649 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
1650 // `Self` in an impl of a trait -- we have a concrete self type and a
1652 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1653 Some(trait_ref) => trait_ref,
1655 // A cycle error occurred, most likely.
1656 return Err(ErrorReported);
1660 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1661 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1663 self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span)?
1665 (&ty::Param(_), Res::SelfTy(Some(param_did), None)) |
1666 (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
1667 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
1670 if variant_resolution.is_some() {
1671 // Variant in type position
1672 let msg = format!("expected type, found variant `{}`", assoc_ident);
1673 tcx.sess.span_err(span, &msg);
1674 } else if qself_ty.is_enum() {
1675 let mut err = tcx.sess.struct_span_err(
1677 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
1680 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1681 if let Some(suggested_name) = find_best_match_for_name(
1682 adt_def.variants.iter().map(|variant| &variant.ident.name),
1683 &assoc_ident.as_str(),
1686 err.span_suggestion(
1688 "there is a variant with a similar name",
1689 suggested_name.to_string(),
1690 Applicability::MaybeIncorrect,
1695 format!("variant not found in `{}`", qself_ty),
1699 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1700 let sp = tcx.sess.source_map().def_span(sp);
1701 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1705 } else if !qself_ty.references_error() {
1706 // Don't print `TyErr` to the user.
1707 self.report_ambiguous_associated_type(
1709 &qself_ty.to_string(),
1714 return Err(ErrorReported);
1718 let trait_did = bound.def_id();
1719 let (assoc_ident, def_scope) =
1720 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1721 let item = tcx.associated_items(trait_did).find(|i| {
1722 Namespace::from(i.kind) == Namespace::Type &&
1723 i.ident.modern() == assoc_ident
1724 }).expect("missing associated type");
1726 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1727 let ty = self.normalize_ty(span, ty);
1729 let kind = DefKind::AssocTy;
1730 if !item.vis.is_accessible_from(def_scope, tcx) {
1731 let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
1732 tcx.sess.span_err(span, &msg);
1734 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1736 if let Some(variant_def_id) = variant_resolution {
1737 let mut err = tcx.struct_span_lint_hir(
1738 AMBIGUOUS_ASSOCIATED_ITEMS,
1741 "ambiguous associated item",
1744 let mut could_refer_to = |kind: DefKind, def_id, also| {
1745 let note_msg = format!("`{}` could{} refer to {} defined here",
1746 assoc_ident, also, kind.descr(def_id));
1747 err.span_note(tcx.def_span(def_id), ¬e_msg);
1749 could_refer_to(DefKind::Variant, variant_def_id, "");
1750 could_refer_to(kind, item.def_id, " also");
1752 err.span_suggestion(
1754 "use fully-qualified syntax",
1755 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1756 Applicability::MachineApplicable,
1760 Ok((ty, kind, item.def_id))
1763 fn qpath_to_ty(&self,
1765 opt_self_ty: Option<Ty<'tcx>>,
1767 trait_segment: &hir::PathSegment,
1768 item_segment: &hir::PathSegment)
1771 let tcx = self.tcx();
1773 let trait_def_id = tcx.parent(item_def_id).unwrap();
1775 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1777 self.prohibit_generics(slice::from_ref(item_segment));
1779 let self_ty = if let Some(ty) = opt_self_ty {
1782 let path_str = tcx.def_path_str(trait_def_id);
1784 let def_id = self.item_def_id();
1786 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1788 let parent_def_id = def_id.and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
1789 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
1791 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1793 // If the trait in segment is the same as the trait defining the item,
1794 // use the `<Self as ..>` syntax in the error.
1795 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1796 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1798 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1804 self.report_ambiguous_associated_type(
1808 item_segment.ident.name,
1810 return tcx.types.err;
1813 debug!("qpath_to_ty: self_type={:?}", self_ty);
1815 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1820 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1822 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1825 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1826 &self, segments: T) -> bool {
1827 let mut has_err = false;
1828 for segment in segments {
1829 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1830 for arg in &segment.generic_args().args {
1831 let (span, kind) = match arg {
1832 hir::GenericArg::Lifetime(lt) => {
1833 if err_for_lt { continue }
1836 (lt.span, "lifetime")
1838 hir::GenericArg::Type(ty) => {
1839 if err_for_ty { continue }
1844 hir::GenericArg::Const(ct) => {
1845 if err_for_ct { continue }
1850 let mut err = struct_span_err!(
1854 "{} arguments are not allowed for this type",
1857 err.span_label(span, format!("{} argument not allowed", kind));
1859 if err_for_lt && err_for_ty && err_for_ct {
1863 for binding in &segment.generic_args().bindings {
1865 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1872 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
1873 let mut err = struct_span_err!(tcx.sess, span, E0229,
1874 "associated type bindings are not allowed here");
1875 err.span_label(span, "associated type not allowed here").emit();
1878 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1879 pub fn def_ids_for_value_path_segments(
1881 segments: &[hir::PathSegment],
1882 self_ty: Option<Ty<'tcx>>,
1886 // We need to extract the type parameters supplied by the user in
1887 // the path `path`. Due to the current setup, this is a bit of a
1888 // tricky-process; the problem is that resolve only tells us the
1889 // end-point of the path resolution, and not the intermediate steps.
1890 // Luckily, we can (at least for now) deduce the intermediate steps
1891 // just from the end-point.
1893 // There are basically five cases to consider:
1895 // 1. Reference to a constructor of a struct:
1897 // struct Foo<T>(...)
1899 // In this case, the parameters are declared in the type space.
1901 // 2. Reference to a constructor of an enum variant:
1903 // enum E<T> { Foo(...) }
1905 // In this case, the parameters are defined in the type space,
1906 // but may be specified either on the type or the variant.
1908 // 3. Reference to a fn item or a free constant:
1912 // In this case, the path will again always have the form
1913 // `a::b::foo::<T>` where only the final segment should have
1914 // type parameters. However, in this case, those parameters are
1915 // declared on a value, and hence are in the `FnSpace`.
1917 // 4. Reference to a method or an associated constant:
1919 // impl<A> SomeStruct<A> {
1923 // Here we can have a path like
1924 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1925 // may appear in two places. The penultimate segment,
1926 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1927 // final segment, `foo::<B>` contains parameters in fn space.
1929 // The first step then is to categorize the segments appropriately.
1931 let tcx = self.tcx();
1933 assert!(!segments.is_empty());
1934 let last = segments.len() - 1;
1936 let mut path_segs = vec![];
1939 // Case 1. Reference to a struct constructor.
1940 DefKind::Ctor(CtorOf::Struct, ..) => {
1941 // Everything but the final segment should have no
1942 // parameters at all.
1943 let generics = tcx.generics_of(def_id);
1944 // Variant and struct constructors use the
1945 // generics of their parent type definition.
1946 let generics_def_id = generics.parent.unwrap_or(def_id);
1947 path_segs.push(PathSeg(generics_def_id, last));
1950 // Case 2. Reference to a variant constructor.
1951 DefKind::Ctor(CtorOf::Variant, ..)
1952 | DefKind::Variant => {
1953 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1954 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1955 debug_assert!(adt_def.is_enum());
1957 } else if last >= 1 && segments[last - 1].args.is_some() {
1958 // Everything but the penultimate segment should have no
1959 // parameters at all.
1960 let mut def_id = def_id;
1962 // `DefKind::Ctor` -> `DefKind::Variant`
1963 if let DefKind::Ctor(..) = kind {
1964 def_id = tcx.parent(def_id).unwrap()
1967 // `DefKind::Variant` -> `DefKind::Enum`
1968 let enum_def_id = tcx.parent(def_id).unwrap();
1969 (enum_def_id, last - 1)
1971 // FIXME: lint here recommending `Enum::<...>::Variant` form
1972 // instead of `Enum::Variant::<...>` form.
1974 // Everything but the final segment should have no
1975 // parameters at all.
1976 let generics = tcx.generics_of(def_id);
1977 // Variant and struct constructors use the
1978 // generics of their parent type definition.
1979 (generics.parent.unwrap_or(def_id), last)
1981 path_segs.push(PathSeg(generics_def_id, index));
1984 // Case 3. Reference to a top-level value.
1987 | DefKind::ConstParam
1988 | DefKind::Static => {
1989 path_segs.push(PathSeg(def_id, last));
1992 // Case 4. Reference to a method or associated const.
1994 | DefKind::AssocConst => {
1995 if segments.len() >= 2 {
1996 let generics = tcx.generics_of(def_id);
1997 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1999 path_segs.push(PathSeg(def_id, last));
2002 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2005 debug!("path_segs = {:?}", path_segs);
2010 // Check a type `Path` and convert it to a `Ty`.
2011 pub fn res_to_ty(&self,
2012 opt_self_ty: Option<Ty<'tcx>>,
2014 permit_variants: bool)
2016 let tcx = self.tcx();
2018 debug!("res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2019 path.res, opt_self_ty, path.segments);
2021 let span = path.span;
2023 Res::Def(DefKind::OpaqueTy, did) => {
2024 // Check for desugared `impl Trait`.
2025 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2026 let item_segment = path.segments.split_last().unwrap();
2027 self.prohibit_generics(item_segment.1);
2028 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2031 tcx.mk_opaque(did, substs),
2034 Res::Def(DefKind::Enum, did)
2035 | Res::Def(DefKind::TyAlias, did)
2036 | Res::Def(DefKind::Struct, did)
2037 | Res::Def(DefKind::Union, did)
2038 | Res::Def(DefKind::ForeignTy, did) => {
2039 assert_eq!(opt_self_ty, None);
2040 self.prohibit_generics(path.segments.split_last().unwrap().1);
2041 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2043 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2044 // Convert "variant type" as if it were a real type.
2045 // The resulting `Ty` is type of the variant's enum for now.
2046 assert_eq!(opt_self_ty, None);
2049 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2050 let generic_segs: FxHashSet<_> =
2051 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2052 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
2053 if !generic_segs.contains(&index) {
2060 let PathSeg(def_id, index) = path_segs.last().unwrap();
2061 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2063 Res::Def(DefKind::TyParam, def_id) => {
2064 assert_eq!(opt_self_ty, None);
2065 self.prohibit_generics(&path.segments);
2067 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2068 let item_id = tcx.hir().get_parent_node(hir_id);
2069 let item_def_id = tcx.hir().local_def_id(item_id);
2070 let generics = tcx.generics_of(item_def_id);
2071 let index = generics.param_def_id_to_index[&def_id];
2072 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2074 Res::SelfTy(Some(_), None) => {
2075 // `Self` in trait or type alias.
2076 assert_eq!(opt_self_ty, None);
2077 self.prohibit_generics(&path.segments);
2078 tcx.types.self_param
2080 Res::SelfTy(_, Some(def_id)) => {
2081 // `Self` in impl (we know the concrete type).
2082 assert_eq!(opt_self_ty, None);
2083 self.prohibit_generics(&path.segments);
2084 // Try to evaluate any array length constants.
2085 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2087 Res::Def(DefKind::AssocTy, def_id) => {
2088 debug_assert!(path.segments.len() >= 2);
2089 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2090 self.qpath_to_ty(span,
2093 &path.segments[path.segments.len() - 2],
2094 path.segments.last().unwrap())
2096 Res::PrimTy(prim_ty) => {
2097 assert_eq!(opt_self_ty, None);
2098 self.prohibit_generics(&path.segments);
2100 hir::Bool => tcx.types.bool,
2101 hir::Char => tcx.types.char,
2102 hir::Int(it) => tcx.mk_mach_int(it),
2103 hir::Uint(uit) => tcx.mk_mach_uint(uit),
2104 hir::Float(ft) => tcx.mk_mach_float(ft),
2105 hir::Str => tcx.mk_str()
2109 self.set_tainted_by_errors();
2110 return self.tcx().types.err;
2112 _ => span_bug!(span, "unexpected resolution: {:?}", path.res)
2116 /// Parses the programmer's textual representation of a type into our
2117 /// internal notion of a type.
2118 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
2119 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
2120 ast_ty.hir_id, ast_ty, ast_ty.kind);
2122 let tcx = self.tcx();
2124 let result_ty = match ast_ty.kind {
2125 hir::TyKind::Slice(ref ty) => {
2126 tcx.mk_slice(self.ast_ty_to_ty(&ty))
2128 hir::TyKind::Ptr(ref mt) => {
2129 tcx.mk_ptr(ty::TypeAndMut {
2130 ty: self.ast_ty_to_ty(&mt.ty),
2134 hir::TyKind::Rptr(ref region, ref mt) => {
2135 let r = self.ast_region_to_region(region, None);
2136 debug!("ast_ty_to_ty: r={:?}", r);
2137 let t = self.ast_ty_to_ty(&mt.ty);
2138 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
2140 hir::TyKind::Never => {
2143 hir::TyKind::Tup(ref fields) => {
2144 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2146 hir::TyKind::BareFn(ref bf) => {
2147 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2148 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
2150 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2151 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2153 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2154 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2155 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
2156 self.ast_ty_to_ty(qself)
2158 self.res_to_ty(opt_self_ty, path, false)
2160 hir::TyKind::Def(item_id, ref lifetimes) => {
2161 let did = tcx.hir().local_def_id(item_id.id);
2162 self.impl_trait_ty_to_ty(did, lifetimes)
2164 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2165 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2166 let ty = self.ast_ty_to_ty(qself);
2168 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2173 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2174 .map(|(ty, _, _)| ty).unwrap_or(tcx.types.err)
2176 hir::TyKind::Array(ref ty, ref length) => {
2177 let length = self.ast_const_to_const(length, tcx.types.usize);
2178 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2179 self.normalize_ty(ast_ty.span, array_ty)
2181 hir::TyKind::Typeof(ref _e) => {
2182 struct_span_err!(tcx.sess, ast_ty.span, E0516,
2183 "`typeof` is a reserved keyword but unimplemented")
2184 .span_label(ast_ty.span, "reserved keyword")
2189 hir::TyKind::Infer => {
2190 // Infer also appears as the type of arguments or return
2191 // values in a ExprKind::Closure, or as
2192 // the type of local variables. Both of these cases are
2193 // handled specially and will not descend into this routine.
2194 self.ty_infer(None, ast_ty.span)
2196 hir::TyKind::Err => {
2201 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2203 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2207 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2208 pub fn const_param_def_id(&self, expr: &hir::Expr) -> Option<DefId> {
2209 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2210 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2211 let expr = match &expr.kind {
2212 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() =>
2213 block.expr.as_ref().unwrap(),
2218 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2219 Res::Def(DefKind::ConstParam, did) => Some(did),
2226 pub fn ast_const_to_const(
2228 ast_const: &hir::AnonConst,
2230 ) -> &'tcx ty::Const<'tcx> {
2231 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2233 let tcx = self.tcx();
2234 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2236 let mut const_ = ty::Const {
2237 val: ty::ConstKind::Unevaluated(
2239 InternalSubsts::identity_for_item(tcx, def_id),
2244 let expr = &tcx.hir().body(ast_const.body).value;
2245 if let Some(def_id) = self.const_param_def_id(expr) {
2246 // Find the name and index of the const parameter by indexing the generics of the
2247 // parent item and construct a `ParamConst`.
2248 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2249 let item_id = tcx.hir().get_parent_node(hir_id);
2250 let item_def_id = tcx.hir().local_def_id(item_id);
2251 let generics = tcx.generics_of(item_def_id);
2252 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2253 let name = tcx.hir().name(hir_id);
2254 const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2257 tcx.mk_const(const_)
2260 pub fn impl_trait_ty_to_ty(
2263 lifetimes: &[hir::GenericArg],
2265 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2266 let tcx = self.tcx();
2268 let generics = tcx.generics_of(def_id);
2270 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2271 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2272 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2273 // Our own parameters are the resolved lifetimes.
2275 GenericParamDefKind::Lifetime => {
2276 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2277 self.ast_region_to_region(lifetime, None).into()
2285 // Replace all parent lifetimes with `'static`.
2287 GenericParamDefKind::Lifetime => {
2288 tcx.lifetimes.re_static.into()
2290 _ => tcx.mk_param_from_def(param)
2294 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2296 let ty = tcx.mk_opaque(def_id, substs);
2297 debug!("impl_trait_ty_to_ty: {}", ty);
2301 pub fn ty_of_arg(&self,
2303 expected_ty: Option<Ty<'tcx>>)
2307 hir::TyKind::Infer if expected_ty.is_some() => {
2308 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2309 expected_ty.unwrap()
2311 _ => self.ast_ty_to_ty(ty),
2315 pub fn ty_of_fn(&self,
2316 unsafety: hir::Unsafety,
2319 -> ty::PolyFnSig<'tcx> {
2322 let tcx = self.tcx();
2324 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2326 let output_ty = match decl.output {
2327 hir::Return(ref output) => self.ast_ty_to_ty(output),
2328 hir::DefaultReturn(..) => tcx.mk_unit(),
2331 debug!("ty_of_fn: output_ty={:?}", output_ty);
2333 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
2341 // Find any late-bound regions declared in return type that do
2342 // not appear in the arguments. These are not well-formed.
2345 // for<'a> fn() -> &'a str <-- 'a is bad
2346 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2347 let inputs = bare_fn_ty.inputs();
2348 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
2349 &inputs.map_bound(|i| i.to_owned()));
2350 let output = bare_fn_ty.output();
2351 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2352 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2353 let lifetime_name = match *br {
2354 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2355 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2357 let mut err = struct_span_err!(tcx.sess,
2360 "return type references {} \
2361 which is not constrained by the fn input types",
2363 if let ty::BrAnon(_) = *br {
2364 // The only way for an anonymous lifetime to wind up
2365 // in the return type but **also** be unconstrained is
2366 // if it only appears in "associated types" in the
2367 // input. See #47511 for an example. In this case,
2368 // though we can easily give a hint that ought to be
2370 err.note("lifetimes appearing in an associated type \
2371 are not considered constrained");
2379 /// Given the bounds on an object, determines what single region bound (if any) we can
2380 /// use to summarize this type. The basic idea is that we will use the bound the user
2381 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2382 /// for region bounds. It may be that we can derive no bound at all, in which case
2383 /// we return `None`.
2384 fn compute_object_lifetime_bound(&self,
2386 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
2387 -> Option<ty::Region<'tcx>> // if None, use the default
2389 let tcx = self.tcx();
2391 debug!("compute_opt_region_bound(existential_predicates={:?})",
2392 existential_predicates);
2394 // No explicit region bound specified. Therefore, examine trait
2395 // bounds and see if we can derive region bounds from those.
2396 let derived_region_bounds =
2397 object_region_bounds(tcx, existential_predicates);
2399 // If there are no derived region bounds, then report back that we
2400 // can find no region bound. The caller will use the default.
2401 if derived_region_bounds.is_empty() {
2405 // If any of the derived region bounds are 'static, that is always
2407 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2408 return Some(tcx.lifetimes.re_static);
2411 // Determine whether there is exactly one unique region in the set
2412 // of derived region bounds. If so, use that. Otherwise, report an
2414 let r = derived_region_bounds[0];
2415 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2416 span_err!(tcx.sess, span, E0227,
2417 "ambiguous lifetime bound, explicit lifetime bound required");
2423 /// Collects together a list of bounds that are applied to some type,
2424 /// after they've been converted into `ty` form (from the HIR
2425 /// representations). These lists of bounds occur in many places in
2429 /// trait Foo: Bar + Baz { }
2430 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2432 /// fn foo<T: Bar + Baz>() { }
2433 /// ^^^^^^^^^ bounding the type parameter `T`
2435 /// impl dyn Bar + Baz
2436 /// ^^^^^^^^^ bounding the forgotten dynamic type
2439 /// Our representation is a bit mixed here -- in some cases, we
2440 /// include the self type (e.g., `trait_bounds`) but in others we do
2441 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2442 pub struct Bounds<'tcx> {
2443 /// A list of region bounds on the (implicit) self type. So if you
2444 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2445 /// the `T` is not explicitly included).
2446 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2448 /// A list of trait bounds. So if you had `T: Debug` this would be
2449 /// `T: Debug`. Note that the self-type is explicit here.
2450 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2452 /// A list of projection equality bounds. So if you had `T:
2453 /// Iterator<Item = u32>` this would include `<T as
2454 /// Iterator>::Item => u32`. Note that the self-type is explicit
2456 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2458 /// `Some` if there is *no* `?Sized` predicate. The `span`
2459 /// is the location in the source of the `T` declaration which can
2460 /// be cited as the source of the `T: Sized` requirement.
2461 pub implicitly_sized: Option<Span>,
2464 impl<'tcx> Bounds<'tcx> {
2465 /// Converts a bounds list into a flat set of predicates (like
2466 /// where-clauses). Because some of our bounds listings (e.g.,
2467 /// regions) don't include the self-type, you must supply the
2468 /// self-type here (the `param_ty` parameter).
2473 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2474 // If it could be sized, and is, add the `Sized` predicate.
2475 let sized_predicate = self.implicitly_sized.and_then(|span| {
2476 tcx.lang_items().sized_trait().map(|sized| {
2477 let trait_ref = ty::TraitRef {
2479 substs: tcx.mk_substs_trait(param_ty, &[])
2481 (trait_ref.to_predicate(), span)
2485 sized_predicate.into_iter().chain(
2486 self.region_bounds.iter().map(|&(region_bound, span)| {
2487 // Account for the binder being introduced below; no need to shift `param_ty`
2488 // because, at present at least, it can only refer to early-bound regions.
2489 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2490 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2491 (ty::Binder::dummy(outlives).to_predicate(), span)
2493 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2494 (bound_trait_ref.to_predicate(), span)
2497 self.projection_bounds.iter().map(|&(projection, span)| {
2498 (projection.to_predicate(), span)