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;
11 use crate::middle::lang_items::SizedTraitLangItem;
12 use crate::middle::resolve_lifetime as rl;
13 use crate::namespace::Namespace;
14 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
16 use rustc::ty::{self, DefIdTree, Ty, TyCtxt, ToPredicate, TypeFoldable};
17 use rustc::ty::{GenericParamDef, GenericParamDefKind};
18 use rustc::ty::subst::{Kind, Subst, InternalSubsts, SubstsRef};
19 use rustc::ty::wf::object_region_bounds;
20 use rustc::mir::interpret::ConstValue;
21 use rustc_target::spec::abi;
22 use crate::require_c_abi_if_c_variadic;
23 use smallvec::SmallVec;
25 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 super::{check_type_alias_enum_variants_enabled};
38 use rustc_data_structures::fx::FxHashSet;
41 pub struct PathSeg(pub DefId, pub usize);
43 pub trait AstConv<'gcx, 'tcx> {
44 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
46 /// Returns the set of bounds in scope for the type parameter with
48 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
49 -> &'tcx ty::GenericPredicates<'tcx>;
51 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
52 fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
53 -> Option<ty::Region<'tcx>>;
55 /// Returns the type to use when a type is omitted.
56 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
58 /// Same as `ty_infer`, but with a known type parameter definition.
59 fn ty_infer_for_def(&self,
60 _def: &ty::GenericParamDef,
61 span: Span) -> Ty<'tcx> {
65 /// Projecting an associated type from a (potentially)
66 /// higher-ranked trait reference is more complicated, because of
67 /// the possibility of late-bound regions appearing in the
68 /// associated type binding. This is not legal in function
69 /// signatures for that reason. In a function body, we can always
70 /// handle it because we can use inference variables to remove the
71 /// late-bound regions.
72 fn projected_ty_from_poly_trait_ref(&self,
75 poly_trait_ref: ty::PolyTraitRef<'tcx>)
78 /// Normalize an associated type coming from the user.
79 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
81 /// Invoked when we encounter an error from some prior pass
82 /// (e.g., resolve) that is translated into a ty-error. This is
83 /// used to help suppress derived errors typeck might otherwise
85 fn set_tainted_by_errors(&self);
87 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
90 pub enum SizedByDefault {
95 struct ConvertedBinding<'tcx> {
96 item_name: ast::Ident,
97 kind: ConvertedBindingKind<'tcx>,
101 enum ConvertedBindingKind<'tcx> {
103 Constraint(P<[hir::GenericBound]>),
107 enum GenericArgPosition {
109 Value, // e.g., functions
113 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
114 pub fn ast_region_to_region(&self,
115 lifetime: &hir::Lifetime,
116 def: Option<&ty::GenericParamDef>)
119 let tcx = self.tcx();
120 let lifetime_name = |def_id| {
121 tcx.hir().name_by_hir_id(tcx.hir().as_local_hir_id(def_id).unwrap()).as_interned_str()
124 let r = match tcx.named_region(lifetime.hir_id) {
125 Some(rl::Region::Static) => {
126 tcx.lifetimes.re_static
129 Some(rl::Region::LateBound(debruijn, id, _)) => {
130 let name = lifetime_name(id);
131 tcx.mk_region(ty::ReLateBound(debruijn,
132 ty::BrNamed(id, name)))
135 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
136 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
139 Some(rl::Region::EarlyBound(index, id, _)) => {
140 let name = lifetime_name(id);
141 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
148 Some(rl::Region::Free(scope, id)) => {
149 let name = lifetime_name(id);
150 tcx.mk_region(ty::ReFree(ty::FreeRegion {
152 bound_region: ty::BrNamed(id, name)
155 // (*) -- not late-bound, won't change
159 self.re_infer(lifetime.span, def)
161 // This indicates an illegal lifetime
162 // elision. `resolve_lifetime` should have
163 // reported an error in this case -- but if
164 // not, let's error out.
165 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
167 // Supply some dummy value. We don't have an
168 // `re_error`, annoyingly, so use `'static`.
169 tcx.lifetimes.re_static
174 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
181 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
182 /// returns an appropriate set of substitutions for this particular reference to `I`.
183 pub fn ast_path_substs_for_ty(&self,
186 item_segment: &hir::PathSegment)
189 let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
190 self.create_substs_for_ast_path(
194 item_segment.infer_types,
199 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
204 /// Report error if there is an explicit type parameter when using `impl Trait`.
206 tcx: TyCtxt<'_, '_, '_>,
208 seg: &hir::PathSegment,
209 generics: &ty::Generics,
211 let explicit = !seg.infer_types;
212 let impl_trait = generics.params.iter().any(|param| match param.kind {
213 ty::GenericParamDefKind::Type {
214 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
219 if explicit && impl_trait {
220 let mut err = struct_span_err! {
224 "cannot provide explicit type parameters when `impl Trait` is \
225 used in argument position."
234 /// Checks that the correct number of generic arguments have been provided.
235 /// Used specifically for function calls.
236 pub fn check_generic_arg_count_for_call(
237 tcx: TyCtxt<'_, '_, '_>,
240 seg: &hir::PathSegment,
241 is_method_call: bool,
243 let empty_args = P(hir::GenericArgs {
244 args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
246 let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
247 Self::check_generic_arg_count(
251 if let Some(ref args) = seg.args {
257 GenericArgPosition::MethodCall
259 GenericArgPosition::Value
261 def.parent.is_none() && def.has_self, // `has_self`
262 seg.infer_types || suppress_mismatch, // `infer_types`
266 /// Checks that the correct number of generic arguments have been provided.
267 /// This is used both for datatypes and function calls.
268 fn check_generic_arg_count(
269 tcx: TyCtxt<'_, '_, '_>,
272 args: &hir::GenericArgs,
273 position: GenericArgPosition,
276 ) -> (bool, Option<Vec<Span>>) {
277 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
278 // that lifetimes will proceed types. So it suffices to check the number of each generic
279 // arguments in order to validate them with respect to the generic parameters.
280 let param_counts = def.own_counts();
281 let arg_counts = args.own_counts();
282 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
283 let infer_consts = position != GenericArgPosition::Type && arg_counts.consts == 0;
285 let mut defaults: ty::GenericParamCount = Default::default();
286 for param in &def.params {
288 GenericParamDefKind::Lifetime => {}
289 GenericParamDefKind::Type { has_default, .. } => {
290 defaults.types += has_default as usize
292 GenericParamDefKind::Const => {
293 // FIXME(const_generics:defaults)
298 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
299 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
302 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
303 let mut reported_late_bound_region_err = None;
304 if !infer_lifetimes {
305 if let Some(span_late) = def.has_late_bound_regions {
306 let msg = "cannot specify lifetime arguments explicitly \
307 if late bound lifetime parameters are present";
308 let note = "the late bound lifetime parameter is introduced here";
309 let span = args.args[0].span();
310 if position == GenericArgPosition::Value
311 && arg_counts.lifetimes != param_counts.lifetimes {
312 let mut err = tcx.sess.struct_span_err(span, msg);
313 err.span_note(span_late, note);
315 reported_late_bound_region_err = Some(true);
317 let mut multispan = MultiSpan::from_span(span);
318 multispan.push_span_label(span_late, note.to_string());
319 tcx.lint_hir(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
320 args.args[0].id(), multispan, msg);
321 reported_late_bound_region_err = Some(false);
326 let check_kind_count = |kind, required, permitted, provided, offset| {
328 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
335 // We enforce the following: `required` <= `provided` <= `permitted`.
336 // For kinds without defaults (i.e., lifetimes), `required == permitted`.
337 // For other kinds (i.e., types), `permitted` may be greater than `required`.
338 if required <= provided && provided <= permitted {
339 return (reported_late_bound_region_err.unwrap_or(false), None);
342 // Unfortunately lifetime and type parameter mismatches are typically styled
343 // differently in diagnostics, which means we have a few cases to consider here.
344 let (bound, quantifier) = if required != permitted {
345 if provided < required {
346 (required, "at least ")
347 } else { // provided > permitted
348 (permitted, "at most ")
354 let mut potential_assoc_types: Option<Vec<Span>> = None;
355 let (spans, label) = if required == permitted && provided > permitted {
356 // In the case when the user has provided too many arguments,
357 // we want to point to the unexpected arguments.
358 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
360 .map(|arg| arg.span())
362 potential_assoc_types = Some(spans.clone());
363 (spans, format!( "unexpected {} argument", kind))
365 (vec![span], format!(
366 "expected {}{} {} argument{}",
370 if bound != 1 { "s" } else { "" },
374 let mut err = tcx.sess.struct_span_err_with_code(
377 "wrong number of {} arguments: expected {}{}, found {}",
383 DiagnosticId::Error("E0107".into())
386 err.span_label(span, label.as_str());
391 provided > required, // `suppress_error`
392 potential_assoc_types,
396 if reported_late_bound_region_err.is_none()
397 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes) {
400 param_counts.lifetimes,
401 param_counts.lifetimes,
402 arg_counts.lifetimes,
406 // FIXME(const_generics:defaults)
407 if !infer_consts || arg_counts.consts > param_counts.consts {
413 arg_counts.lifetimes + arg_counts.types,
416 // Note that type errors are currently be emitted *after* const errors.
418 || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
421 param_counts.types - defaults.types - has_self as usize,
422 param_counts.types - has_self as usize,
424 arg_counts.lifetimes,
427 (reported_late_bound_region_err.unwrap_or(false), None)
431 /// Creates the relevant generic argument substitutions
432 /// corresponding to a set of generic parameters. This is a
433 /// rather complex function. Let us try to explain the role
434 /// of each of its parameters:
436 /// To start, we are given the `def_id` of the thing we are
437 /// creating the substitutions for, and a partial set of
438 /// substitutions `parent_substs`. In general, the substitutions
439 /// for an item begin with substitutions for all the "parents" of
440 /// that item -- e.g., for a method it might include the
441 /// parameters from the impl.
443 /// Therefore, the method begins by walking down these parents,
444 /// starting with the outermost parent and proceed inwards until
445 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
446 /// first to see if the parent's substitutions are listed in there. If so,
447 /// we can append those and move on. Otherwise, it invokes the
448 /// three callback functions:
450 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
451 /// generic arguments that were given to that parent from within
452 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
453 /// might refer to the trait `Foo`, and the arguments might be
454 /// `[T]`. The boolean value indicates whether to infer values
455 /// for arguments whose values were not explicitly provided.
456 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
457 /// instantiate a `Kind`.
458 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
459 /// creates a suitable inference variable.
460 pub fn create_substs_for_generic_args<'a, 'b>(
461 tcx: TyCtxt<'a, 'gcx, 'tcx>,
463 parent_substs: &[Kind<'tcx>],
465 self_ty: Option<Ty<'tcx>>,
466 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
467 provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
468 inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
469 ) -> SubstsRef<'tcx> {
470 // Collect the segments of the path; we need to substitute arguments
471 // for parameters throughout the entire path (wherever there are
472 // generic parameters).
473 let mut parent_defs = tcx.generics_of(def_id);
474 let count = parent_defs.count();
475 let mut stack = vec![(def_id, parent_defs)];
476 while let Some(def_id) = parent_defs.parent {
477 parent_defs = tcx.generics_of(def_id);
478 stack.push((def_id, parent_defs));
481 // We manually build up the substitution, rather than using convenience
482 // methods in `subst.rs`, so that we can iterate over the arguments and
483 // parameters in lock-step linearly, instead of trying to match each pair.
484 let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
486 // Iterate over each segment of the path.
487 while let Some((def_id, defs)) = stack.pop() {
488 let mut params = defs.params.iter().peekable();
490 // If we have already computed substitutions for parents, we can use those directly.
491 while let Some(¶m) = params.peek() {
492 if let Some(&kind) = parent_substs.get(param.index as usize) {
500 // `Self` is handled first, unless it's been handled in `parent_substs`.
502 if let Some(¶m) = params.peek() {
503 if param.index == 0 {
504 if let GenericParamDefKind::Type { .. } = param.kind {
505 substs.push(self_ty.map(|ty| ty.into())
506 .unwrap_or_else(|| inferred_kind(None, param, true)));
513 // Check whether this segment takes generic arguments and the user has provided any.
514 let (generic_args, infer_types) = args_for_def_id(def_id);
516 let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
520 // We're going to iterate through the generic arguments that the user
521 // provided, matching them with the generic parameters we expect.
522 // Mismatches can occur as a result of elided lifetimes, or for malformed
523 // input. We try to handle both sensibly.
524 match (args.peek(), params.peek()) {
525 (Some(&arg), Some(¶m)) => {
526 match (arg, ¶m.kind) {
527 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
528 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
529 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
530 substs.push(provided_kind(param, arg));
534 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
535 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
536 // We expected a lifetime argument, but got a type or const
537 // argument. That means we're inferring the lifetimes.
538 substs.push(inferred_kind(None, param, infer_types));
542 // We expected one kind of parameter, but the user provided
543 // another. This is an error, but we need to handle it
544 // gracefully so we can report sensible errors.
545 // In this case, we're simply going to infer this argument.
551 // We should never be able to reach this point with well-formed input.
552 // Getting to this point means the user supplied more arguments than
553 // there are parameters.
556 (None, Some(¶m)) => {
557 // If there are fewer arguments than parameters, it means
558 // we're inferring the remaining arguments.
559 substs.push(inferred_kind(Some(&substs), param, infer_types));
563 (None, None) => break,
568 tcx.intern_substs(&substs)
571 /// Given the type/lifetime/const arguments provided to some path (along with
572 /// an implicit `Self`, if this is a trait reference), returns the complete
573 /// set of substitutions. This may involve applying defaulted type parameters.
574 /// Also returns back constriants on associated types.
576 /// Note that the type listing given here is *exactly* what the user provided.
577 fn create_substs_for_ast_path<'a>(&self,
580 generic_args: &'a hir::GenericArgs,
582 self_ty: Option<Ty<'tcx>>)
583 -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
585 // If the type is parameterized by this region, then replace this
586 // region with the current anon region binding (in other words,
587 // whatever & would get replaced with).
588 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
590 def_id, self_ty, generic_args);
592 let tcx = self.tcx();
593 let generic_params = tcx.generics_of(def_id);
595 // If a self-type was declared, one should be provided.
596 assert_eq!(generic_params.has_self, self_ty.is_some());
598 let has_self = generic_params.has_self;
599 let (_, potential_assoc_types) = Self::check_generic_arg_count(
604 GenericArgPosition::Type,
609 let is_object = self_ty.map_or(false, |ty| {
610 ty == self.tcx().types.trait_object_dummy_self
612 let default_needs_object_self = |param: &ty::GenericParamDef| {
613 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
614 if is_object && has_default {
615 if tcx.at(span).type_of(param.def_id).has_self_ty() {
616 // There is no suitable inference default for a type parameter
617 // that references self, in an object type.
626 let substs = Self::create_substs_for_generic_args(
632 // Provide the generic args, and whether types should be inferred.
633 |_| (Some(generic_args), infer_types),
634 // Provide substitutions for parameters for which (valid) arguments have been provided.
636 match (¶m.kind, arg) {
637 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
638 self.ast_region_to_region(<, Some(param)).into()
640 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
641 self.ast_ty_to_ty(&ty).into()
643 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
644 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
649 // Provide substitutions for parameters for which arguments are inferred.
650 |substs, param, infer_types| {
652 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
653 GenericParamDefKind::Type { has_default, .. } => {
654 if !infer_types && has_default {
655 // No type parameter provided, but a default exists.
657 // If we are converting an object type, then the
658 // `Self` parameter is unknown. However, some of the
659 // other type parameters may reference `Self` in their
660 // defaults. This will lead to an ICE if we are not
662 if default_needs_object_self(param) {
663 struct_span_err!(tcx.sess, span, E0393,
664 "the type parameter `{}` must be explicitly specified",
667 .span_label(span, format!(
668 "missing reference to `{}`", param.name))
670 "because of the default `Self` reference, type parameters \
671 must be specified on object types"))
675 // This is a default type parameter.
678 tcx.at(span).type_of(param.def_id)
679 .subst_spanned(tcx, substs.unwrap(), Some(span))
682 } else if infer_types {
683 // No type parameters were provided, we can infer all.
684 if !default_needs_object_self(param) {
685 self.ty_infer_for_def(param, span).into()
687 self.ty_infer(span).into()
690 // We've already errored above about the mismatch.
694 GenericParamDefKind::Const => {
695 // FIXME(const_generics:defaults)
696 // We've already errored above about the mismatch.
697 tcx.consts.err.into()
703 // Convert associated-type bindings or constraints into a separate vector.
704 // Example: Given this:
706 // T: Iterator<Item = u32>
708 // The `T` is passed in as a self-type; the `Item = u32` is
709 // not a "type parameter" of the `Iterator` trait, but rather
710 // a restriction on `<T as Iterator>::Item`, so it is passed
712 let assoc_bindings = generic_args.bindings.iter()
714 let kind = match binding.kind {
715 hir::TypeBindingKind::Equality { ref ty } =>
716 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty)),
717 hir::TypeBindingKind::Constraint { ref bounds } =>
718 ConvertedBindingKind::Constraint(bounds.clone()),
721 item_name: binding.ident,
728 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
729 generic_params, self_ty, substs);
731 (substs, assoc_bindings, potential_assoc_types)
734 /// Instantiates the path for the given trait reference, assuming that it's
735 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
736 /// The type _cannot_ be a type other than a trait type.
738 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
739 /// are disallowed. Otherwise, they are pushed onto the vector given.
740 pub fn instantiate_mono_trait_ref(&self,
741 trait_ref: &hir::TraitRef,
743 ) -> ty::TraitRef<'tcx>
745 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
747 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
748 trait_ref.trait_def_id(),
750 trait_ref.path.segments.last().unwrap())
753 /// The given trait-ref must actually be a trait.
754 pub(super) fn instantiate_poly_trait_ref_inner(&self,
755 trait_ref: &hir::TraitRef,
757 bounds: &mut Bounds<'tcx>,
759 ) -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
761 let trait_def_id = trait_ref.trait_def_id();
763 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
765 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
767 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
771 trait_ref.path.segments.last().unwrap(),
773 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
775 let mut dup_bindings = FxHashMap::default();
776 for binding in &assoc_bindings {
777 // Specify type to assert that error was already reported in `Err` case.
778 let _: Result<_, ErrorReported> =
779 self.add_predicates_for_ast_type_binding(
780 trait_ref.hir_ref_id,
787 // Okay to ignore `Err` because of `ErrorReported` (see above).
790 debug!("instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
791 trait_ref, bounds, poly_trait_ref);
792 (poly_trait_ref, potential_assoc_types)
795 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
796 /// a full trait reference. The resulting trait reference is returned. This may also generate
797 /// auxiliary bounds, which are added to `bounds`.
802 /// poly_trait_ref = Iterator<Item = u32>
806 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
808 /// **A note on binders:** against our usual convention, there is an implied bounder around
809 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
810 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
811 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
812 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
814 pub fn instantiate_poly_trait_ref(&self,
815 poly_trait_ref: &hir::PolyTraitRef,
817 bounds: &mut Bounds<'tcx>
818 ) -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
820 self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty, bounds, false)
823 fn ast_path_to_mono_trait_ref(&self,
827 trait_segment: &hir::PathSegment
828 ) -> ty::TraitRef<'tcx>
830 let (substs, assoc_bindings, _) =
831 self.create_substs_for_ast_trait_ref(span,
835 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
836 ty::TraitRef::new(trait_def_id, substs)
839 fn create_substs_for_ast_trait_ref(
844 trait_segment: &hir::PathSegment,
845 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
846 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
849 let trait_def = self.tcx().trait_def(trait_def_id);
851 if !self.tcx().features().unboxed_closures &&
852 trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
853 != trait_def.paren_sugar {
854 // For now, require that parenthetical notation be used only with `Fn()` etc.
855 let msg = if trait_def.paren_sugar {
856 "the precise format of `Fn`-family traits' type parameters is subject to change. \
857 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
859 "parenthetical notation is only stable when used with `Fn`-family traits"
861 emit_feature_err(&self.tcx().sess.parse_sess, sym::unboxed_closures,
862 span, GateIssue::Language, msg);
865 trait_segment.with_generic_args(|generic_args| {
866 self.create_substs_for_ast_path(span,
869 trait_segment.infer_types,
874 fn trait_defines_associated_type_named(&self,
876 assoc_name: ast::Ident)
879 self.tcx().associated_items(trait_def_id).any(|item| {
880 item.kind == ty::AssocKind::Type &&
881 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
885 // Returns `true` if a bounds list includes `?Sized`.
886 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound], span: Span) -> bool {
887 let tcx = self.tcx();
889 // Try to find an unbound in bounds.
890 let mut unbound = None;
891 for ab in ast_bounds {
892 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
893 if unbound.is_none() {
894 unbound = Some(ptr.trait_ref.clone());
900 "type parameter has more than one relaxed default \
901 bound, only one is supported"
907 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
910 // FIXME(#8559) currently requires the unbound to be built-in.
911 if let Ok(kind_id) = kind_id {
912 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
915 "default bound relaxed for a type parameter, but \
916 this does nothing because the given bound is not \
917 a default. Only `?Sized` is supported",
922 _ if kind_id.is_ok() => {
925 // No lang item for `Sized`, so we can't add it as a bound.
932 /// This helper takes a *converted* parameter type (`param_ty`)
933 /// and an *unconverted* list of bounds:
937 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
939 /// `param_ty`, in ty form
942 /// It adds these `ast_bounds` into the `bounds` structure.
944 /// **A note on binders:** There is an implied binder around
945 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
946 /// for more details.
949 ast_bounds: &[hir::GenericBound],
950 bounds: &mut Bounds<'tcx>,
952 let mut trait_bounds = Vec::new();
953 let mut region_bounds = Vec::new();
955 for ast_bound in ast_bounds {
957 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) =>
958 trait_bounds.push(b),
959 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
960 hir::GenericBound::Outlives(ref l) =>
961 region_bounds.push(l),
965 for bound in trait_bounds {
966 let (poly_trait_ref, _) = self.instantiate_poly_trait_ref(
971 bounds.trait_bounds.push((poly_trait_ref, bound.span))
974 bounds.region_bounds.extend(region_bounds
976 .map(|r| (self.ast_region_to_region(r, None), r.span))
980 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
981 /// The self-type for the bounds is given by `param_ty`.
986 /// fn foo<T: Bar + Baz>() { }
987 /// ^ ^^^^^^^^^ ast_bounds
991 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
992 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
993 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
995 /// `span` should be the declaration size of the parameter.
996 pub fn compute_bounds(&self,
998 ast_bounds: &[hir::GenericBound],
999 sized_by_default: SizedByDefault,
1002 let mut bounds = Bounds::default();
1004 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1005 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1007 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1008 if !self.is_unsized(ast_bounds, span) {
1020 fn add_predicates_for_ast_type_binding(
1022 hir_ref_id: hir::HirId,
1023 trait_ref: ty::PolyTraitRef<'tcx>,
1024 binding: &ConvertedBinding<'tcx>,
1025 bounds: &mut Bounds<'tcx>,
1027 dup_bindings: &mut FxHashMap<DefId, Span>,
1028 ) -> Result<(), ErrorReported> {
1029 let tcx = self.tcx();
1032 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1033 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1034 // subtle in the event that `T` is defined in a supertrait of
1035 // `SomeTrait`, because in that case we need to upcast.
1037 // That is, consider this case:
1040 // trait SubTrait: SuperTrait<int> { }
1041 // trait SuperTrait<A> { type T; }
1043 // ... B: SubTrait<T = foo> ...
1046 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1048 // Find any late-bound regions declared in `ty` that are not
1049 // declared in the trait-ref. These are not well-formed.
1053 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1054 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1055 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1056 let late_bound_in_trait_ref =
1057 tcx.collect_constrained_late_bound_regions(&trait_ref);
1058 let late_bound_in_ty =
1059 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1060 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1061 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1062 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1063 let br_name = match *br {
1064 ty::BrNamed(_, name) => name,
1068 "anonymous bound region {:?} in binding but not trait ref",
1072 struct_span_err!(tcx.sess,
1075 "binding for associated type `{}` references lifetime `{}`, \
1076 which does not appear in the trait input types",
1077 binding.item_name, br_name)
1083 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
1084 binding.item_name) {
1085 // Simple case: X is defined in the current trait.
1088 // Otherwise, we have to walk through the supertraits to find
1090 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
1091 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
1093 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
1094 binding.item_name, binding.span)
1097 let (assoc_ident, def_scope) =
1098 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1099 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
1100 i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident
1101 }).expect("missing associated type");
1103 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1104 let msg = format!("associated type `{}` is private", binding.item_name);
1105 tcx.sess.span_err(binding.span, &msg);
1107 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1110 dup_bindings.entry(assoc_ty.def_id)
1111 .and_modify(|prev_span| {
1112 struct_span_err!(self.tcx().sess, binding.span, E0719,
1113 "the value of the associated type `{}` (from the trait `{}`) \
1114 is already specified",
1116 tcx.def_path_str(assoc_ty.container.id()))
1117 .span_label(binding.span, "re-bound here")
1118 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1121 .or_insert(binding.span);
1124 match binding.kind {
1125 ConvertedBindingKind::Equality(ref ty) => {
1126 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1127 // the "projection predicate" for:
1129 // `<T as Iterator>::Item = u32`
1130 bounds.projection_bounds.push((candidate.map_bound(|trait_ref| {
1131 ty::ProjectionPredicate {
1132 projection_ty: ty::ProjectionTy::from_ref_and_name(
1141 ConvertedBindingKind::Constraint(ref ast_bounds) => {
1142 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1144 // `<T as Iterator>::Item: Debug`
1146 // Calling `skip_binder` is okay, because the predicates are re-bound later by
1147 // `instantiate_poly_trait_ref`.
1148 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1159 fn ast_path_to_ty(&self,
1162 item_segment: &hir::PathSegment)
1165 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1168 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
1172 /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1173 /// removing the dummy `Self` type (`trait_object_dummy_self`).
1174 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
1175 -> ty::ExistentialTraitRef<'tcx> {
1176 if trait_ref.self_ty() != self.tcx().types.trait_object_dummy_self {
1177 bug!("trait_ref_to_existential called on {:?} with non-dummy Self", trait_ref);
1179 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
1182 fn conv_object_ty_poly_trait_ref(&self,
1184 trait_bounds: &[hir::PolyTraitRef],
1185 lifetime: &hir::Lifetime)
1188 let tcx = self.tcx();
1190 let mut bounds = Bounds::default();
1191 let mut potential_assoc_types = Vec::new();
1192 let dummy_self = self.tcx().types.trait_object_dummy_self;
1193 // FIXME: we want to avoid collecting into a `Vec` here, but simply cloning the iterator is
1194 // not straightforward due to the borrow checker.
1195 let bound_trait_refs: Vec<_> = trait_bounds
1198 .map(|trait_bound| {
1199 let (trait_ref, cur_potential_assoc_types) = self.instantiate_poly_trait_ref(
1204 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1205 (trait_ref, trait_bound.span)
1209 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1210 // is used and no 'maybe' bounds are used.
1211 let expanded_traits = traits::expand_trait_aliases(tcx, bound_trait_refs.iter().cloned());
1212 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1213 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1214 if regular_traits.len() > 1 {
1215 let first_trait = ®ular_traits[0];
1216 let additional_trait = ®ular_traits[1];
1217 let mut err = struct_span_err!(tcx.sess, additional_trait.bottom().1, E0225,
1218 "only auto traits can be used as additional traits in a trait object"
1220 additional_trait.label_with_exp_info(&mut err,
1221 "additional non-auto trait", "additional use");
1222 first_trait.label_with_exp_info(&mut err,
1223 "first non-auto trait", "first use");
1227 if regular_traits.is_empty() && auto_traits.is_empty() {
1228 span_err!(tcx.sess, span, E0224,
1229 "at least one non-builtin trait is required for an object type");
1230 return tcx.types.err;
1233 // Check that there are no gross object safety violations;
1234 // most importantly, that the supertraits don't contain `Self`,
1236 for item in ®ular_traits {
1237 let object_safety_violations =
1238 tcx.global_tcx().astconv_object_safety_violations(item.trait_ref().def_id());
1239 if !object_safety_violations.is_empty() {
1240 tcx.report_object_safety_error(
1242 item.trait_ref().def_id(),
1243 object_safety_violations
1245 .map(|mut err| err.emit());
1246 return tcx.types.err;
1250 // Use a `BTreeSet` to keep output in a more consistent order.
1251 let mut associated_types = BTreeSet::default();
1253 let regular_traits_refs = bound_trait_refs
1255 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()))
1256 .map(|(trait_ref, _)| trait_ref);
1257 for trait_ref in traits::elaborate_trait_refs(tcx, regular_traits_refs) {
1258 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", trait_ref);
1260 ty::Predicate::Trait(pred) => {
1262 .extend(tcx.associated_items(pred.def_id())
1263 .filter(|item| item.kind == ty::AssocKind::Type)
1264 .map(|item| item.def_id));
1266 ty::Predicate::Projection(pred) => {
1267 // A `Self` within the original bound will be substituted with a
1268 // `trait_object_dummy_self`, so check for that.
1269 let references_self =
1270 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1272 // If the projection output contains `Self`, force the user to
1273 // elaborate it explicitly to avoid a lot of complexity.
1275 // The "classicaly useful" case is the following:
1277 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1282 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1283 // but actually supporting that would "expand" to an infinitely-long type
1284 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1286 // Instead, we force the user to write `dyn MyTrait<MyOutput = X, Output = X>`,
1287 // which is uglier but works. See the discussion in #56288 for alternatives.
1288 if !references_self {
1289 // Include projections defined on supertraits.
1290 bounds.projection_bounds.push((pred, DUMMY_SP))
1297 for (projection_bound, _) in &bounds.projection_bounds {
1298 associated_types.remove(&projection_bound.projection_def_id());
1301 if !associated_types.is_empty() {
1302 let names = associated_types.iter().map(|item_def_id| {
1303 let assoc_item = tcx.associated_item(*item_def_id);
1304 let trait_def_id = assoc_item.container.id();
1306 "`{}` (from the trait `{}`)",
1308 tcx.def_path_str(trait_def_id),
1310 }).collect::<Vec<_>>().join(", ");
1311 let mut err = struct_span_err!(
1315 "the value of the associated type{} {} must be specified",
1316 if associated_types.len() == 1 { "" } else { "s" },
1319 let (suggest, potential_assoc_types_spans) =
1320 if potential_assoc_types.len() == associated_types.len() {
1321 // Only suggest when the amount of missing associated types equals the number of
1322 // extra type arguments present, as that gives us a relatively high confidence
1323 // that the user forgot to give the associtated type's name. The canonical
1324 // example would be trying to use `Iterator<isize>` instead of
1325 // `Iterator<Item = isize>`.
1326 (true, potential_assoc_types)
1330 let mut suggestions = Vec::new();
1331 for (i, item_def_id) in associated_types.iter().enumerate() {
1332 let assoc_item = tcx.associated_item(*item_def_id);
1335 format!("associated type `{}` must be specified", assoc_item.ident),
1337 if item_def_id.is_local() {
1339 tcx.def_span(*item_def_id),
1340 format!("`{}` defined here", assoc_item.ident),
1344 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1345 potential_assoc_types_spans[i],
1348 potential_assoc_types_spans[i],
1349 format!("{} = {}", assoc_item.ident, snippet),
1354 if !suggestions.is_empty() {
1355 let msg = format!("if you meant to specify the associated {}, write",
1356 if suggestions.len() == 1 { "type" } else { "types" });
1357 err.multipart_suggestion(
1360 Applicability::MaybeIncorrect,
1366 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1367 // `dyn Trait + Send`.
1368 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1369 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1370 debug!("regular_traits: {:?}", regular_traits);
1371 debug!("auto_traits: {:?}", auto_traits);
1373 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1374 let existential_trait_refs = regular_traits.iter().map(|i| {
1375 i.trait_ref().map_bound(|trait_ref| self.trait_ref_to_existential(trait_ref))
1377 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1378 bound.map_bound(|b| {
1379 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1380 ty::ExistentialProjection {
1382 item_def_id: b.projection_ty.item_def_id,
1383 substs: trait_ref.substs,
1388 // Calling `skip_binder` is okay because the predicates are re-bound.
1389 let regular_trait_predicates = existential_trait_refs.map(
1390 |trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1391 let auto_trait_predicates = auto_traits.into_iter().map(
1392 |trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1394 regular_trait_predicates
1395 .chain(auto_trait_predicates)
1396 .chain(existential_projections
1397 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1398 .collect::<SmallVec<[_; 8]>>();
1399 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1401 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1403 // Use explicitly-specified region bound.
1404 let region_bound = if !lifetime.is_elided() {
1405 self.ast_region_to_region(lifetime, None)
1407 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1408 if tcx.named_region(lifetime.hir_id).is_some() {
1409 self.ast_region_to_region(lifetime, None)
1411 self.re_infer(span, None).unwrap_or_else(|| {
1412 span_err!(tcx.sess, span, E0228,
1413 "the lifetime bound for this object type cannot be deduced \
1414 from context; please supply an explicit bound");
1415 tcx.lifetimes.re_static
1420 debug!("region_bound: {:?}", region_bound);
1422 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1423 debug!("trait_object_type: {:?}", ty);
1427 fn report_ambiguous_associated_type(
1434 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1435 if let (Some(_), Ok(snippet)) = (
1436 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1437 self.tcx().sess.source_map().span_to_snippet(span),
1439 err.span_suggestion(
1441 "you are looking for the module in `std`, not the primitive type",
1442 format!("std::{}", snippet),
1443 Applicability::MachineApplicable,
1446 err.span_suggestion(
1448 "use fully-qualified syntax",
1449 format!("<{} as {}>::{}", type_str, trait_str, name),
1450 Applicability::HasPlaceholders
1456 // Search for a bound on a type parameter which includes the associated item
1457 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1458 // This function will fail if there are no suitable bounds or there is
1460 fn find_bound_for_assoc_item(&self,
1461 ty_param_def_id: DefId,
1462 assoc_name: ast::Ident,
1464 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1466 let tcx = self.tcx();
1468 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1469 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1471 // Check that there is exactly one way to find an associated type with the
1473 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1474 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1476 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1477 let param_name = tcx.hir().ty_param_name(param_hir_id);
1478 self.one_bound_for_assoc_type(suitable_bounds,
1479 ¶m_name.as_str(),
1484 // Checks that `bounds` contains exactly one element and reports appropriate
1485 // errors otherwise.
1486 fn one_bound_for_assoc_type<I>(&self,
1488 ty_param_name: &str,
1489 assoc_name: ast::Ident,
1491 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1492 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1494 let bound = match bounds.next() {
1495 Some(bound) => bound,
1497 struct_span_err!(self.tcx().sess, span, E0220,
1498 "associated type `{}` not found for `{}`",
1501 .span_label(span, format!("associated type `{}` not found", assoc_name))
1503 return Err(ErrorReported);
1507 if let Some(bound2) = bounds.next() {
1508 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1509 let mut err = struct_span_err!(
1510 self.tcx().sess, span, E0221,
1511 "ambiguous associated type `{}` in bounds of `{}`",
1514 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1516 for bound in bounds {
1517 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1518 item.kind == ty::AssocKind::Type &&
1519 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1521 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1523 if let Some(span) = bound_span {
1524 err.span_label(span, format!("ambiguous `{}` from `{}`",
1528 span_note!(&mut err, span,
1529 "associated type `{}` could derive from `{}`",
1540 // Create a type from a path to an associated type.
1541 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1542 // and item_segment is the path segment for `D`. We return a type and a def for
1544 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1545 // parameter or `Self`.
1546 pub fn associated_path_to_ty(
1548 hir_ref_id: hir::HirId,
1552 assoc_segment: &hir::PathSegment,
1553 permit_variants: bool,
1554 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1555 let tcx = self.tcx();
1556 let assoc_ident = assoc_segment.ident;
1558 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1560 self.prohibit_generics(slice::from_ref(assoc_segment));
1562 // Check if we have an enum variant.
1563 let mut variant_resolution = None;
1564 if let ty::Adt(adt_def, _) = qself_ty.sty {
1565 if adt_def.is_enum() {
1566 let variant_def = adt_def.variants.iter().find(|vd| {
1567 tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1569 if let Some(variant_def) = variant_def {
1570 if permit_variants {
1571 check_type_alias_enum_variants_enabled(tcx, span);
1572 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1573 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1575 variant_resolution = Some(variant_def.def_id);
1581 // Find the type of the associated item, and the trait where the associated
1582 // item is declared.
1583 let bound = match (&qself_ty.sty, qself_res) {
1584 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
1585 // `Self` in an impl of a trait -- we have a concrete self type and a
1587 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1588 Some(trait_ref) => trait_ref,
1590 // A cycle error occurred, most likely.
1591 return Err(ErrorReported);
1595 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1596 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1598 self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span)?
1600 (&ty::Param(_), Res::SelfTy(Some(param_did), None)) |
1601 (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
1602 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
1605 if variant_resolution.is_some() {
1606 // Variant in type position
1607 let msg = format!("expected type, found variant `{}`", assoc_ident);
1608 tcx.sess.span_err(span, &msg);
1609 } else if qself_ty.is_enum() {
1610 let mut err = tcx.sess.struct_span_err(
1612 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
1615 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1616 if let Some(suggested_name) = find_best_match_for_name(
1617 adt_def.variants.iter().map(|variant| &variant.ident.name),
1618 &assoc_ident.as_str(),
1621 err.span_suggestion(
1623 "there is a variant with a similar name",
1624 suggested_name.to_string(),
1625 Applicability::MaybeIncorrect,
1628 err.span_label(span, format!("variant not found in `{}`", qself_ty));
1631 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1632 let sp = tcx.sess.source_map().def_span(sp);
1633 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1637 } else if !qself_ty.references_error() {
1638 // Don't print `TyErr` to the user.
1639 self.report_ambiguous_associated_type(
1641 &qself_ty.to_string(),
1643 &assoc_ident.as_str(),
1646 return Err(ErrorReported);
1650 let trait_did = bound.def_id();
1651 let (assoc_ident, def_scope) =
1652 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1653 let item = tcx.associated_items(trait_did).find(|i| {
1654 Namespace::from(i.kind) == Namespace::Type &&
1655 i.ident.modern() == assoc_ident
1656 }).expect("missing associated type");
1658 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1659 let ty = self.normalize_ty(span, ty);
1661 let kind = DefKind::AssocTy;
1662 if !item.vis.is_accessible_from(def_scope, tcx) {
1663 let msg = format!("{} `{}` is private", kind.descr(), assoc_ident);
1664 tcx.sess.span_err(span, &msg);
1666 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1668 if let Some(variant_def_id) = variant_resolution {
1669 let mut err = tcx.struct_span_lint_hir(
1670 AMBIGUOUS_ASSOCIATED_ITEMS,
1673 "ambiguous associated item",
1676 let mut could_refer_to = |kind: DefKind, def_id, also| {
1677 let note_msg = format!("`{}` could{} refer to {} defined here",
1678 assoc_ident, also, kind.descr());
1679 err.span_note(tcx.def_span(def_id), ¬e_msg);
1681 could_refer_to(DefKind::Variant, variant_def_id, "");
1682 could_refer_to(kind, item.def_id, " also");
1684 err.span_suggestion(
1686 "use fully-qualified syntax",
1687 format!("<{} as {}>::{}", qself_ty, "Trait", assoc_ident),
1688 Applicability::HasPlaceholders,
1692 Ok((ty, kind, item.def_id))
1695 fn qpath_to_ty(&self,
1697 opt_self_ty: Option<Ty<'tcx>>,
1699 trait_segment: &hir::PathSegment,
1700 item_segment: &hir::PathSegment)
1703 let tcx = self.tcx();
1704 let trait_def_id = tcx.parent(item_def_id).unwrap();
1706 self.prohibit_generics(slice::from_ref(item_segment));
1708 let self_ty = if let Some(ty) = opt_self_ty {
1711 let path_str = tcx.def_path_str(trait_def_id);
1712 self.report_ambiguous_associated_type(
1716 &item_segment.ident.as_str(),
1718 return tcx.types.err;
1721 debug!("qpath_to_ty: self_type={:?}", self_ty);
1723 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1728 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1730 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1733 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1734 &self, segments: T) -> bool {
1735 let mut has_err = false;
1736 for segment in segments {
1737 segment.with_generic_args(|generic_args| {
1738 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1739 for arg in &generic_args.args {
1740 let (span, kind) = match arg {
1741 hir::GenericArg::Lifetime(lt) => {
1742 if err_for_lt { continue }
1745 (lt.span, "lifetime")
1747 hir::GenericArg::Type(ty) => {
1748 if err_for_ty { continue }
1753 hir::GenericArg::Const(ct) => {
1754 if err_for_ct { continue }
1759 let mut err = struct_span_err!(
1763 "{} arguments are not allowed for this type",
1766 err.span_label(span, format!("{} argument not allowed", kind));
1768 if err_for_lt && err_for_ty && err_for_ct {
1772 for binding in &generic_args.bindings {
1774 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1782 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_, '_, '_>, span: Span) {
1783 let mut err = struct_span_err!(tcx.sess, span, E0229,
1784 "associated type bindings are not allowed here");
1785 err.span_label(span, "associated type not allowed here").emit();
1788 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1789 pub fn def_ids_for_value_path_segments(
1791 segments: &[hir::PathSegment],
1792 self_ty: Option<Ty<'tcx>>,
1796 // We need to extract the type parameters supplied by the user in
1797 // the path `path`. Due to the current setup, this is a bit of a
1798 // tricky-process; the problem is that resolve only tells us the
1799 // end-point of the path resolution, and not the intermediate steps.
1800 // Luckily, we can (at least for now) deduce the intermediate steps
1801 // just from the end-point.
1803 // There are basically five cases to consider:
1805 // 1. Reference to a constructor of a struct:
1807 // struct Foo<T>(...)
1809 // In this case, the parameters are declared in the type space.
1811 // 2. Reference to a constructor of an enum variant:
1813 // enum E<T> { Foo(...) }
1815 // In this case, the parameters are defined in the type space,
1816 // but may be specified either on the type or the variant.
1818 // 3. Reference to a fn item or a free constant:
1822 // In this case, the path will again always have the form
1823 // `a::b::foo::<T>` where only the final segment should have
1824 // type parameters. However, in this case, those parameters are
1825 // declared on a value, and hence are in the `FnSpace`.
1827 // 4. Reference to a method or an associated constant:
1829 // impl<A> SomeStruct<A> {
1833 // Here we can have a path like
1834 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1835 // may appear in two places. The penultimate segment,
1836 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1837 // final segment, `foo::<B>` contains parameters in fn space.
1839 // The first step then is to categorize the segments appropriately.
1841 let tcx = self.tcx();
1843 assert!(!segments.is_empty());
1844 let last = segments.len() - 1;
1846 let mut path_segs = vec![];
1849 // Case 1. Reference to a struct constructor.
1850 DefKind::Ctor(CtorOf::Struct, ..) => {
1851 // Everything but the final segment should have no
1852 // parameters at all.
1853 let generics = tcx.generics_of(def_id);
1854 // Variant and struct constructors use the
1855 // generics of their parent type definition.
1856 let generics_def_id = generics.parent.unwrap_or(def_id);
1857 path_segs.push(PathSeg(generics_def_id, last));
1860 // Case 2. Reference to a variant constructor.
1861 DefKind::Ctor(CtorOf::Variant, ..)
1862 | DefKind::Variant => {
1863 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1864 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1865 debug_assert!(adt_def.is_enum());
1867 } else if last >= 1 && segments[last - 1].args.is_some() {
1868 // Everything but the penultimate segment should have no
1869 // parameters at all.
1870 let mut def_id = def_id;
1872 // `DefKind::Ctor` -> `DefKind::Variant`
1873 if let DefKind::Ctor(..) = kind {
1874 def_id = tcx.parent(def_id).unwrap()
1877 // `DefKind::Variant` -> `DefKind::Enum`
1878 let enum_def_id = tcx.parent(def_id).unwrap();
1879 (enum_def_id, last - 1)
1881 // FIXME: lint here recommending `Enum::<...>::Variant` form
1882 // instead of `Enum::Variant::<...>` form.
1884 // Everything but the final segment should have no
1885 // parameters at all.
1886 let generics = tcx.generics_of(def_id);
1887 // Variant and struct constructors use the
1888 // generics of their parent type definition.
1889 (generics.parent.unwrap_or(def_id), last)
1891 path_segs.push(PathSeg(generics_def_id, index));
1894 // Case 3. Reference to a top-level value.
1897 | DefKind::ConstParam
1898 | DefKind::Static => {
1899 path_segs.push(PathSeg(def_id, last));
1902 // Case 4. Reference to a method or associated const.
1904 | DefKind::AssocConst => {
1905 if segments.len() >= 2 {
1906 let generics = tcx.generics_of(def_id);
1907 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1909 path_segs.push(PathSeg(def_id, last));
1912 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1915 debug!("path_segs = {:?}", path_segs);
1920 // Check a type `Path` and convert it to a `Ty`.
1921 pub fn res_to_ty(&self,
1922 opt_self_ty: Option<Ty<'tcx>>,
1924 permit_variants: bool)
1926 let tcx = self.tcx();
1928 debug!("res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
1929 path.res, opt_self_ty, path.segments);
1931 let span = path.span;
1933 Res::Def(DefKind::Existential, did) => {
1934 // Check for desugared `impl Trait`.
1935 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1936 let item_segment = path.segments.split_last().unwrap();
1937 self.prohibit_generics(item_segment.1);
1938 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1941 tcx.mk_opaque(did, substs),
1944 Res::Def(DefKind::Enum, did)
1945 | Res::Def(DefKind::TyAlias, did)
1946 | Res::Def(DefKind::Struct, did)
1947 | Res::Def(DefKind::Union, did)
1948 | Res::Def(DefKind::ForeignTy, did) => {
1949 assert_eq!(opt_self_ty, None);
1950 self.prohibit_generics(path.segments.split_last().unwrap().1);
1951 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1953 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
1954 // Convert "variant type" as if it were a real type.
1955 // The resulting `Ty` is type of the variant's enum for now.
1956 assert_eq!(opt_self_ty, None);
1959 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
1960 let generic_segs: FxHashSet<_> =
1961 path_segs.iter().map(|PathSeg(_, index)| index).collect();
1962 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1963 if !generic_segs.contains(&index) {
1970 let PathSeg(def_id, index) = path_segs.last().unwrap();
1971 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1973 Res::Def(DefKind::TyParam, did) => {
1974 assert_eq!(opt_self_ty, None);
1975 self.prohibit_generics(&path.segments);
1977 let hir_id = tcx.hir().as_local_hir_id(did).unwrap();
1978 let item_id = tcx.hir().get_parent_node_by_hir_id(hir_id);
1979 let item_def_id = tcx.hir().local_def_id_from_hir_id(item_id);
1980 let generics = tcx.generics_of(item_def_id);
1981 let index = generics.param_def_id_to_index[
1982 &tcx.hir().local_def_id_from_hir_id(hir_id)];
1983 tcx.mk_ty_param(index, tcx.hir().name_by_hir_id(hir_id).as_interned_str())
1985 Res::SelfTy(Some(_), None) => {
1986 // `Self` in trait or type alias.
1987 assert_eq!(opt_self_ty, None);
1988 self.prohibit_generics(&path.segments);
1991 Res::SelfTy(_, Some(def_id)) => {
1992 // `Self` in impl (we know the concrete type).
1993 assert_eq!(opt_self_ty, None);
1994 self.prohibit_generics(&path.segments);
1995 // Try to evaluate any array length constants.
1996 self.normalize_ty(span, tcx.at(span).type_of(def_id))
1998 Res::Def(DefKind::AssocTy, def_id) => {
1999 debug_assert!(path.segments.len() >= 2);
2000 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2001 self.qpath_to_ty(span,
2004 &path.segments[path.segments.len() - 2],
2005 path.segments.last().unwrap())
2007 Res::PrimTy(prim_ty) => {
2008 assert_eq!(opt_self_ty, None);
2009 self.prohibit_generics(&path.segments);
2011 hir::Bool => tcx.types.bool,
2012 hir::Char => tcx.types.char,
2013 hir::Int(it) => tcx.mk_mach_int(it),
2014 hir::Uint(uit) => tcx.mk_mach_uint(uit),
2015 hir::Float(ft) => tcx.mk_mach_float(ft),
2016 hir::Str => tcx.mk_str()
2020 self.set_tainted_by_errors();
2021 return self.tcx().types.err;
2023 _ => span_bug!(span, "unexpected resolution: {:?}", path.res)
2027 /// Parses the programmer's textual representation of a type into our
2028 /// internal notion of a type.
2029 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
2030 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
2031 ast_ty.hir_id, ast_ty, ast_ty.node);
2033 let tcx = self.tcx();
2035 let result_ty = match ast_ty.node {
2036 hir::TyKind::Slice(ref ty) => {
2037 tcx.mk_slice(self.ast_ty_to_ty(&ty))
2039 hir::TyKind::Ptr(ref mt) => {
2040 tcx.mk_ptr(ty::TypeAndMut {
2041 ty: self.ast_ty_to_ty(&mt.ty),
2045 hir::TyKind::Rptr(ref region, ref mt) => {
2046 let r = self.ast_region_to_region(region, None);
2047 debug!("ast_ty_to_ty: r={:?}", r);
2048 let t = self.ast_ty_to_ty(&mt.ty);
2049 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
2051 hir::TyKind::Never => {
2054 hir::TyKind::Tup(ref fields) => {
2055 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2057 hir::TyKind::BareFn(ref bf) => {
2058 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2059 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
2061 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2062 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2064 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2065 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2066 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
2067 self.ast_ty_to_ty(qself)
2069 self.res_to_ty(opt_self_ty, path, false)
2071 hir::TyKind::Def(item_id, ref lifetimes) => {
2072 let did = tcx.hir().local_def_id_from_hir_id(item_id.id);
2073 self.impl_trait_ty_to_ty(did, lifetimes)
2075 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2076 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2077 let ty = self.ast_ty_to_ty(qself);
2079 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
2084 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2085 .map(|(ty, _, _)| ty).unwrap_or(tcx.types.err)
2087 hir::TyKind::Array(ref ty, ref length) => {
2088 let length = self.ast_const_to_const(length, tcx.types.usize);
2089 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2090 self.normalize_ty(ast_ty.span, array_ty)
2092 hir::TyKind::Typeof(ref _e) => {
2093 struct_span_err!(tcx.sess, ast_ty.span, E0516,
2094 "`typeof` is a reserved keyword but unimplemented")
2095 .span_label(ast_ty.span, "reserved keyword")
2100 hir::TyKind::Infer => {
2101 // Infer also appears as the type of arguments or return
2102 // values in a ExprKind::Closure, or as
2103 // the type of local variables. Both of these cases are
2104 // handled specially and will not descend into this routine.
2105 self.ty_infer(ast_ty.span)
2107 hir::TyKind::CVarArgs(lt) => {
2108 let va_list_did = match tcx.lang_items().va_list() {
2110 None => span_bug!(ast_ty.span,
2111 "`va_list` lang item required for variadics"),
2113 let region = self.ast_region_to_region(<, None);
2114 tcx.type_of(va_list_did).subst(tcx, &[region.into()])
2116 hir::TyKind::Err => {
2121 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2123 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2127 pub fn ast_const_to_const(
2129 ast_const: &hir::AnonConst,
2131 ) -> &'tcx ty::Const<'tcx> {
2132 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2134 let tcx = self.tcx();
2135 let def_id = tcx.hir().local_def_id_from_hir_id(ast_const.hir_id);
2137 let mut const_ = ty::Const {
2138 val: ConstValue::Unevaluated(
2140 InternalSubsts::identity_for_item(tcx, def_id),
2145 let mut expr = &tcx.hir().body(ast_const.body).value;
2147 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2148 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2149 if let ExprKind::Block(block, _) = &expr.node {
2150 if block.stmts.is_empty() {
2151 if let Some(trailing) = &block.expr {
2157 if let ExprKind::Path(ref qpath) = expr.node {
2158 if let hir::QPath::Resolved(_, ref path) = qpath {
2159 if let Res::Def(DefKind::ConstParam, def_id) = path.res {
2160 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
2161 let item_id = tcx.hir().get_parent_node(node_id);
2162 let item_def_id = tcx.hir().local_def_id(item_id);
2163 let generics = tcx.generics_of(item_def_id);
2164 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(node_id)];
2165 let name = tcx.hir().name(node_id).as_interned_str();
2166 const_.val = ConstValue::Param(ty::ParamConst::new(index, name));
2171 tcx.mk_const(const_)
2174 pub fn impl_trait_ty_to_ty(
2177 lifetimes: &[hir::GenericArg],
2179 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2180 let tcx = self.tcx();
2182 let generics = tcx.generics_of(def_id);
2184 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2185 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2186 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2187 // Our own parameters are the resolved lifetimes.
2189 GenericParamDefKind::Lifetime => {
2190 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2191 self.ast_region_to_region(lifetime, None).into()
2199 // Replace all parent lifetimes with `'static`.
2201 GenericParamDefKind::Lifetime => {
2202 tcx.lifetimes.re_static.into()
2204 _ => tcx.mk_param_from_def(param)
2208 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2210 let ty = tcx.mk_opaque(def_id, substs);
2211 debug!("impl_trait_ty_to_ty: {}", ty);
2215 pub fn ty_of_arg(&self,
2217 expected_ty: Option<Ty<'tcx>>)
2221 hir::TyKind::Infer if expected_ty.is_some() => {
2222 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2223 expected_ty.unwrap()
2225 _ => self.ast_ty_to_ty(ty),
2229 pub fn ty_of_fn(&self,
2230 unsafety: hir::Unsafety,
2233 -> ty::PolyFnSig<'tcx> {
2236 let tcx = self.tcx();
2238 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2240 let output_ty = match decl.output {
2241 hir::Return(ref output) => self.ast_ty_to_ty(output),
2242 hir::DefaultReturn(..) => tcx.mk_unit(),
2245 debug!("ty_of_fn: output_ty={:?}", output_ty);
2247 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
2255 // Find any late-bound regions declared in return type that do
2256 // not appear in the arguments. These are not well-formed.
2259 // for<'a> fn() -> &'a str <-- 'a is bad
2260 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2261 let inputs = bare_fn_ty.inputs();
2262 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
2263 &inputs.map_bound(|i| i.to_owned()));
2264 let output = bare_fn_ty.output();
2265 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2266 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2267 let lifetime_name = match *br {
2268 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2269 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2271 let mut err = struct_span_err!(tcx.sess,
2274 "return type references {} \
2275 which is not constrained by the fn input types",
2277 if let ty::BrAnon(_) = *br {
2278 // The only way for an anonymous lifetime to wind up
2279 // in the return type but **also** be unconstrained is
2280 // if it only appears in "associated types" in the
2281 // input. See #47511 for an example. In this case,
2282 // though we can easily give a hint that ought to be
2284 err.note("lifetimes appearing in an associated type \
2285 are not considered constrained");
2293 /// Given the bounds on an object, determines what single region bound (if any) we can
2294 /// use to summarize this type. The basic idea is that we will use the bound the user
2295 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2296 /// for region bounds. It may be that we can derive no bound at all, in which case
2297 /// we return `None`.
2298 fn compute_object_lifetime_bound(&self,
2300 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
2301 -> Option<ty::Region<'tcx>> // if None, use the default
2303 let tcx = self.tcx();
2305 debug!("compute_opt_region_bound(existential_predicates={:?})",
2306 existential_predicates);
2308 // No explicit region bound specified. Therefore, examine trait
2309 // bounds and see if we can derive region bounds from those.
2310 let derived_region_bounds =
2311 object_region_bounds(tcx, existential_predicates);
2313 // If there are no derived region bounds, then report back that we
2314 // can find no region bound. The caller will use the default.
2315 if derived_region_bounds.is_empty() {
2319 // If any of the derived region bounds are 'static, that is always
2321 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2322 return Some(tcx.lifetimes.re_static);
2325 // Determine whether there is exactly one unique region in the set
2326 // of derived region bounds. If so, use that. Otherwise, report an
2328 let r = derived_region_bounds[0];
2329 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2330 span_err!(tcx.sess, span, E0227,
2331 "ambiguous lifetime bound, explicit lifetime bound required");
2337 /// Collects together a list of bounds that are applied to some type,
2338 /// after they've been converted into `ty` form (from the HIR
2339 /// representations). These lists of bounds occur in many places in
2343 /// trait Foo: Bar + Baz { }
2344 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2346 /// fn foo<T: Bar + Baz>() { }
2347 /// ^^^^^^^^^ bounding the type parameter `T`
2349 /// impl dyn Bar + Baz
2350 /// ^^^^^^^^^ bounding the forgotten dynamic type
2353 /// Our representation is a bit mixed here -- in some cases, we
2354 /// include the self type (e.g., `trait_bounds`) but in others we do
2355 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2356 pub struct Bounds<'tcx> {
2357 /// A list of region bounds on the (implicit) self type. So if you
2358 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2359 /// the `T` is not explicitly included).
2360 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2362 /// A list of trait bounds. So if you had `T: Debug` this would be
2363 /// `T: Debug`. Note that the self-type is explicit here.
2364 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2366 /// A list of projection equality bounds. So if you had `T:
2367 /// Iterator<Item = u32>` this would include `<T as
2368 /// Iterator>::Item => u32`. Note that the self-type is explicit
2370 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2372 /// `Some` if there is *no* `?Sized` predicate. The `span`
2373 /// is the location in the source of the `T` declaration which can
2374 /// be cited as the source of the `T: Sized` requirement.
2375 pub implicitly_sized: Option<Span>,
2378 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2379 /// Converts a bounds list into a flat set of predicates (like
2380 /// where-clauses). Because some of our bounds listings (e.g.,
2381 /// regions) don't include the self-type, you must supply the
2382 /// self-type here (the `param_ty` parameter).
2383 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2384 -> Vec<(ty::Predicate<'tcx>, Span)>
2386 // If it could be sized, and is, add the `Sized` predicate.
2387 let sized_predicate = self.implicitly_sized.and_then(|span| {
2388 tcx.lang_items().sized_trait().map(|sized| {
2389 let trait_ref = ty::TraitRef {
2391 substs: tcx.mk_substs_trait(param_ty, &[])
2393 (trait_ref.to_predicate(), span)
2397 sized_predicate.into_iter().chain(
2398 self.region_bounds.iter().map(|&(region_bound, span)| {
2399 // Account for the binder being introduced below; no need to shift `param_ty`
2400 // because, at present at least, it can only refer to early-bound regions.
2401 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2402 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2403 (ty::Binder::dummy(outlives).to_predicate(), span)
2405 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2406 (bound_trait_ref.to_predicate(), span)
2409 self.projection_bounds.iter().map(|&(projection, span)| {
2410 (projection.to_predicate(), span)