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::{Kind, Subst, InternalSubsts, SubstsRef};
20 use rustc::ty::wf::object_region_bounds;
21 use rustc::mir::interpret::ConstValue;
22 use rustc_target::spec::abi;
23 use crate::require_c_abi_if_c_variadic;
24 use smallvec::SmallVec;
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 /// Returns the set of bounds in scope for the type parameter with
47 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
48 -> &'tcx ty::GenericPredicates<'tcx>;
50 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
53 param: Option<&ty::GenericParamDef>,
56 -> Option<ty::Region<'tcx>>;
58 /// Returns the type to use when a type is omitted.
59 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
61 /// Returns the const to use when a const is omitted.
65 param: Option<&ty::GenericParamDef>,
67 ) -> &'tcx Const<'tcx>;
69 /// Projecting an associated type from a (potentially)
70 /// higher-ranked trait reference is more complicated, because of
71 /// the possibility of late-bound regions appearing in the
72 /// associated type binding. This is not legal in function
73 /// signatures for that reason. In a function body, we can always
74 /// handle it because we can use inference variables to remove the
75 /// late-bound regions.
76 fn projected_ty_from_poly_trait_ref(&self,
79 poly_trait_ref: ty::PolyTraitRef<'tcx>)
82 /// Normalize an associated type coming from the user.
83 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
85 /// Invoked when we encounter an error from some prior pass
86 /// (e.g., resolve) that is translated into a ty-error. This is
87 /// used to help suppress derived errors typeck might otherwise
89 fn set_tainted_by_errors(&self);
91 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
94 pub enum SizedByDefault {
99 struct ConvertedBinding<'a, 'tcx> {
100 item_name: ast::Ident,
101 kind: ConvertedBindingKind<'a, 'tcx>,
105 enum ConvertedBindingKind<'a, 'tcx> {
107 Constraint(&'a [hir::GenericBound]),
111 enum GenericArgPosition {
113 Value, // e.g., functions
117 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
118 pub fn ast_region_to_region(&self,
119 lifetime: &hir::Lifetime,
120 def: Option<&ty::GenericParamDef>)
123 let tcx = self.tcx();
124 let lifetime_name = |def_id| {
125 tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap()).as_interned_str()
128 let r = match tcx.named_region(lifetime.hir_id) {
129 Some(rl::Region::Static) => {
130 tcx.lifetimes.re_static
133 Some(rl::Region::LateBound(debruijn, id, _)) => {
134 let name = lifetime_name(id);
135 tcx.mk_region(ty::ReLateBound(debruijn,
136 ty::BrNamed(id, name)))
139 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
140 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
143 Some(rl::Region::EarlyBound(index, id, _)) => {
144 let name = lifetime_name(id);
145 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
152 Some(rl::Region::Free(scope, id)) => {
153 let name = lifetime_name(id);
154 tcx.mk_region(ty::ReFree(ty::FreeRegion {
156 bound_region: ty::BrNamed(id, name)
159 // (*) -- not late-bound, won't change
163 self.re_infer(def, lifetime.span)
165 // This indicates an illegal lifetime
166 // elision. `resolve_lifetime` should have
167 // reported an error in this case -- but if
168 // not, let's error out.
169 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
171 // Supply some dummy value. We don't have an
172 // `re_error`, annoyingly, so use `'static`.
173 tcx.lifetimes.re_static
178 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
185 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
186 /// returns an appropriate set of substitutions for this particular reference to `I`.
187 pub fn ast_path_substs_for_ty(&self,
190 item_segment: &hir::PathSegment)
193 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
196 item_segment.generic_args(),
197 item_segment.infer_args,
201 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
206 /// Report error if there is an explicit type parameter when using `impl Trait`.
210 seg: &hir::PathSegment,
211 generics: &ty::Generics,
213 let explicit = !seg.infer_args;
214 let impl_trait = generics.params.iter().any(|param| match param.kind {
215 ty::GenericParamDefKind::Type {
216 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
221 if explicit && impl_trait {
222 let mut err = struct_span_err! {
226 "cannot provide explicit type parameters when `impl Trait` is \
227 used in argument position."
236 /// Checks that the correct number of generic arguments have been provided.
237 /// Used specifically for function calls.
238 pub fn check_generic_arg_count_for_call(
242 seg: &hir::PathSegment,
243 is_method_call: bool,
245 let empty_args = P(hir::GenericArgs {
246 args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
248 let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
249 Self::check_generic_arg_count(
253 if let Some(ref args) = seg.args {
259 GenericArgPosition::MethodCall
261 GenericArgPosition::Value
263 def.parent.is_none() && def.has_self, // `has_self`
264 seg.infer_args || suppress_mismatch, // `infer_args`
268 /// Checks that the correct number of generic arguments have been provided.
269 /// This is used both for datatypes and function calls.
270 fn check_generic_arg_count(
274 args: &hir::GenericArgs,
275 position: GenericArgPosition,
278 ) -> (bool, Option<Vec<Span>>) {
279 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
280 // that lifetimes will proceed types. So it suffices to check the number of each generic
281 // arguments in order to validate them with respect to the generic parameters.
282 let param_counts = def.own_counts();
283 let arg_counts = args.own_counts();
284 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
286 let mut defaults: ty::GenericParamCount = Default::default();
287 for param in &def.params {
289 GenericParamDefKind::Lifetime => {}
290 GenericParamDefKind::Type { has_default, .. } => {
291 defaults.types += has_default as usize
293 GenericParamDefKind::Const => {
294 // FIXME(const_generics:defaults)
299 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
300 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
303 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
304 let mut reported_late_bound_region_err = None;
305 if !infer_lifetimes {
306 if let Some(span_late) = def.has_late_bound_regions {
307 let msg = "cannot specify lifetime arguments explicitly \
308 if late bound lifetime parameters are present";
309 let note = "the late bound lifetime parameter is introduced here";
310 let span = args.args[0].span();
311 if position == GenericArgPosition::Value
312 && arg_counts.lifetimes != param_counts.lifetimes {
313 let mut err = tcx.sess.struct_span_err(span, msg);
314 err.span_note(span_late, note);
316 reported_late_bound_region_err = Some(true);
318 let mut multispan = MultiSpan::from_span(span);
319 multispan.push_span_label(span_late, note.to_string());
320 tcx.lint_hir(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
321 args.args[0].id(), multispan, msg);
322 reported_late_bound_region_err = Some(false);
327 let check_kind_count = |kind, required, permitted, provided, offset| {
329 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
336 // We enforce the following: `required` <= `provided` <= `permitted`.
337 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
338 // For other kinds (i.e., types), `permitted` may be greater than `required`.
339 if required <= provided && provided <= permitted {
340 return (reported_late_bound_region_err.unwrap_or(false), None);
343 // Unfortunately lifetime and type parameter mismatches are typically styled
344 // differently in diagnostics, which means we have a few cases to consider here.
345 let (bound, quantifier) = if required != permitted {
346 if provided < required {
347 (required, "at least ")
348 } else { // provided > permitted
349 (permitted, "at most ")
355 let mut potential_assoc_types: Option<Vec<Span>> = None;
356 let (spans, label) = if required == permitted && provided > permitted {
357 // In the case when the user has provided too many arguments,
358 // we want to point to the unexpected arguments.
359 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
361 .map(|arg| arg.span())
363 potential_assoc_types = Some(spans.clone());
364 (spans, format!( "unexpected {} argument", kind))
366 (vec![span], format!(
367 "expected {}{} {} argument{}",
371 if bound != 1 { "s" } else { "" },
375 let mut err = tcx.sess.struct_span_err_with_code(
378 "wrong number of {} arguments: expected {}{}, found {}",
384 DiagnosticId::Error("E0107".into())
387 err.span_label(span, label.as_str());
392 provided > required, // `suppress_error`
393 potential_assoc_types,
397 if reported_late_bound_region_err.is_none()
398 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes) {
401 param_counts.lifetimes,
402 param_counts.lifetimes,
403 arg_counts.lifetimes,
407 // FIXME(const_generics:defaults)
408 if !infer_args || arg_counts.consts > param_counts.consts {
414 arg_counts.lifetimes + arg_counts.types,
417 // Note that type errors are currently be emitted *after* const errors.
419 || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
422 param_counts.types - defaults.types - has_self as usize,
423 param_counts.types - has_self as usize,
425 arg_counts.lifetimes,
428 (reported_late_bound_region_err.unwrap_or(false), None)
432 /// Creates the relevant generic argument substitutions
433 /// corresponding to a set of generic parameters. This is a
434 /// rather complex function. Let us try to explain the role
435 /// of each of its parameters:
437 /// To start, we are given the `def_id` of the thing we are
438 /// creating the substitutions for, and a partial set of
439 /// substitutions `parent_substs`. In general, the substitutions
440 /// for an item begin with substitutions for all the "parents" of
441 /// that item -- e.g., for a method it might include the
442 /// parameters from the impl.
444 /// Therefore, the method begins by walking down these parents,
445 /// starting with the outermost parent and proceed inwards until
446 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
447 /// first to see if the parent's substitutions are listed in there. If so,
448 /// we can append those and move on. Otherwise, it invokes the
449 /// three callback functions:
451 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
452 /// generic arguments that were given to that parent from within
453 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
454 /// might refer to the trait `Foo`, and the arguments might be
455 /// `[T]`. The boolean value indicates whether to infer values
456 /// for arguments whose values were not explicitly provided.
457 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
458 /// instantiate a `Kind`.
459 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
460 /// creates a suitable inference variable.
461 pub fn create_substs_for_generic_args<'b>(
464 parent_substs: &[Kind<'tcx>],
466 self_ty: Option<Ty<'tcx>>,
467 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
468 provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
469 inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
470 ) -> SubstsRef<'tcx> {
471 // Collect the segments of the path; we need to substitute arguments
472 // for parameters throughout the entire path (wherever there are
473 // generic parameters).
474 let mut parent_defs = tcx.generics_of(def_id);
475 let count = parent_defs.count();
476 let mut stack = vec![(def_id, parent_defs)];
477 while let Some(def_id) = parent_defs.parent {
478 parent_defs = tcx.generics_of(def_id);
479 stack.push((def_id, parent_defs));
482 // We manually build up the substitution, rather than using convenience
483 // methods in `subst.rs`, so that we can iterate over the arguments and
484 // parameters in lock-step linearly, instead of trying to match each pair.
485 let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
487 // Iterate over each segment of the path.
488 while let Some((def_id, defs)) = stack.pop() {
489 let mut params = defs.params.iter().peekable();
491 // If we have already computed substitutions for parents, we can use those directly.
492 while let Some(¶m) = params.peek() {
493 if let Some(&kind) = parent_substs.get(param.index as usize) {
501 // `Self` is handled first, unless it's been handled in `parent_substs`.
503 if let Some(¶m) = params.peek() {
504 if param.index == 0 {
505 if let GenericParamDefKind::Type { .. } = param.kind {
506 substs.push(self_ty.map(|ty| ty.into())
507 .unwrap_or_else(|| inferred_kind(None, param, true)));
514 // Check whether this segment takes generic arguments and the user has provided any.
515 let (generic_args, infer_args) = args_for_def_id(def_id);
517 let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
521 // We're going to iterate through the generic arguments that the user
522 // provided, matching them with the generic parameters we expect.
523 // Mismatches can occur as a result of elided lifetimes, or for malformed
524 // input. We try to handle both sensibly.
525 match (args.peek(), params.peek()) {
526 (Some(&arg), Some(¶m)) => {
527 match (arg, ¶m.kind) {
528 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
529 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
530 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
531 substs.push(provided_kind(param, arg));
535 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
536 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
537 // We expected a lifetime argument, but got a type or const
538 // argument. That means we're inferring the lifetimes.
539 substs.push(inferred_kind(None, param, infer_args));
543 // We expected one kind of parameter, but the user provided
544 // another. This is an error, but we need to handle it
545 // gracefully so we can report sensible errors.
546 // In this case, we're simply going to infer this argument.
552 // We should never be able to reach this point with well-formed input.
553 // Getting to this point means the user supplied more arguments than
554 // there are parameters.
557 (None, Some(¶m)) => {
558 // If there are fewer arguments than parameters, it means
559 // we're inferring the remaining arguments.
560 substs.push(inferred_kind(Some(&substs), param, infer_args));
564 (None, None) => break,
569 tcx.intern_substs(&substs)
572 /// Given the type/lifetime/const arguments provided to some path (along with
573 /// an implicit `Self`, if this is a trait reference), returns the complete
574 /// set of substitutions. This may involve applying defaulted type parameters.
575 /// Also returns back constriants on associated types.
580 /// T: std::ops::Index<usize, Output = u32>
581 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
584 /// 1. The `self_ty` here would refer to the type `T`.
585 /// 2. The path in question is the path to the trait `std::ops::Index`,
586 /// which will have been resolved to a `def_id`
587 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
588 /// parameters are returned in the `SubstsRef`, the associated type bindings like
589 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
591 /// Note that the type listing given here is *exactly* what the user provided.
592 fn create_substs_for_ast_path<'a>(&self,
595 generic_args: &'a hir::GenericArgs,
597 self_ty: Option<Ty<'tcx>>)
598 -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>)
600 // If the type is parameterized by this region, then replace this
601 // region with the current anon region binding (in other words,
602 // whatever & would get replaced with).
603 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
605 def_id, self_ty, generic_args);
607 let tcx = self.tcx();
608 let generic_params = tcx.generics_of(def_id);
610 // If a self-type was declared, one should be provided.
611 assert_eq!(generic_params.has_self, self_ty.is_some());
613 let has_self = generic_params.has_self;
614 let (_, potential_assoc_types) = Self::check_generic_arg_count(
619 GenericArgPosition::Type,
624 let is_object = self_ty.map_or(false, |ty| {
625 ty == self.tcx().types.trait_object_dummy_self
627 let default_needs_object_self = |param: &ty::GenericParamDef| {
628 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
629 if is_object && has_default {
630 if tcx.at(span).type_of(param.def_id).has_self_ty() {
631 // There is no suitable inference default for a type parameter
632 // that references self, in an object type.
641 let substs = Self::create_substs_for_generic_args(
647 // Provide the generic args, and whether types should be inferred.
648 |_| (Some(generic_args), infer_args),
649 // Provide substitutions for parameters for which (valid) arguments have been provided.
651 match (¶m.kind, arg) {
652 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
653 self.ast_region_to_region(<, Some(param)).into()
655 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
656 self.ast_ty_to_ty(&ty).into()
658 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
659 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
664 // Provide substitutions for parameters for which arguments are inferred.
665 |substs, param, infer_args| {
667 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
668 GenericParamDefKind::Type { has_default, .. } => {
669 if !infer_args && has_default {
670 // No type parameter provided, but a default exists.
672 // If we are converting an object type, then the
673 // `Self` parameter is unknown. However, some of the
674 // other type parameters may reference `Self` in their
675 // defaults. This will lead to an ICE if we are not
677 if default_needs_object_self(param) {
678 struct_span_err!(tcx.sess, span, E0393,
679 "the type parameter `{}` must be explicitly specified",
682 .span_label(span, format!(
683 "missing reference to `{}`", param.name))
685 "because of the default `Self` reference, type parameters \
686 must be specified on object types"))
690 // This is a default type parameter.
693 tcx.at(span).type_of(param.def_id)
694 .subst_spanned(tcx, substs.unwrap(), Some(span))
697 } else if infer_args {
698 // No type parameters were provided, we can infer all.
699 let param = if !default_needs_object_self(param) {
704 self.ty_infer(param, span).into()
706 // We've already errored above about the mismatch.
710 GenericParamDefKind::Const => {
711 // FIXME(const_generics:defaults)
713 // No const parameters were provided, we can infer all.
714 let ty = tcx.at(span).type_of(param.def_id);
715 self.ct_infer(ty, Some(param), span).into()
717 // We've already errored above about the mismatch.
718 tcx.consts.err.into()
725 // Convert associated-type bindings or constraints into a separate vector.
726 // Example: Given this:
728 // T: Iterator<Item = u32>
730 // The `T` is passed in as a self-type; the `Item = u32` is
731 // not a "type parameter" of the `Iterator` trait, but rather
732 // a restriction on `<T as Iterator>::Item`, so it is passed
734 let assoc_bindings = generic_args.bindings.iter()
736 let kind = match binding.kind {
737 hir::TypeBindingKind::Equality { ref ty } =>
738 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty)),
739 hir::TypeBindingKind::Constraint { ref bounds } =>
740 ConvertedBindingKind::Constraint(bounds),
743 item_name: binding.ident,
750 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
751 generic_params, self_ty, substs);
753 (substs, assoc_bindings, potential_assoc_types)
756 /// Instantiates the path for the given trait reference, assuming that it's
757 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
758 /// The type _cannot_ be a type other than a trait type.
760 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
761 /// are disallowed. Otherwise, they are pushed onto the vector given.
762 pub fn instantiate_mono_trait_ref(&self,
763 trait_ref: &hir::TraitRef,
765 ) -> ty::TraitRef<'tcx>
767 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
769 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
770 trait_ref.trait_def_id(),
772 trait_ref.path.segments.last().unwrap())
775 /// The given trait-ref must actually be a trait.
776 pub(super) fn instantiate_poly_trait_ref_inner(&self,
777 trait_ref: &hir::TraitRef,
779 bounds: &mut Bounds<'tcx>,
781 ) -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
783 let trait_def_id = trait_ref.trait_def_id();
785 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
787 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
789 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
793 trait_ref.path.segments.last().unwrap(),
795 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
797 let mut dup_bindings = FxHashMap::default();
798 for binding in &assoc_bindings {
799 // Specify type to assert that error was already reported in `Err` case.
800 let _: Result<_, ErrorReported> =
801 self.add_predicates_for_ast_type_binding(
802 trait_ref.hir_ref_id,
809 // Okay to ignore `Err` because of `ErrorReported` (see above).
812 debug!("instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
813 trait_ref, bounds, poly_trait_ref);
814 (poly_trait_ref, potential_assoc_types)
817 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
818 /// a full trait reference. The resulting trait reference is returned. This may also generate
819 /// auxiliary bounds, which are added to `bounds`.
824 /// poly_trait_ref = Iterator<Item = u32>
828 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
830 /// **A note on binders:** against our usual convention, there is an implied bounder around
831 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
832 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
833 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
834 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
836 pub fn instantiate_poly_trait_ref(&self,
837 poly_trait_ref: &hir::PolyTraitRef,
839 bounds: &mut Bounds<'tcx>
840 ) -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
842 self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty, bounds, false)
845 fn ast_path_to_mono_trait_ref(&self,
849 trait_segment: &hir::PathSegment
850 ) -> ty::TraitRef<'tcx>
852 let (substs, assoc_bindings, _) =
853 self.create_substs_for_ast_trait_ref(span,
857 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
858 ty::TraitRef::new(trait_def_id, substs)
861 fn create_substs_for_ast_trait_ref<'a>(
866 trait_segment: &'a hir::PathSegment,
867 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
868 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
871 let trait_def = self.tcx().trait_def(trait_def_id);
873 if !self.tcx().features().unboxed_closures &&
874 trait_segment.generic_args().parenthesized != trait_def.paren_sugar
876 // For now, require that parenthetical notation be used only with `Fn()` etc.
877 let msg = if trait_def.paren_sugar {
878 "the precise format of `Fn`-family traits' type parameters is subject to change. \
879 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
881 "parenthetical notation is only stable when used with `Fn`-family traits"
883 emit_feature_err(&self.tcx().sess.parse_sess, sym::unboxed_closures,
884 span, GateIssue::Language, msg);
887 self.create_substs_for_ast_path(span,
889 trait_segment.generic_args(),
890 trait_segment.infer_args,
894 fn trait_defines_associated_type_named(&self,
896 assoc_name: ast::Ident)
899 self.tcx().associated_items(trait_def_id).any(|item| {
900 item.kind == ty::AssocKind::Type &&
901 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
905 // Returns `true` if a bounds list includes `?Sized`.
906 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound], span: Span) -> bool {
907 let tcx = self.tcx();
909 // Try to find an unbound in bounds.
910 let mut unbound = None;
911 for ab in ast_bounds {
912 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
913 if unbound.is_none() {
914 unbound = Some(&ptr.trait_ref);
920 "type parameter has more than one relaxed default \
921 bound, only one is supported"
927 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
930 // FIXME(#8559) currently requires the unbound to be built-in.
931 if let Ok(kind_id) = kind_id {
932 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
935 "default bound relaxed for a type parameter, but \
936 this does nothing because the given bound is not \
937 a default. Only `?Sized` is supported",
942 _ if kind_id.is_ok() => {
945 // No lang item for `Sized`, so we can't add it as a bound.
952 /// This helper takes a *converted* parameter type (`param_ty`)
953 /// and an *unconverted* list of bounds:
957 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
959 /// `param_ty`, in ty form
962 /// It adds these `ast_bounds` into the `bounds` structure.
964 /// **A note on binders:** there is an implied binder around
965 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
966 /// for more details.
969 ast_bounds: &[hir::GenericBound],
970 bounds: &mut Bounds<'tcx>,
972 let mut trait_bounds = Vec::new();
973 let mut region_bounds = Vec::new();
975 for ast_bound in ast_bounds {
977 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) =>
978 trait_bounds.push(b),
979 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
980 hir::GenericBound::Outlives(ref l) =>
981 region_bounds.push(l),
985 for bound in trait_bounds {
986 let (poly_trait_ref, _) = self.instantiate_poly_trait_ref(
991 bounds.trait_bounds.push((poly_trait_ref, bound.span))
994 bounds.region_bounds.extend(region_bounds
996 .map(|r| (self.ast_region_to_region(r, None), r.span))
1000 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1001 /// The self-type for the bounds is given by `param_ty`.
1006 /// fn foo<T: Bar + Baz>() { }
1007 /// ^ ^^^^^^^^^ ast_bounds
1011 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1012 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1013 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1015 /// `span` should be the declaration size of the parameter.
1016 pub fn compute_bounds(&self,
1018 ast_bounds: &[hir::GenericBound],
1019 sized_by_default: SizedByDefault,
1022 let mut bounds = Bounds::default();
1024 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1025 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1027 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1028 if !self.is_unsized(ast_bounds, span) {
1040 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1043 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1044 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1045 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1046 fn add_predicates_for_ast_type_binding(
1048 hir_ref_id: hir::HirId,
1049 trait_ref: ty::PolyTraitRef<'tcx>,
1050 binding: &ConvertedBinding<'_, 'tcx>,
1051 bounds: &mut Bounds<'tcx>,
1053 dup_bindings: &mut FxHashMap<DefId, Span>,
1054 ) -> Result<(), ErrorReported> {
1055 let tcx = self.tcx();
1058 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1059 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1060 // subtle in the event that `T` is defined in a supertrait of
1061 // `SomeTrait`, because in that case we need to upcast.
1063 // That is, consider this case:
1066 // trait SubTrait: SuperTrait<int> { }
1067 // trait SuperTrait<A> { type T; }
1069 // ... B: SubTrait<T = foo> ...
1072 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1074 // Find any late-bound regions declared in `ty` that are not
1075 // declared in the trait-ref. These are not well-formed.
1079 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1080 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1081 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1082 let late_bound_in_trait_ref =
1083 tcx.collect_constrained_late_bound_regions(&trait_ref);
1084 let late_bound_in_ty =
1085 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1086 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1087 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1088 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1089 let br_name = match *br {
1090 ty::BrNamed(_, name) => name,
1094 "anonymous bound region {:?} in binding but not trait ref",
1098 struct_span_err!(tcx.sess,
1101 "binding for associated type `{}` references lifetime `{}`, \
1102 which does not appear in the trait input types",
1103 binding.item_name, br_name)
1109 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
1110 binding.item_name) {
1111 // Simple case: X is defined in the current trait.
1114 // Otherwise, we have to walk through the supertraits to find
1116 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
1117 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
1119 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
1120 binding.item_name, binding.span)
1123 let (assoc_ident, def_scope) =
1124 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1125 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
1126 i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident
1127 }).expect("missing associated type");
1129 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1130 let msg = format!("associated type `{}` is private", binding.item_name);
1131 tcx.sess.span_err(binding.span, &msg);
1133 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1136 dup_bindings.entry(assoc_ty.def_id)
1137 .and_modify(|prev_span| {
1138 struct_span_err!(self.tcx().sess, binding.span, E0719,
1139 "the value of the associated type `{}` (from the trait `{}`) \
1140 is already specified",
1142 tcx.def_path_str(assoc_ty.container.id()))
1143 .span_label(binding.span, "re-bound here")
1144 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1147 .or_insert(binding.span);
1150 match binding.kind {
1151 ConvertedBindingKind::Equality(ref ty) => {
1152 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1153 // the "projection predicate" for:
1155 // `<T as Iterator>::Item = u32`
1156 bounds.projection_bounds.push((candidate.map_bound(|trait_ref| {
1157 ty::ProjectionPredicate {
1158 projection_ty: ty::ProjectionTy::from_ref_and_name(
1167 ConvertedBindingKind::Constraint(ast_bounds) => {
1168 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1170 // `<T as Iterator>::Item: Debug`
1172 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1173 // parameter to have a skipped binder.
1174 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1185 fn ast_path_to_ty(&self,
1188 item_segment: &hir::PathSegment)
1191 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1194 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
1198 /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1199 /// removing the dummy `Self` type (`trait_object_dummy_self`).
1200 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
1201 -> ty::ExistentialTraitRef<'tcx> {
1202 if trait_ref.self_ty() != self.tcx().types.trait_object_dummy_self {
1203 bug!("trait_ref_to_existential called on {:?} with non-dummy Self", trait_ref);
1205 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
1208 fn conv_object_ty_poly_trait_ref(&self,
1210 trait_bounds: &[hir::PolyTraitRef],
1211 lifetime: &hir::Lifetime)
1214 let tcx = self.tcx();
1216 let mut bounds = Bounds::default();
1217 let mut potential_assoc_types = Vec::new();
1218 let dummy_self = self.tcx().types.trait_object_dummy_self;
1219 // FIXME: we want to avoid collecting into a `Vec` here, but simply cloning the iterator is
1220 // not straightforward due to the borrow checker.
1221 let bound_trait_refs: Vec<_> = trait_bounds
1224 .map(|trait_bound| {
1225 let (trait_ref, cur_potential_assoc_types) = self.instantiate_poly_trait_ref(
1230 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1231 (trait_ref, trait_bound.span)
1235 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1236 // is used and no 'maybe' bounds are used.
1237 let expanded_traits = traits::expand_trait_aliases(tcx, bound_trait_refs.iter().cloned());
1238 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1239 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1240 if regular_traits.len() > 1 {
1241 let first_trait = ®ular_traits[0];
1242 let additional_trait = ®ular_traits[1];
1243 let mut err = struct_span_err!(tcx.sess, additional_trait.bottom().1, E0225,
1244 "only auto traits can be used as additional traits in a trait object"
1246 additional_trait.label_with_exp_info(&mut err,
1247 "additional non-auto trait", "additional use");
1248 first_trait.label_with_exp_info(&mut err,
1249 "first non-auto trait", "first use");
1253 if regular_traits.is_empty() && auto_traits.is_empty() {
1254 span_err!(tcx.sess, span, E0224,
1255 "at least one trait is required for an object type");
1256 return tcx.types.err;
1259 // Check that there are no gross object safety violations;
1260 // most importantly, that the supertraits don't contain `Self`,
1262 for item in ®ular_traits {
1263 let object_safety_violations =
1264 tcx.global_tcx().astconv_object_safety_violations(item.trait_ref().def_id());
1265 if !object_safety_violations.is_empty() {
1266 tcx.report_object_safety_error(
1268 item.trait_ref().def_id(),
1269 object_safety_violations
1271 .map(|mut err| err.emit());
1272 return tcx.types.err;
1276 // Use a `BTreeSet` to keep output in a more consistent order.
1277 let mut associated_types = BTreeSet::default();
1279 let regular_traits_refs = bound_trait_refs
1281 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()))
1282 .map(|(trait_ref, _)| trait_ref);
1283 for trait_ref in traits::elaborate_trait_refs(tcx, regular_traits_refs) {
1284 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", trait_ref);
1286 ty::Predicate::Trait(pred) => {
1288 .extend(tcx.associated_items(pred.def_id())
1289 .filter(|item| item.kind == ty::AssocKind::Type)
1290 .map(|item| item.def_id));
1292 ty::Predicate::Projection(pred) => {
1293 // A `Self` within the original bound will be substituted with a
1294 // `trait_object_dummy_self`, so check for that.
1295 let references_self =
1296 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1298 // If the projection output contains `Self`, force the user to
1299 // elaborate it explicitly to avoid a lot of complexity.
1301 // The "classicaly useful" case is the following:
1303 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1308 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1309 // but actually supporting that would "expand" to an infinitely-long type
1310 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1312 // Instead, we force the user to write `dyn MyTrait<MyOutput = X, Output = X>`,
1313 // which is uglier but works. See the discussion in #56288 for alternatives.
1314 if !references_self {
1315 // Include projections defined on supertraits.
1316 bounds.projection_bounds.push((pred, DUMMY_SP))
1323 for (projection_bound, _) in &bounds.projection_bounds {
1324 associated_types.remove(&projection_bound.projection_def_id());
1327 if !associated_types.is_empty() {
1328 let names = associated_types.iter().map(|item_def_id| {
1329 let assoc_item = tcx.associated_item(*item_def_id);
1330 let trait_def_id = assoc_item.container.id();
1332 "`{}` (from the trait `{}`)",
1334 tcx.def_path_str(trait_def_id),
1336 }).collect::<Vec<_>>().join(", ");
1337 let mut err = struct_span_err!(
1341 "the value of the associated type{} {} must be specified",
1342 if associated_types.len() == 1 { "" } else { "s" },
1345 let (suggest, potential_assoc_types_spans) =
1346 if potential_assoc_types.len() == associated_types.len() {
1347 // Only suggest when the amount of missing associated types equals the number of
1348 // extra type arguments present, as that gives us a relatively high confidence
1349 // that the user forgot to give the associtated type's name. The canonical
1350 // example would be trying to use `Iterator<isize>` instead of
1351 // `Iterator<Item = isize>`.
1352 (true, potential_assoc_types)
1356 let mut suggestions = Vec::new();
1357 for (i, item_def_id) in associated_types.iter().enumerate() {
1358 let assoc_item = tcx.associated_item(*item_def_id);
1361 format!("associated type `{}` must be specified", assoc_item.ident),
1363 if item_def_id.is_local() {
1365 tcx.def_span(*item_def_id),
1366 format!("`{}` defined here", assoc_item.ident),
1370 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1371 potential_assoc_types_spans[i],
1374 potential_assoc_types_spans[i],
1375 format!("{} = {}", assoc_item.ident, snippet),
1380 if !suggestions.is_empty() {
1381 let msg = format!("if you meant to specify the associated {}, write",
1382 if suggestions.len() == 1 { "type" } else { "types" });
1383 err.multipart_suggestion(
1386 Applicability::MaybeIncorrect,
1392 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1393 // `dyn Trait + Send`.
1394 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1395 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1396 debug!("regular_traits: {:?}", regular_traits);
1397 debug!("auto_traits: {:?}", auto_traits);
1399 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1400 let existential_trait_refs = regular_traits.iter().map(|i| {
1401 i.trait_ref().map_bound(|trait_ref| self.trait_ref_to_existential(trait_ref))
1403 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1404 bound.map_bound(|b| {
1405 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1406 ty::ExistentialProjection {
1408 item_def_id: b.projection_ty.item_def_id,
1409 substs: trait_ref.substs,
1414 // Calling `skip_binder` is okay because the predicates are re-bound.
1415 let regular_trait_predicates = existential_trait_refs.map(
1416 |trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1417 let auto_trait_predicates = auto_traits.into_iter().map(
1418 |trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1420 regular_trait_predicates
1421 .chain(auto_trait_predicates)
1422 .chain(existential_projections
1423 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1424 .collect::<SmallVec<[_; 8]>>();
1425 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1427 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1429 // Use explicitly-specified region bound.
1430 let region_bound = if !lifetime.is_elided() {
1431 self.ast_region_to_region(lifetime, None)
1433 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1434 if tcx.named_region(lifetime.hir_id).is_some() {
1435 self.ast_region_to_region(lifetime, None)
1437 self.re_infer(None, span).unwrap_or_else(|| {
1438 span_err!(tcx.sess, span, E0228,
1439 "the lifetime bound for this object type cannot be deduced \
1440 from context; please supply an explicit bound");
1441 tcx.lifetimes.re_static
1446 debug!("region_bound: {:?}", region_bound);
1448 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1449 debug!("trait_object_type: {:?}", ty);
1453 fn report_ambiguous_associated_type(
1460 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1461 if let (Some(_), Ok(snippet)) = (
1462 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1463 self.tcx().sess.source_map().span_to_snippet(span),
1465 err.span_suggestion(
1467 "you are looking for the module in `std`, not the primitive type",
1468 format!("std::{}", snippet),
1469 Applicability::MachineApplicable,
1472 err.span_suggestion(
1474 "use fully-qualified syntax",
1475 format!("<{} as {}>::{}", type_str, trait_str, name),
1476 Applicability::HasPlaceholders
1482 // Search for a bound on a type parameter which includes the associated item
1483 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1484 // This function will fail if there are no suitable bounds or there is
1486 fn find_bound_for_assoc_item(&self,
1487 ty_param_def_id: DefId,
1488 assoc_name: ast::Ident,
1490 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1492 let tcx = self.tcx();
1494 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1495 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1497 // Check that there is exactly one way to find an associated type with the
1499 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1500 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1502 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1503 let param_name = tcx.hir().ty_param_name(param_hir_id);
1504 self.one_bound_for_assoc_type(suitable_bounds,
1505 ¶m_name.as_str(),
1510 // Checks that `bounds` contains exactly one element and reports appropriate
1511 // errors otherwise.
1512 fn one_bound_for_assoc_type<I>(&self,
1514 ty_param_name: &str,
1515 assoc_name: ast::Ident,
1517 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1518 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1520 let bound = match bounds.next() {
1521 Some(bound) => bound,
1523 struct_span_err!(self.tcx().sess, span, E0220,
1524 "associated type `{}` not found for `{}`",
1527 .span_label(span, format!("associated type `{}` not found", assoc_name))
1529 return Err(ErrorReported);
1533 if let Some(bound2) = bounds.next() {
1534 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1535 let mut err = struct_span_err!(
1536 self.tcx().sess, span, E0221,
1537 "ambiguous associated type `{}` in bounds of `{}`",
1540 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1542 for bound in bounds {
1543 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1544 item.kind == ty::AssocKind::Type &&
1545 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1547 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1549 if let Some(span) = bound_span {
1550 err.span_label(span, format!("ambiguous `{}` from `{}`",
1554 span_note!(&mut err, span,
1555 "associated type `{}` could derive from `{}`",
1566 // Create a type from a path to an associated type.
1567 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1568 // and item_segment is the path segment for `D`. We return a type and a def for
1570 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1571 // parameter or `Self`.
1572 pub fn associated_path_to_ty(
1574 hir_ref_id: hir::HirId,
1578 assoc_segment: &hir::PathSegment,
1579 permit_variants: bool,
1580 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1581 let tcx = self.tcx();
1582 let assoc_ident = assoc_segment.ident;
1584 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1586 self.prohibit_generics(slice::from_ref(assoc_segment));
1588 // Check if we have an enum variant.
1589 let mut variant_resolution = None;
1590 if let ty::Adt(adt_def, _) = qself_ty.sty {
1591 if adt_def.is_enum() {
1592 let variant_def = adt_def.variants.iter().find(|vd| {
1593 tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1595 if let Some(variant_def) = variant_def {
1596 if permit_variants {
1597 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1598 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1600 variant_resolution = Some(variant_def.def_id);
1606 // Find the type of the associated item, and the trait where the associated
1607 // item is declared.
1608 let bound = match (&qself_ty.sty, qself_res) {
1609 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
1610 // `Self` in an impl of a trait -- we have a concrete self type and a
1612 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1613 Some(trait_ref) => trait_ref,
1615 // A cycle error occurred, most likely.
1616 return Err(ErrorReported);
1620 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1621 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1623 self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span)?
1625 (&ty::Param(_), Res::SelfTy(Some(param_did), None)) |
1626 (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
1627 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
1630 if variant_resolution.is_some() {
1631 // Variant in type position
1632 let msg = format!("expected type, found variant `{}`", assoc_ident);
1633 tcx.sess.span_err(span, &msg);
1634 } else if qself_ty.is_enum() {
1635 let mut err = tcx.sess.struct_span_err(
1637 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
1640 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1641 if let Some(suggested_name) = find_best_match_for_name(
1642 adt_def.variants.iter().map(|variant| &variant.ident.name),
1643 &assoc_ident.as_str(),
1646 err.span_suggestion(
1648 "there is a variant with a similar name",
1649 suggested_name.to_string(),
1650 Applicability::MaybeIncorrect,
1655 format!("variant not found in `{}`", qself_ty),
1659 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1660 let sp = tcx.sess.source_map().def_span(sp);
1661 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1665 } else if !qself_ty.references_error() {
1666 // Don't print `TyErr` to the user.
1667 self.report_ambiguous_associated_type(
1669 &qself_ty.to_string(),
1671 &assoc_ident.as_str(),
1674 return Err(ErrorReported);
1678 let trait_did = bound.def_id();
1679 let (assoc_ident, def_scope) =
1680 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1681 let item = tcx.associated_items(trait_did).find(|i| {
1682 Namespace::from(i.kind) == Namespace::Type &&
1683 i.ident.modern() == assoc_ident
1684 }).expect("missing associated type");
1686 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1687 let ty = self.normalize_ty(span, ty);
1689 let kind = DefKind::AssocTy;
1690 if !item.vis.is_accessible_from(def_scope, tcx) {
1691 let msg = format!("{} `{}` is private", kind.descr(), assoc_ident);
1692 tcx.sess.span_err(span, &msg);
1694 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1696 if let Some(variant_def_id) = variant_resolution {
1697 let mut err = tcx.struct_span_lint_hir(
1698 AMBIGUOUS_ASSOCIATED_ITEMS,
1701 "ambiguous associated item",
1704 let mut could_refer_to = |kind: DefKind, def_id, also| {
1705 let note_msg = format!("`{}` could{} refer to {} defined here",
1706 assoc_ident, also, kind.descr());
1707 err.span_note(tcx.def_span(def_id), ¬e_msg);
1709 could_refer_to(DefKind::Variant, variant_def_id, "");
1710 could_refer_to(kind, item.def_id, " also");
1712 err.span_suggestion(
1714 "use fully-qualified syntax",
1715 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1716 Applicability::MachineApplicable,
1720 Ok((ty, kind, item.def_id))
1723 fn qpath_to_ty(&self,
1725 opt_self_ty: Option<Ty<'tcx>>,
1727 trait_segment: &hir::PathSegment,
1728 item_segment: &hir::PathSegment)
1731 let tcx = self.tcx();
1732 let trait_def_id = tcx.parent(item_def_id).unwrap();
1734 self.prohibit_generics(slice::from_ref(item_segment));
1736 let self_ty = if let Some(ty) = opt_self_ty {
1739 let path_str = tcx.def_path_str(trait_def_id);
1740 self.report_ambiguous_associated_type(
1744 &item_segment.ident.as_str(),
1746 return tcx.types.err;
1749 debug!("qpath_to_ty: self_type={:?}", self_ty);
1751 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1756 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1758 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1761 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1762 &self, segments: T) -> bool {
1763 let mut has_err = false;
1764 for segment in segments {
1765 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1766 for arg in &segment.generic_args().args {
1767 let (span, kind) = match arg {
1768 hir::GenericArg::Lifetime(lt) => {
1769 if err_for_lt { continue }
1772 (lt.span, "lifetime")
1774 hir::GenericArg::Type(ty) => {
1775 if err_for_ty { continue }
1780 hir::GenericArg::Const(ct) => {
1781 if err_for_ct { continue }
1786 let mut err = struct_span_err!(
1790 "{} arguments are not allowed for this type",
1793 err.span_label(span, format!("{} argument not allowed", kind));
1795 if err_for_lt && err_for_ty && err_for_ct {
1799 for binding in &segment.generic_args().bindings {
1801 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1808 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
1809 let mut err = struct_span_err!(tcx.sess, span, E0229,
1810 "associated type bindings are not allowed here");
1811 err.span_label(span, "associated type not allowed here").emit();
1814 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1815 pub fn def_ids_for_value_path_segments(
1817 segments: &[hir::PathSegment],
1818 self_ty: Option<Ty<'tcx>>,
1822 // We need to extract the type parameters supplied by the user in
1823 // the path `path`. Due to the current setup, this is a bit of a
1824 // tricky-process; the problem is that resolve only tells us the
1825 // end-point of the path resolution, and not the intermediate steps.
1826 // Luckily, we can (at least for now) deduce the intermediate steps
1827 // just from the end-point.
1829 // There are basically five cases to consider:
1831 // 1. Reference to a constructor of a struct:
1833 // struct Foo<T>(...)
1835 // In this case, the parameters are declared in the type space.
1837 // 2. Reference to a constructor of an enum variant:
1839 // enum E<T> { Foo(...) }
1841 // In this case, the parameters are defined in the type space,
1842 // but may be specified either on the type or the variant.
1844 // 3. Reference to a fn item or a free constant:
1848 // In this case, the path will again always have the form
1849 // `a::b::foo::<T>` where only the final segment should have
1850 // type parameters. However, in this case, those parameters are
1851 // declared on a value, and hence are in the `FnSpace`.
1853 // 4. Reference to a method or an associated constant:
1855 // impl<A> SomeStruct<A> {
1859 // Here we can have a path like
1860 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1861 // may appear in two places. The penultimate segment,
1862 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1863 // final segment, `foo::<B>` contains parameters in fn space.
1865 // The first step then is to categorize the segments appropriately.
1867 let tcx = self.tcx();
1869 assert!(!segments.is_empty());
1870 let last = segments.len() - 1;
1872 let mut path_segs = vec![];
1875 // Case 1. Reference to a struct constructor.
1876 DefKind::Ctor(CtorOf::Struct, ..) => {
1877 // Everything but the final segment should have no
1878 // parameters at all.
1879 let generics = tcx.generics_of(def_id);
1880 // Variant and struct constructors use the
1881 // generics of their parent type definition.
1882 let generics_def_id = generics.parent.unwrap_or(def_id);
1883 path_segs.push(PathSeg(generics_def_id, last));
1886 // Case 2. Reference to a variant constructor.
1887 DefKind::Ctor(CtorOf::Variant, ..)
1888 | DefKind::Variant => {
1889 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1890 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1891 debug_assert!(adt_def.is_enum());
1893 } else if last >= 1 && segments[last - 1].args.is_some() {
1894 // Everything but the penultimate segment should have no
1895 // parameters at all.
1896 let mut def_id = def_id;
1898 // `DefKind::Ctor` -> `DefKind::Variant`
1899 if let DefKind::Ctor(..) = kind {
1900 def_id = tcx.parent(def_id).unwrap()
1903 // `DefKind::Variant` -> `DefKind::Enum`
1904 let enum_def_id = tcx.parent(def_id).unwrap();
1905 (enum_def_id, last - 1)
1907 // FIXME: lint here recommending `Enum::<...>::Variant` form
1908 // instead of `Enum::Variant::<...>` form.
1910 // Everything but the final segment should have no
1911 // parameters at all.
1912 let generics = tcx.generics_of(def_id);
1913 // Variant and struct constructors use the
1914 // generics of their parent type definition.
1915 (generics.parent.unwrap_or(def_id), last)
1917 path_segs.push(PathSeg(generics_def_id, index));
1920 // Case 3. Reference to a top-level value.
1923 | DefKind::ConstParam
1924 | DefKind::Static => {
1925 path_segs.push(PathSeg(def_id, last));
1928 // Case 4. Reference to a method or associated const.
1930 | DefKind::AssocConst => {
1931 if segments.len() >= 2 {
1932 let generics = tcx.generics_of(def_id);
1933 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1935 path_segs.push(PathSeg(def_id, last));
1938 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1941 debug!("path_segs = {:?}", path_segs);
1946 // Check a type `Path` and convert it to a `Ty`.
1947 pub fn res_to_ty(&self,
1948 opt_self_ty: Option<Ty<'tcx>>,
1950 permit_variants: bool)
1952 let tcx = self.tcx();
1954 debug!("res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
1955 path.res, opt_self_ty, path.segments);
1957 let span = path.span;
1959 Res::Def(DefKind::OpaqueTy, did) => {
1960 // Check for desugared `impl Trait`.
1961 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1962 let item_segment = path.segments.split_last().unwrap();
1963 self.prohibit_generics(item_segment.1);
1964 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1967 tcx.mk_opaque(did, substs),
1970 Res::Def(DefKind::Enum, did)
1971 | Res::Def(DefKind::TyAlias, did)
1972 | Res::Def(DefKind::Struct, did)
1973 | Res::Def(DefKind::Union, did)
1974 | Res::Def(DefKind::ForeignTy, did) => {
1975 assert_eq!(opt_self_ty, None);
1976 self.prohibit_generics(path.segments.split_last().unwrap().1);
1977 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1979 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
1980 // Convert "variant type" as if it were a real type.
1981 // The resulting `Ty` is type of the variant's enum for now.
1982 assert_eq!(opt_self_ty, None);
1985 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
1986 let generic_segs: FxHashSet<_> =
1987 path_segs.iter().map(|PathSeg(_, index)| index).collect();
1988 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1989 if !generic_segs.contains(&index) {
1996 let PathSeg(def_id, index) = path_segs.last().unwrap();
1997 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1999 Res::Def(DefKind::TyParam, def_id) => {
2000 assert_eq!(opt_self_ty, None);
2001 self.prohibit_generics(&path.segments);
2003 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2004 let item_id = tcx.hir().get_parent_node(hir_id);
2005 let item_def_id = tcx.hir().local_def_id(item_id);
2006 let generics = tcx.generics_of(item_def_id);
2007 let index = generics.param_def_id_to_index[&def_id];
2008 tcx.mk_ty_param(index, tcx.hir().name(hir_id).as_interned_str())
2010 Res::SelfTy(Some(_), None) => {
2011 // `Self` in trait or type alias.
2012 assert_eq!(opt_self_ty, None);
2013 self.prohibit_generics(&path.segments);
2016 Res::SelfTy(_, Some(def_id)) => {
2017 // `Self` in impl (we know the concrete type).
2018 assert_eq!(opt_self_ty, None);
2019 self.prohibit_generics(&path.segments);
2020 // Try to evaluate any array length constants.
2021 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2023 Res::Def(DefKind::AssocTy, def_id) => {
2024 debug_assert!(path.segments.len() >= 2);
2025 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2026 self.qpath_to_ty(span,
2029 &path.segments[path.segments.len() - 2],
2030 path.segments.last().unwrap())
2032 Res::PrimTy(prim_ty) => {
2033 assert_eq!(opt_self_ty, None);
2034 self.prohibit_generics(&path.segments);
2036 hir::Bool => tcx.types.bool,
2037 hir::Char => tcx.types.char,
2038 hir::Int(it) => tcx.mk_mach_int(it),
2039 hir::Uint(uit) => tcx.mk_mach_uint(uit),
2040 hir::Float(ft) => tcx.mk_mach_float(ft),
2041 hir::Str => tcx.mk_str()
2045 self.set_tainted_by_errors();
2046 return self.tcx().types.err;
2048 _ => span_bug!(span, "unexpected resolution: {:?}", path.res)
2052 /// Parses the programmer's textual representation of a type into our
2053 /// internal notion of a type.
2054 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
2055 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
2056 ast_ty.hir_id, ast_ty, ast_ty.node);
2058 let tcx = self.tcx();
2060 let result_ty = match ast_ty.node {
2061 hir::TyKind::Slice(ref ty) => {
2062 tcx.mk_slice(self.ast_ty_to_ty(&ty))
2064 hir::TyKind::Ptr(ref mt) => {
2065 tcx.mk_ptr(ty::TypeAndMut {
2066 ty: self.ast_ty_to_ty(&mt.ty),
2070 hir::TyKind::Rptr(ref region, ref mt) => {
2071 let r = self.ast_region_to_region(region, None);
2072 debug!("ast_ty_to_ty: r={:?}", r);
2073 let t = self.ast_ty_to_ty(&mt.ty);
2074 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
2076 hir::TyKind::Never => {
2079 hir::TyKind::Tup(ref fields) => {
2080 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2082 hir::TyKind::BareFn(ref bf) => {
2083 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2084 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
2086 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2087 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2089 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2090 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2091 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
2092 self.ast_ty_to_ty(qself)
2094 self.res_to_ty(opt_self_ty, path, false)
2096 hir::TyKind::Def(item_id, ref lifetimes) => {
2097 let did = tcx.hir().local_def_id(item_id.id);
2098 self.impl_trait_ty_to_ty(did, lifetimes)
2100 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2101 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2102 let ty = self.ast_ty_to_ty(qself);
2104 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
2109 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2110 .map(|(ty, _, _)| ty).unwrap_or(tcx.types.err)
2112 hir::TyKind::Array(ref ty, ref length) => {
2113 let length = self.ast_const_to_const(length, tcx.types.usize);
2114 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2115 self.normalize_ty(ast_ty.span, array_ty)
2117 hir::TyKind::Typeof(ref _e) => {
2118 struct_span_err!(tcx.sess, ast_ty.span, E0516,
2119 "`typeof` is a reserved keyword but unimplemented")
2120 .span_label(ast_ty.span, "reserved keyword")
2125 hir::TyKind::Infer => {
2126 // Infer also appears as the type of arguments or return
2127 // values in a ExprKind::Closure, or as
2128 // the type of local variables. Both of these cases are
2129 // handled specially and will not descend into this routine.
2130 self.ty_infer(None, ast_ty.span)
2132 hir::TyKind::CVarArgs(lt) => {
2133 let va_list_did = match tcx.lang_items().va_list() {
2135 None => span_bug!(ast_ty.span,
2136 "`va_list` lang item required for variadics"),
2138 let region = self.ast_region_to_region(<, None);
2139 tcx.type_of(va_list_did).subst(tcx, &[region.into()])
2141 hir::TyKind::Err => {
2146 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2148 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2152 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2153 pub fn const_param_def_id(&self, expr: &hir::Expr) -> Option<DefId> {
2154 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2155 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2156 let expr = match &expr.node {
2157 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() =>
2158 block.expr.as_ref().unwrap(),
2163 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2164 Res::Def(DefKind::ConstParam, did) => Some(did),
2171 pub fn ast_const_to_const(
2173 ast_const: &hir::AnonConst,
2175 ) -> &'tcx ty::Const<'tcx> {
2176 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2178 let tcx = self.tcx();
2179 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2181 let mut const_ = ty::Const {
2182 val: ConstValue::Unevaluated(
2184 InternalSubsts::identity_for_item(tcx, def_id),
2189 let expr = &tcx.hir().body(ast_const.body).value;
2190 if let Some(def_id) = self.const_param_def_id(expr) {
2191 // Find the name and index of the const parameter by indexing the generics of the
2192 // parent item and construct a `ParamConst`.
2193 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2194 let item_id = tcx.hir().get_parent_node(hir_id);
2195 let item_def_id = tcx.hir().local_def_id(item_id);
2196 let generics = tcx.generics_of(item_def_id);
2197 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2198 let name = tcx.hir().name(hir_id).as_interned_str();
2199 const_.val = ConstValue::Param(ty::ParamConst::new(index, name));
2202 tcx.mk_const(const_)
2205 pub fn impl_trait_ty_to_ty(
2208 lifetimes: &[hir::GenericArg],
2210 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2211 let tcx = self.tcx();
2213 let generics = tcx.generics_of(def_id);
2215 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2216 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2217 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2218 // Our own parameters are the resolved lifetimes.
2220 GenericParamDefKind::Lifetime => {
2221 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2222 self.ast_region_to_region(lifetime, None).into()
2230 // Replace all parent lifetimes with `'static`.
2232 GenericParamDefKind::Lifetime => {
2233 tcx.lifetimes.re_static.into()
2235 _ => tcx.mk_param_from_def(param)
2239 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2241 let ty = tcx.mk_opaque(def_id, substs);
2242 debug!("impl_trait_ty_to_ty: {}", ty);
2246 pub fn ty_of_arg(&self,
2248 expected_ty: Option<Ty<'tcx>>)
2252 hir::TyKind::Infer if expected_ty.is_some() => {
2253 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2254 expected_ty.unwrap()
2256 _ => self.ast_ty_to_ty(ty),
2260 pub fn ty_of_fn(&self,
2261 unsafety: hir::Unsafety,
2264 -> ty::PolyFnSig<'tcx> {
2267 let tcx = self.tcx();
2269 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2271 let output_ty = match decl.output {
2272 hir::Return(ref output) => self.ast_ty_to_ty(output),
2273 hir::DefaultReturn(..) => tcx.mk_unit(),
2276 debug!("ty_of_fn: output_ty={:?}", output_ty);
2278 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
2286 // Find any late-bound regions declared in return type that do
2287 // not appear in the arguments. These are not well-formed.
2290 // for<'a> fn() -> &'a str <-- 'a is bad
2291 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2292 let inputs = bare_fn_ty.inputs();
2293 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
2294 &inputs.map_bound(|i| i.to_owned()));
2295 let output = bare_fn_ty.output();
2296 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2297 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2298 let lifetime_name = match *br {
2299 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2300 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2302 let mut err = struct_span_err!(tcx.sess,
2305 "return type references {} \
2306 which is not constrained by the fn input types",
2308 if let ty::BrAnon(_) = *br {
2309 // The only way for an anonymous lifetime to wind up
2310 // in the return type but **also** be unconstrained is
2311 // if it only appears in "associated types" in the
2312 // input. See #47511 for an example. In this case,
2313 // though we can easily give a hint that ought to be
2315 err.note("lifetimes appearing in an associated type \
2316 are not considered constrained");
2324 /// Given the bounds on an object, determines what single region bound (if any) we can
2325 /// use to summarize this type. The basic idea is that we will use the bound the user
2326 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2327 /// for region bounds. It may be that we can derive no bound at all, in which case
2328 /// we return `None`.
2329 fn compute_object_lifetime_bound(&self,
2331 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
2332 -> Option<ty::Region<'tcx>> // if None, use the default
2334 let tcx = self.tcx();
2336 debug!("compute_opt_region_bound(existential_predicates={:?})",
2337 existential_predicates);
2339 // No explicit region bound specified. Therefore, examine trait
2340 // bounds and see if we can derive region bounds from those.
2341 let derived_region_bounds =
2342 object_region_bounds(tcx, existential_predicates);
2344 // If there are no derived region bounds, then report back that we
2345 // can find no region bound. The caller will use the default.
2346 if derived_region_bounds.is_empty() {
2350 // If any of the derived region bounds are 'static, that is always
2352 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2353 return Some(tcx.lifetimes.re_static);
2356 // Determine whether there is exactly one unique region in the set
2357 // of derived region bounds. If so, use that. Otherwise, report an
2359 let r = derived_region_bounds[0];
2360 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2361 span_err!(tcx.sess, span, E0227,
2362 "ambiguous lifetime bound, explicit lifetime bound required");
2368 /// Collects together a list of bounds that are applied to some type,
2369 /// after they've been converted into `ty` form (from the HIR
2370 /// representations). These lists of bounds occur in many places in
2374 /// trait Foo: Bar + Baz { }
2375 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2377 /// fn foo<T: Bar + Baz>() { }
2378 /// ^^^^^^^^^ bounding the type parameter `T`
2380 /// impl dyn Bar + Baz
2381 /// ^^^^^^^^^ bounding the forgotten dynamic type
2384 /// Our representation is a bit mixed here -- in some cases, we
2385 /// include the self type (e.g., `trait_bounds`) but in others we do
2386 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2387 pub struct Bounds<'tcx> {
2388 /// A list of region bounds on the (implicit) self type. So if you
2389 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2390 /// the `T` is not explicitly included).
2391 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2393 /// A list of trait bounds. So if you had `T: Debug` this would be
2394 /// `T: Debug`. Note that the self-type is explicit here.
2395 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2397 /// A list of projection equality bounds. So if you had `T:
2398 /// Iterator<Item = u32>` this would include `<T as
2399 /// Iterator>::Item => u32`. Note that the self-type is explicit
2401 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2403 /// `Some` if there is *no* `?Sized` predicate. The `span`
2404 /// is the location in the source of the `T` declaration which can
2405 /// be cited as the source of the `T: Sized` requirement.
2406 pub implicitly_sized: Option<Span>,
2409 impl<'tcx> Bounds<'tcx> {
2410 /// Converts a bounds list into a flat set of predicates (like
2411 /// where-clauses). Because some of our bounds listings (e.g.,
2412 /// regions) don't include the self-type, you must supply the
2413 /// self-type here (the `param_ty` parameter).
2418 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2419 // If it could be sized, and is, add the `Sized` predicate.
2420 let sized_predicate = self.implicitly_sized.and_then(|span| {
2421 tcx.lang_items().sized_trait().map(|sized| {
2422 let trait_ref = ty::TraitRef {
2424 substs: tcx.mk_substs_trait(param_ty, &[])
2426 (trait_ref.to_predicate(), span)
2430 sized_predicate.into_iter().chain(
2431 self.region_bounds.iter().map(|&(region_bound, span)| {
2432 // Account for the binder being introduced below; no need to shift `param_ty`
2433 // because, at present at least, it can only refer to early-bound regions.
2434 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2435 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2436 (ty::Binder::dummy(outlives).to_predicate(), span)
2438 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2439 (bound_trait_ref.to_predicate(), span)
2442 self.projection_bounds.iter().map(|&(projection, span)| {
2443 (projection.to_predicate(), span)