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, FatalError, DiagnosticId};
6 use hir::{self, GenericArg, GenericArgs};
8 use hir::def_id::DefId;
11 use middle::resolve_lifetime as rl;
12 use namespace::Namespace;
14 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
15 use rustc::ty::{GenericParamDef, GenericParamDefKind};
16 use rustc::ty::subst::{Kind, Subst, Substs};
17 use rustc::ty::wf::object_region_bounds;
18 use rustc_data_structures::sync::Lrc;
19 use rustc_target::spec::abi;
20 use require_c_abi_if_variadic;
21 use smallvec::SmallVec;
23 use syntax::feature_gate::{GateIssue, emit_feature_err};
25 use syntax::util::lev_distance::find_best_match_for_name;
26 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
27 use util::common::ErrorReported;
28 use util::nodemap::FxHashMap;
30 use std::collections::BTreeSet;
34 use super::{check_type_alias_enum_variants_enabled};
35 use rustc_data_structures::fx::FxHashSet;
38 pub struct PathSeg(pub DefId, pub usize);
40 pub trait AstConv<'gcx, 'tcx> {
41 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
43 /// Returns the set of bounds in scope for the type parameter with
45 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
46 -> Lrc<ty::GenericPredicates<'tcx>>;
48 /// What lifetime should we use when a lifetime is omitted (and not elided)?
49 fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
50 -> Option<ty::Region<'tcx>>;
52 /// What type should we use when a type is omitted?
53 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
55 /// Same as ty_infer, but with a known type parameter definition.
56 fn ty_infer_for_def(&self,
57 _def: &ty::GenericParamDef,
58 span: Span) -> Ty<'tcx> {
62 /// Projecting an associated type from a (potentially)
63 /// higher-ranked trait reference is more complicated, because of
64 /// the possibility of late-bound regions appearing in the
65 /// associated type binding. This is not legal in function
66 /// signatures for that reason. In a function body, we can always
67 /// handle it because we can use inference variables to remove the
68 /// late-bound regions.
69 fn projected_ty_from_poly_trait_ref(&self,
72 poly_trait_ref: ty::PolyTraitRef<'tcx>)
75 /// Normalize an associated type coming from the user.
76 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
78 /// Invoked when we encounter an error from some prior pass
79 /// (e.g., resolve) that is translated into a ty-error. This is
80 /// used to help suppress derived errors typeck might otherwise
82 fn set_tainted_by_errors(&self);
84 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
87 struct ConvertedBinding<'tcx> {
88 item_name: ast::Ident,
94 enum GenericArgPosition {
96 Value, // e.g., functions
100 /// Dummy type used for the `Self` of a `TraitRef` created for converting
101 /// a trait object, and which gets removed in `ExistentialTraitRef`.
102 /// This type must not appear anywhere in other converted types.
103 const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
105 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
106 pub fn ast_region_to_region(&self,
107 lifetime: &hir::Lifetime,
108 def: Option<&ty::GenericParamDef>)
111 let tcx = self.tcx();
112 let lifetime_name = |def_id| {
113 tcx.hir().name(tcx.hir().as_local_node_id(def_id).unwrap()).as_interned_str()
116 let hir_id = tcx.hir().node_to_hir_id(lifetime.id);
117 let r = match tcx.named_region(hir_id) {
118 Some(rl::Region::Static) => {
122 Some(rl::Region::LateBound(debruijn, id, _)) => {
123 let name = lifetime_name(id);
124 tcx.mk_region(ty::ReLateBound(debruijn,
125 ty::BrNamed(id, name)))
128 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
129 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
132 Some(rl::Region::EarlyBound(index, id, _)) => {
133 let name = lifetime_name(id);
134 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
141 Some(rl::Region::Free(scope, id)) => {
142 let name = lifetime_name(id);
143 tcx.mk_region(ty::ReFree(ty::FreeRegion {
145 bound_region: ty::BrNamed(id, name)
148 // (*) -- not late-bound, won't change
152 self.re_infer(lifetime.span, def)
154 // This indicates an illegal lifetime
155 // elision. `resolve_lifetime` should have
156 // reported an error in this case -- but if
157 // not, let's error out.
158 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
160 // Supply some dummy value. We don't have an
161 // `re_error`, annoyingly, so use `'static`.
167 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
174 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
175 /// returns an appropriate set of substitutions for this particular reference to `I`.
176 pub fn ast_path_substs_for_ty(&self,
179 item_segment: &hir::PathSegment)
180 -> &'tcx Substs<'tcx>
182 let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
183 self.create_substs_for_ast_path(
187 item_segment.infer_types,
192 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
197 /// Report error if there is an explicit type parameter when using `impl Trait`.
201 seg: &hir::PathSegment,
202 generics: &ty::Generics,
204 let explicit = !seg.infer_types;
205 let impl_trait = generics.params.iter().any(|param| match param.kind {
206 ty::GenericParamDefKind::Type {
207 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
212 if explicit && impl_trait {
213 let mut err = struct_span_err! {
217 "cannot provide explicit type parameters when `impl Trait` is \
218 used in argument position."
227 /// Check that the correct number of generic arguments have been provided.
228 /// Used specifically for function calls.
229 pub fn check_generic_arg_count_for_call(
233 seg: &hir::PathSegment,
234 is_method_call: bool,
236 let empty_args = P(hir::GenericArgs {
237 args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
239 let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
240 Self::check_generic_arg_count(
244 if let Some(ref args) = seg.args {
250 GenericArgPosition::MethodCall
252 GenericArgPosition::Value
254 def.parent.is_none() && def.has_self, // `has_self`
255 seg.infer_types || suppress_mismatch, // `infer_types`
259 /// Check that the correct number of generic arguments have been provided.
260 /// This is used both for datatypes and function calls.
261 fn check_generic_arg_count(
265 args: &hir::GenericArgs,
266 position: GenericArgPosition,
269 ) -> (bool, Option<Vec<Span>>) {
270 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
271 // that lifetimes will proceed types. So it suffices to check the number of each generic
272 // arguments in order to validate them with respect to the generic parameters.
273 let param_counts = def.own_counts();
274 let arg_counts = args.own_counts();
275 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
277 let mut defaults: ty::GenericParamCount = Default::default();
278 for param in &def.params {
280 GenericParamDefKind::Lifetime => {}
281 GenericParamDefKind::Type { has_default, .. } => {
282 defaults.types += has_default as usize
287 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
288 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
291 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
292 if !infer_lifetimes {
293 if let Some(span_late) = def.has_late_bound_regions {
294 let msg = "cannot specify lifetime arguments explicitly \
295 if late bound lifetime parameters are present";
296 let note = "the late bound lifetime parameter is introduced here";
297 let span = args.args[0].span();
298 if position == GenericArgPosition::Value
299 && arg_counts.lifetimes != param_counts.lifetimes {
300 let mut err = tcx.sess.struct_span_err(span, msg);
301 err.span_note(span_late, note);
305 let mut multispan = MultiSpan::from_span(span);
306 multispan.push_span_label(span_late, note.to_string());
307 tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
308 args.args[0].id(), multispan, msg);
309 return (false, None);
314 let check_kind_count = |kind,
319 // We enforce the following: `required` <= `provided` <= `permitted`.
320 // For kinds without defaults (i.e., lifetimes), `required == permitted`.
321 // For other kinds (i.e., types), `permitted` may be greater than `required`.
322 if required <= provided && provided <= permitted {
323 return (false, None);
326 // Unfortunately lifetime and type parameter mismatches are typically styled
327 // differently in diagnostics, which means we have a few cases to consider here.
328 let (bound, quantifier) = if required != permitted {
329 if provided < required {
330 (required, "at least ")
331 } else { // provided > permitted
332 (permitted, "at most ")
338 let mut potential_assoc_types: Option<Vec<Span>> = None;
339 let (spans, label) = if required == permitted && provided > permitted {
340 // In the case when the user has provided too many arguments,
341 // we want to point to the unexpected arguments.
342 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
344 .map(|arg| arg.span())
346 potential_assoc_types = Some(spans.clone());
347 (spans, format!( "unexpected {} argument", kind))
349 (vec![span], format!(
350 "expected {}{} {} argument{}",
354 if bound != 1 { "s" } else { "" },
358 let mut err = tcx.sess.struct_span_err_with_code(
361 "wrong number of {} arguments: expected {}{}, found {}",
367 DiagnosticId::Error("E0107".into())
370 err.span_label(span, label.as_str());
374 (provided > required, // `suppress_error`
375 potential_assoc_types)
378 if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
381 param_counts.lifetimes,
382 param_counts.lifetimes,
383 arg_counts.lifetimes,
388 || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
391 param_counts.types - defaults.types - has_self as usize,
392 param_counts.types - has_self as usize,
394 arg_counts.lifetimes,
401 /// Creates the relevant generic argument substitutions
402 /// corresponding to a set of generic parameters. This is a
403 /// rather complex little function. Let me try to explain the
404 /// role of each of its parameters:
406 /// To start, we are given the `def_id` of the thing we are
407 /// creating the substitutions for, and a partial set of
408 /// substitutions `parent_substs`. In general, the substitutions
409 /// for an item begin with substitutions for all the "parents" of
410 /// that item -- e.g., for a method it might include the
411 /// parameters from the impl.
413 /// Therefore, the method begins by walking down these parents,
414 /// starting with the outermost parent and proceed inwards until
415 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
416 /// first to see if the parent's substitutions are listed in there. If so,
417 /// we can append those and move on. Otherwise, it invokes the
418 /// three callback functions:
420 /// - `args_for_def_id`: given the def-id `P`, supplies back the
421 /// generic arguments that were given to that parent from within
422 /// the path; so e.g., if you have `<T as Foo>::Bar`, the def-id
423 /// might refer to the trait `Foo`, and the arguments might be
424 /// `[T]`. The boolean value indicates whether to infer values
425 /// for arguments whose values were not explicitly provided.
426 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
427 /// instantiate a `Kind`.
428 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
429 /// creates a suitable inference variable.
430 pub fn create_substs_for_generic_args<'a, 'b>(
431 tcx: TyCtxt<'a, 'gcx, 'tcx>,
433 parent_substs: &[Kind<'tcx>],
435 self_ty: Option<Ty<'tcx>>,
436 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
437 provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
438 inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
439 ) -> &'tcx Substs<'tcx> {
440 // Collect the segments of the path; we need to substitute arguments
441 // for parameters throughout the entire path (wherever there are
442 // generic parameters).
443 let mut parent_defs = tcx.generics_of(def_id);
444 let count = parent_defs.count();
445 let mut stack = vec![(def_id, parent_defs)];
446 while let Some(def_id) = parent_defs.parent {
447 parent_defs = tcx.generics_of(def_id);
448 stack.push((def_id, parent_defs));
451 // We manually build up the substitution, rather than using convenience
452 // methods in `subst.rs`, so that we can iterate over the arguments and
453 // parameters in lock-step linearly, instead of trying to match each pair.
454 let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
456 // Iterate over each segment of the path.
457 while let Some((def_id, defs)) = stack.pop() {
458 let mut params = defs.params.iter().peekable();
460 // If we have already computed substitutions for parents, we can use those directly.
461 while let Some(¶m) = params.peek() {
462 if let Some(&kind) = parent_substs.get(param.index as usize) {
470 // `Self` is handled first, unless it's been handled in `parent_substs`.
472 if let Some(¶m) = params.peek() {
473 if param.index == 0 {
474 if let GenericParamDefKind::Type { .. } = param.kind {
475 substs.push(self_ty.map(|ty| ty.into())
476 .unwrap_or_else(|| inferred_kind(None, param, true)));
483 // Check whether this segment takes generic arguments and the user has provided any.
484 let (generic_args, infer_types) = args_for_def_id(def_id);
486 let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
490 // We're going to iterate through the generic arguments that the user
491 // provided, matching them with the generic parameters we expect.
492 // Mismatches can occur as a result of elided lifetimes, or for malformed
493 // input. We try to handle both sensibly.
494 match (args.peek(), params.peek()) {
495 (Some(&arg), Some(¶m)) => {
496 match (arg, ¶m.kind) {
497 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
498 | (GenericArg::Type(_), GenericParamDefKind::Type { .. }) => {
499 substs.push(provided_kind(param, arg));
503 (GenericArg::Lifetime(_), GenericParamDefKind::Type { .. }) => {
504 // We expected a type argument, but got a lifetime
505 // argument. This is an error, but we need to handle it
506 // gracefully so we can report sensible errors. In this
507 // case, we're simply going to infer this argument.
510 (GenericArg::Type(_), GenericParamDefKind::Lifetime) => {
511 // We expected a lifetime argument, but got a type
512 // argument. That means we're inferring the lifetimes.
513 substs.push(inferred_kind(None, param, infer_types));
519 // We should never be able to reach this point with well-formed input.
520 // Getting to this point means the user supplied more arguments than
521 // there are parameters.
524 (None, Some(¶m)) => {
525 // If there are fewer arguments than parameters, it means
526 // we're inferring the remaining arguments.
528 GenericParamDefKind::Lifetime | GenericParamDefKind::Type { .. } => {
529 let kind = inferred_kind(Some(&substs), param, infer_types);
536 (None, None) => break,
541 tcx.intern_substs(&substs)
544 /// Given the type/region arguments provided to some path (along with
545 /// an implicit `Self`, if this is a trait reference) returns the complete
546 /// set of substitutions. This may involve applying defaulted type parameters.
548 /// Note that the type listing given here is *exactly* what the user provided.
549 fn create_substs_for_ast_path(&self,
552 generic_args: &hir::GenericArgs,
554 self_ty: Option<Ty<'tcx>>)
555 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
557 // If the type is parameterized by this region, then replace this
558 // region with the current anon region binding (in other words,
559 // whatever & would get replaced with).
560 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
562 def_id, self_ty, generic_args);
564 let tcx = self.tcx();
565 let generic_params = tcx.generics_of(def_id);
567 // If a self-type was declared, one should be provided.
568 assert_eq!(generic_params.has_self, self_ty.is_some());
570 let has_self = generic_params.has_self;
571 let (_, potential_assoc_types) = Self::check_generic_arg_count(
576 GenericArgPosition::Type,
581 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
582 let default_needs_object_self = |param: &ty::GenericParamDef| {
583 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
584 if is_object && has_default {
585 if tcx.at(span).type_of(param.def_id).has_self_ty() {
586 // There is no suitable inference default for a type parameter
587 // that references self, in an object type.
596 let substs = Self::create_substs_for_generic_args(
602 // Provide the generic args, and whether types should be inferred.
603 |_| (Some(generic_args), infer_types),
604 // Provide substitutions for parameters for which (valid) arguments have been provided.
606 match (¶m.kind, arg) {
607 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
608 self.ast_region_to_region(<, Some(param)).into()
610 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
611 self.ast_ty_to_ty(&ty).into()
616 // Provide substitutions for parameters for which arguments are inferred.
617 |substs, param, infer_types| {
619 GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
620 GenericParamDefKind::Type { has_default, .. } => {
621 if !infer_types && has_default {
622 // No type parameter provided, but a default exists.
624 // If we are converting an object type, then the
625 // `Self` parameter is unknown. However, some of the
626 // other type parameters may reference `Self` in their
627 // defaults. This will lead to an ICE if we are not
629 if default_needs_object_self(param) {
630 struct_span_err!(tcx.sess, span, E0393,
631 "the type parameter `{}` must be explicitly \
635 format!("missing reference to `{}`", param.name))
636 .note(&format!("because of the default `Self` reference, \
637 type parameters must be specified on object \
642 // This is a default type parameter.
645 tcx.at(span).type_of(param.def_id)
646 .subst_spanned(tcx, substs.unwrap(), Some(span))
649 } else if infer_types {
650 // No type parameters were provided, we can infer all.
651 if !default_needs_object_self(param) {
652 self.ty_infer_for_def(param, span).into()
654 self.ty_infer(span).into()
657 // We've already errored above about the mismatch.
665 let assoc_bindings = generic_args.bindings.iter().map(|binding| {
667 item_name: binding.ident,
668 ty: self.ast_ty_to_ty(&binding.ty),
673 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
674 generic_params, self_ty, substs);
676 (substs, assoc_bindings, potential_assoc_types)
679 /// Instantiates the path for the given trait reference, assuming that it's
680 /// bound to a valid trait type. Returns the def_id for the defining trait.
681 /// The type _cannot_ be a type other than a trait type.
683 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
684 /// are disallowed. Otherwise, they are pushed onto the vector given.
685 pub fn instantiate_mono_trait_ref(&self,
686 trait_ref: &hir::TraitRef,
688 -> ty::TraitRef<'tcx>
690 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
692 let trait_def_id = self.trait_def_id(trait_ref);
693 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
696 trait_ref.path.segments.last().unwrap())
699 /// Get the `DefId` of the given trait ref. It _must_ actually be a trait.
700 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
701 let path = &trait_ref.path;
703 Def::Trait(trait_def_id) => trait_def_id,
704 Def::TraitAlias(alias_def_id) => alias_def_id,
712 /// The given trait ref must actually be a trait.
713 pub(super) fn instantiate_poly_trait_ref_inner(&self,
714 trait_ref: &hir::TraitRef,
716 poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
718 -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
720 let trait_def_id = self.trait_def_id(trait_ref);
722 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
724 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
726 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
730 trait_ref.path.segments.last().unwrap(),
732 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
734 let mut dup_bindings = FxHashMap::default();
735 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
736 // specify type to assert that error was already reported in Err case:
737 let predicate: Result<_, ErrorReported> =
738 self.ast_type_binding_to_poly_projection_predicate(
739 trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
740 // okay to ignore Err because of ErrorReported (see above)
741 Some((predicate.ok()?, binding.span))
744 debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
745 trait_ref, poly_projections, poly_trait_ref);
746 (poly_trait_ref, potential_assoc_types)
749 pub fn instantiate_poly_trait_ref(&self,
750 poly_trait_ref: &hir::PolyTraitRef,
752 poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
753 -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
755 self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
756 poly_projections, false)
759 fn ast_path_to_mono_trait_ref(&self,
763 trait_segment: &hir::PathSegment)
764 -> ty::TraitRef<'tcx>
766 let (substs, assoc_bindings, _) =
767 self.create_substs_for_ast_trait_ref(span,
771 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
772 ty::TraitRef::new(trait_def_id, substs)
775 fn create_substs_for_ast_trait_ref(
780 trait_segment: &hir::PathSegment,
781 ) -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
782 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
785 let trait_def = self.tcx().trait_def(trait_def_id);
787 if !self.tcx().features().unboxed_closures &&
788 trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
789 != trait_def.paren_sugar {
790 // For now, require that parenthetical notation be used only with `Fn()` etc.
791 let msg = if trait_def.paren_sugar {
792 "the precise format of `Fn`-family traits' type parameters is subject to change. \
793 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
795 "parenthetical notation is only stable when used with `Fn`-family traits"
797 emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
798 span, GateIssue::Language, msg);
801 trait_segment.with_generic_args(|generic_args| {
802 self.create_substs_for_ast_path(span,
805 trait_segment.infer_types,
810 fn trait_defines_associated_type_named(&self,
812 assoc_name: ast::Ident)
815 self.tcx().associated_items(trait_def_id).any(|item| {
816 item.kind == ty::AssociatedKind::Type &&
817 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
821 fn ast_type_binding_to_poly_projection_predicate(
824 trait_ref: ty::PolyTraitRef<'tcx>,
825 binding: &ConvertedBinding<'tcx>,
827 dup_bindings: &mut FxHashMap<DefId, Span>)
828 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
830 let tcx = self.tcx();
833 // Given something like `U: SomeTrait<T = X>`, we want to produce a
834 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
835 // subtle in the event that `T` is defined in a supertrait of
836 // `SomeTrait`, because in that case we need to upcast.
838 // That is, consider this case:
841 // trait SubTrait: SuperTrait<int> { }
842 // trait SuperTrait<A> { type T; }
844 // ... B : SubTrait<T=foo> ...
847 // We want to produce `<B as SuperTrait<int>>::T == foo`.
849 // Find any late-bound regions declared in `ty` that are not
850 // declared in the trait-ref. These are not wellformed.
854 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
855 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
856 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
857 let late_bound_in_ty =
858 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
859 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
860 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
861 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
862 let br_name = match *br {
863 ty::BrNamed(_, name) => name,
867 "anonymous bound region {:?} in binding but not trait ref",
871 struct_span_err!(tcx.sess,
874 "binding for associated type `{}` references lifetime `{}`, \
875 which does not appear in the trait input types",
876 binding.item_name, br_name)
881 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
883 // Simple case: X is defined in the current trait.
886 // Otherwise, we have to walk through the supertraits to find
888 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
889 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
891 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
892 binding.item_name, binding.span)
895 let (assoc_ident, def_scope) =
896 tcx.adjust_ident(binding.item_name, candidate.def_id(), ref_id);
897 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
898 i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
899 }).expect("missing associated type");
901 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
902 let msg = format!("associated type `{}` is private", binding.item_name);
903 tcx.sess.span_err(binding.span, &msg);
905 tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
908 dup_bindings.entry(assoc_ty.def_id)
909 .and_modify(|prev_span| {
910 struct_span_err!(self.tcx().sess, binding.span, E0719,
911 "the value of the associated type `{}` (from the trait `{}`) \
912 is already specified",
914 tcx.item_path_str(assoc_ty.container.id()))
915 .span_label(binding.span, "re-bound here")
916 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
919 .or_insert(binding.span);
922 Ok(candidate.map_bound(|trait_ref| {
923 ty::ProjectionPredicate {
924 projection_ty: ty::ProjectionTy::from_ref_and_name(
934 fn ast_path_to_ty(&self,
937 item_segment: &hir::PathSegment)
940 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
943 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
947 /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
948 /// removing the dummy `Self` type (`TRAIT_OBJECT_DUMMY_SELF`).
949 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
950 -> ty::ExistentialTraitRef<'tcx> {
951 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
952 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
955 fn conv_object_ty_poly_trait_ref(&self,
957 trait_bounds: &[hir::PolyTraitRef],
958 lifetime: &hir::Lifetime)
961 let tcx = self.tcx();
963 if trait_bounds.is_empty() {
964 span_err!(tcx.sess, span, E0224,
965 "at least one non-builtin trait is required for an object type");
966 return tcx.types.err;
969 let mut projection_bounds = Vec::new();
970 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
971 let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
974 &mut projection_bounds,
976 debug!("principal: {:?}", principal);
978 for trait_bound in trait_bounds[1..].iter() {
979 // sanity check for non-principal trait bounds
980 self.instantiate_poly_trait_ref(trait_bound,
985 let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
987 if !trait_bounds.is_empty() {
988 let b = &trait_bounds[0];
989 let span = b.trait_ref.path.span;
990 struct_span_err!(self.tcx().sess, span, E0225,
991 "only auto traits can be used as additional traits in a trait object")
992 .span_label(span, "non-auto additional trait")
996 // Check that there are no gross object safety violations;
997 // most importantly, that the supertraits don't contain `Self`,
999 let object_safety_violations =
1000 tcx.global_tcx().astconv_object_safety_violations(principal.def_id());
1001 if !object_safety_violations.is_empty() {
1002 tcx.report_object_safety_error(
1003 span, principal.def_id(), object_safety_violations)
1005 return tcx.types.err;
1008 // Use a `BTreeSet` to keep output in a more consistent order.
1009 let mut associated_types = BTreeSet::default();
1011 for tr in traits::elaborate_trait_ref(tcx, principal) {
1012 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", tr);
1014 ty::Predicate::Trait(pred) => {
1015 associated_types.extend(tcx.associated_items(pred.def_id())
1016 .filter(|item| item.kind == ty::AssociatedKind::Type)
1017 .map(|item| item.def_id));
1019 ty::Predicate::Projection(pred) => {
1020 // A `Self` within the original bound will be substituted with a
1021 // `TRAIT_OBJECT_DUMMY_SELF`, so check for that.
1022 let references_self =
1023 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1025 // If the projection output contains `Self`, force the user to
1026 // elaborate it explicitly to avoid a bunch of complexity.
1028 // The "classicaly useful" case is the following:
1030 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1035 // Here, the user could theoretically write `dyn MyTrait<Output=X>`,
1036 // but actually supporting that would "expand" to an infinitely-long type
1037 // `fix $ τ → dyn MyTrait<MyOutput=X, Output=<τ as MyTrait>::MyOutput`.
1039 // Instead, we force the user to write `dyn MyTrait<MyOutput=X, Output=X>`,
1040 // which is uglier but works. See the discussion in #56288 for alternatives.
1041 if !references_self {
1042 // Include projections defined on supertraits,
1043 projection_bounds.push((pred, DUMMY_SP))
1050 for (projection_bound, _) in &projection_bounds {
1051 associated_types.remove(&projection_bound.projection_def_id());
1054 if !associated_types.is_empty() {
1055 let names = associated_types.iter().map(|item_def_id| {
1056 let assoc_item = tcx.associated_item(*item_def_id);
1057 let trait_def_id = assoc_item.container.id();
1059 "`{}` (from the trait `{}`)",
1061 tcx.item_path_str(trait_def_id),
1063 }).collect::<Vec<_>>().join(", ");
1064 let mut err = struct_span_err!(
1068 "the value of the associated type{} {} must be specified",
1069 if associated_types.len() == 1 { "" } else { "s" },
1072 let mut suggest = false;
1073 let mut potential_assoc_types_spans = vec![];
1074 if let Some(potential_assoc_types) = potential_assoc_types {
1075 if potential_assoc_types.len() == associated_types.len() {
1076 // Only suggest when the amount of missing associated types is equals to the
1077 // extra type arguments present, as that gives us a relatively high confidence
1078 // that the user forgot to give the associtated type's name. The canonical
1079 // example would be trying to use `Iterator<isize>` instead of
1080 // `Iterator<Item=isize>`.
1082 potential_assoc_types_spans = potential_assoc_types;
1085 let mut suggestions = vec![];
1086 for (i, item_def_id) in associated_types.iter().enumerate() {
1087 let assoc_item = tcx.associated_item(*item_def_id);
1090 format!("associated type `{}` must be specified", assoc_item.ident),
1092 if item_def_id.is_local() {
1094 tcx.def_span(*item_def_id),
1095 format!("`{}` defined here", assoc_item.ident),
1099 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1100 potential_assoc_types_spans[i],
1103 potential_assoc_types_spans[i],
1104 format!("{} = {}", assoc_item.ident, snippet),
1109 if !suggestions.is_empty() {
1110 let msg = format!("if you meant to specify the associated {}, write",
1111 if suggestions.len() == 1 { "type" } else { "types" });
1112 err.multipart_suggestion_with_applicability(
1115 Applicability::MaybeIncorrect,
1121 // Erase the `dummy_self` (`TRAIT_OBJECT_DUMMY_SELF`) used above.
1122 let existential_principal = principal.map_bound(|trait_ref| {
1123 self.trait_ref_to_existential(trait_ref)
1125 let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1126 bound.map_bound(|b| {
1127 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1128 ty::ExistentialProjection {
1130 item_def_id: b.projection_ty.item_def_id,
1131 substs: trait_ref.substs,
1136 // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1138 auto_traits.dedup();
1140 // Calling `skip_binder` is okay, because the predicates are re-bound.
1141 let principal = if tcx.trait_is_auto(existential_principal.def_id()) {
1142 ty::ExistentialPredicate::AutoTrait(existential_principal.def_id())
1144 ty::ExistentialPredicate::Trait(*existential_principal.skip_binder())
1147 iter::once(principal)
1148 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1149 .chain(existential_projections
1150 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1151 .collect::<SmallVec<[_; 8]>>();
1152 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1154 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1156 // Use explicitly-specified region bound.
1157 let region_bound = if !lifetime.is_elided() {
1158 self.ast_region_to_region(lifetime, None)
1160 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1161 let hir_id = tcx.hir().node_to_hir_id(lifetime.id);
1162 if tcx.named_region(hir_id).is_some() {
1163 self.ast_region_to_region(lifetime, None)
1165 self.re_infer(span, None).unwrap_or_else(|| {
1166 span_err!(tcx.sess, span, E0228,
1167 "the lifetime bound for this object type cannot be deduced \
1168 from context; please supply an explicit bound");
1175 debug!("region_bound: {:?}", region_bound);
1177 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1178 debug!("trait_object_type: {:?}", ty);
1182 fn report_ambiguous_associated_type(&self,
1187 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1188 .span_suggestion_with_applicability(
1190 "use fully-qualified syntax",
1191 format!("<{} as {}>::{}", type_str, trait_str, name),
1192 Applicability::HasPlaceholders
1196 // Search for a bound on a type parameter which includes the associated item
1197 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1198 // This function will fail if there are no suitable bounds or there is
1200 fn find_bound_for_assoc_item(&self,
1201 ty_param_def_id: DefId,
1202 assoc_name: ast::Ident,
1204 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1206 let tcx = self.tcx();
1208 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1209 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1211 // Check that there is exactly one way to find an associated type with the
1213 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1214 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1216 let param_node_id = tcx.hir().as_local_node_id(ty_param_def_id).unwrap();
1217 let param_name = tcx.hir().ty_param_name(param_node_id);
1218 self.one_bound_for_assoc_type(suitable_bounds,
1219 ¶m_name.as_str(),
1224 // Checks that `bounds` contains exactly one element and reports appropriate
1225 // errors otherwise.
1226 fn one_bound_for_assoc_type<I>(&self,
1228 ty_param_name: &str,
1229 assoc_name: ast::Ident,
1231 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1232 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1234 let bound = match bounds.next() {
1235 Some(bound) => bound,
1237 struct_span_err!(self.tcx().sess, span, E0220,
1238 "associated type `{}` not found for `{}`",
1241 .span_label(span, format!("associated type `{}` not found", assoc_name))
1243 return Err(ErrorReported);
1247 if let Some(bound2) = bounds.next() {
1248 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1249 let mut err = struct_span_err!(
1250 self.tcx().sess, span, E0221,
1251 "ambiguous associated type `{}` in bounds of `{}`",
1254 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1256 for bound in bounds {
1257 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1258 item.kind == ty::AssociatedKind::Type &&
1259 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1261 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1263 if let Some(span) = bound_span {
1264 err.span_label(span, format!("ambiguous `{}` from `{}`",
1268 span_note!(&mut err, span,
1269 "associated type `{}` could derive from `{}`",
1280 // Create a type from a path to an associated type.
1281 // For a path `A::B::C::D`, `ty` and `ty_path_def` are the type and def for `A::B::C`
1282 // and item_segment is the path segment for `D`. We return a type and a def for
1284 // Will fail except for `T::A` and `Self::A`; i.e., if `ty`/`ty_path_def` are not a type
1285 // parameter or `Self`.
1286 pub fn associated_path_def_to_ty(&self,
1287 ref_id: ast::NodeId,
1291 item_segment: &hir::PathSegment)
1294 let tcx = self.tcx();
1295 let assoc_name = item_segment.ident;
1297 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1299 self.prohibit_generics(slice::from_ref(item_segment));
1301 // Find the type of the associated item, and the trait where the associated
1302 // item is declared.
1303 let bound = match (&ty.sty, ty_path_def) {
1304 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1305 // `Self` in an impl of a trait -- we have a concrete self type and a
1307 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1308 Some(trait_ref) => trait_ref,
1310 // A cycle error occurred, most likely.
1311 return (tcx.types.err, Def::Err);
1315 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1316 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1318 match self.one_bound_for_assoc_type(candidates, "Self", assoc_name, span) {
1320 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1323 (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1324 (&ty::Param(_), Def::TyParam(param_did)) => {
1325 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
1327 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1330 (&ty::Adt(adt_def, _substs), Def::Enum(_did)) => {
1331 let ty_str = ty.to_string();
1332 // Incorrect enum variant.
1333 let mut err = tcx.sess.struct_span_err(
1335 &format!("no variant `{}` on enum `{}`", &assoc_name.as_str(), ty_str),
1337 // Check if it was a typo.
1338 let input = adt_def.variants.iter().map(|variant| &variant.ident.name);
1339 if let Some(suggested_name) = find_best_match_for_name(
1341 &assoc_name.as_str(),
1344 err.span_suggestion_with_applicability(
1347 format!("{}::{}", ty_str, suggested_name.to_string()),
1348 Applicability::MaybeIncorrect,
1351 err.span_label(span, "unknown variant");
1354 return (tcx.types.err, Def::Err);
1357 // Check if we have an enum variant.
1359 ty::Adt(adt_def, _) if adt_def.is_enum() => {
1360 let variant_def = adt_def.variants.iter().find(|vd| {
1361 tcx.hygienic_eq(assoc_name, vd.ident, adt_def.did)
1363 if let Some(variant_def) = variant_def {
1364 check_type_alias_enum_variants_enabled(tcx, span);
1366 let def = Def::Variant(variant_def.did);
1367 tcx.check_stability(def.def_id(), Some(ref_id), span);
1374 // Don't print `TyErr` to the user.
1375 if !ty.references_error() {
1376 self.report_ambiguous_associated_type(span,
1379 &assoc_name.as_str());
1381 return (tcx.types.err, Def::Err);
1385 let trait_did = bound.def_id();
1386 let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_name, trait_did, ref_id);
1387 let item = tcx.associated_items(trait_did).find(|i| {
1388 Namespace::from(i.kind) == Namespace::Type &&
1389 i.ident.modern() == assoc_ident
1390 }).expect("missing associated type");
1392 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1393 let ty = self.normalize_ty(span, ty);
1395 let def = Def::AssociatedTy(item.def_id);
1396 if !item.vis.is_accessible_from(def_scope, tcx) {
1397 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
1398 tcx.sess.span_err(span, &msg);
1400 tcx.check_stability(item.def_id, Some(ref_id), span);
1405 fn qpath_to_ty(&self,
1407 opt_self_ty: Option<Ty<'tcx>>,
1409 trait_segment: &hir::PathSegment,
1410 item_segment: &hir::PathSegment)
1413 let tcx = self.tcx();
1414 let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1416 self.prohibit_generics(slice::from_ref(item_segment));
1418 let self_ty = if let Some(ty) = opt_self_ty {
1421 let path_str = tcx.item_path_str(trait_def_id);
1422 self.report_ambiguous_associated_type(span,
1425 &item_segment.ident.as_str());
1426 return tcx.types.err;
1429 debug!("qpath_to_ty: self_type={:?}", self_ty);
1431 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1436 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1438 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1441 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1442 &self, segments: T) -> bool {
1443 let mut has_err = false;
1444 for segment in segments {
1445 segment.with_generic_args(|generic_args| {
1446 let (mut err_for_lt, mut err_for_ty) = (false, false);
1447 for arg in &generic_args.args {
1448 let (mut span_err, span, kind) = match arg {
1449 hir::GenericArg::Lifetime(lt) => {
1450 if err_for_lt { continue }
1453 (struct_span_err!(self.tcx().sess, lt.span, E0110,
1454 "lifetime arguments are not allowed on this entity"),
1458 hir::GenericArg::Type(ty) => {
1459 if err_for_ty { continue }
1462 (struct_span_err!(self.tcx().sess, ty.span, E0109,
1463 "type arguments are not allowed on this entity"),
1468 span_err.span_label(span, format!("{} argument not allowed", kind))
1470 if err_for_lt && err_for_ty {
1474 for binding in &generic_args.bindings {
1476 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1484 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt, span: Span) {
1485 let mut err = struct_span_err!(tcx.sess, span, E0229,
1486 "associated type bindings are not allowed here");
1487 err.span_label(span, "associated type not allowed here").emit();
1490 pub fn def_ids_for_path_segments(&self,
1491 segments: &[hir::PathSegment],
1492 self_ty: Option<Ty<'tcx>>,
1495 // We need to extract the type parameters supplied by the user in
1496 // the path `path`. Due to the current setup, this is a bit of a
1497 // tricky-process; the problem is that resolve only tells us the
1498 // end-point of the path resolution, and not the intermediate steps.
1499 // Luckily, we can (at least for now) deduce the intermediate steps
1500 // just from the end-point.
1502 // There are basically five cases to consider:
1504 // 1. Reference to a constructor of a struct:
1506 // struct Foo<T>(...)
1508 // In this case, the parameters are declared in the type space.
1510 // 2. Reference to a constructor of an enum variant:
1512 // enum E<T> { Foo(...) }
1514 // In this case, the parameters are defined in the type space,
1515 // but may be specified either on the type or the variant.
1517 // 3. Reference to a fn item or a free constant:
1521 // In this case, the path will again always have the form
1522 // `a::b::foo::<T>` where only the final segment should have
1523 // type parameters. However, in this case, those parameters are
1524 // declared on a value, and hence are in the `FnSpace`.
1526 // 4. Reference to a method or an associated constant:
1528 // impl<A> SomeStruct<A> {
1532 // Here we can have a path like
1533 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1534 // may appear in two places. The penultimate segment,
1535 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1536 // final segment, `foo::<B>` contains parameters in fn space.
1538 // 5. Reference to a local variable
1540 // Local variables can't have any type parameters.
1542 // The first step then is to categorize the segments appropriately.
1544 let tcx = self.tcx();
1546 assert!(!segments.is_empty());
1547 let last = segments.len() - 1;
1549 let mut path_segs = vec![];
1552 // Case 1. Reference to a struct constructor.
1553 Def::StructCtor(def_id, ..) |
1554 Def::SelfCtor(.., def_id) => {
1555 // Everything but the final segment should have no
1556 // parameters at all.
1557 let generics = tcx.generics_of(def_id);
1558 // Variant and struct constructors use the
1559 // generics of their parent type definition.
1560 let generics_def_id = generics.parent.unwrap_or(def_id);
1561 path_segs.push(PathSeg(generics_def_id, last));
1564 // Case 2. Reference to a variant constructor.
1565 Def::Variant(def_id) |
1566 Def::VariantCtor(def_id, ..) => {
1567 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1568 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1569 debug_assert!(adt_def.is_enum());
1571 } else if last >= 1 && segments[last - 1].args.is_some() {
1572 // Everything but the penultimate segment should have no
1573 // parameters at all.
1574 let enum_def_id = tcx.parent_def_id(def_id).unwrap();
1575 (enum_def_id, last - 1)
1577 // FIXME: lint here recommending `Enum::<...>::Variant` form
1578 // instead of `Enum::Variant::<...>` form.
1580 // Everything but the final segment should have no
1581 // parameters at all.
1582 let generics = tcx.generics_of(def_id);
1583 // Variant and struct constructors use the
1584 // generics of their parent type definition.
1585 (generics.parent.unwrap_or(def_id), last)
1587 path_segs.push(PathSeg(generics_def_id, index));
1590 // Case 3. Reference to a top-level value.
1592 Def::Const(def_id) |
1593 Def::Static(def_id, _) => {
1594 path_segs.push(PathSeg(def_id, last));
1597 // Case 4. Reference to a method or associated const.
1598 Def::Method(def_id) |
1599 Def::AssociatedConst(def_id) => {
1600 if segments.len() >= 2 {
1601 let generics = tcx.generics_of(def_id);
1602 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1604 path_segs.push(PathSeg(def_id, last));
1607 // Case 5. Local variable, no generics.
1608 Def::Local(..) | Def::Upvar(..) => {}
1610 _ => bug!("unexpected definition: {:?}", def),
1613 debug!("path_segs = {:?}", path_segs);
1618 // Check a type `Path` and convert it to a `Ty`.
1619 pub fn def_to_ty(&self,
1620 opt_self_ty: Option<Ty<'tcx>>,
1622 permit_variants: bool)
1624 let tcx = self.tcx();
1626 debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1627 path.def, opt_self_ty, path.segments);
1629 let span = path.span;
1631 Def::Existential(did) => {
1632 // Check for desugared impl trait.
1633 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1634 let item_segment = path.segments.split_last().unwrap();
1635 self.prohibit_generics(item_segment.1);
1636 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1639 tcx.mk_opaque(did, substs),
1642 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1643 Def::Union(did) | Def::ForeignTy(did) => {
1644 assert_eq!(opt_self_ty, None);
1645 self.prohibit_generics(path.segments.split_last().unwrap().1);
1646 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1648 Def::Variant(_) if permit_variants => {
1649 // Convert "variant type" as if it were a real type.
1650 // The resulting `Ty` is type of the variant's enum for now.
1651 assert_eq!(opt_self_ty, None);
1653 let path_segs = self.def_ids_for_path_segments(&path.segments, None, path.def);
1654 let generic_segs: FxHashSet<_> =
1655 path_segs.iter().map(|PathSeg(_, index)| index).collect();
1656 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1657 if !generic_segs.contains(&index) {
1664 let PathSeg(def_id, index) = path_segs.last().unwrap();
1665 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1667 Def::TyParam(did) => {
1668 assert_eq!(opt_self_ty, None);
1669 self.prohibit_generics(&path.segments);
1671 let node_id = tcx.hir().as_local_node_id(did).unwrap();
1672 let item_id = tcx.hir().get_parent_node(node_id);
1673 let item_def_id = tcx.hir().local_def_id(item_id);
1674 let generics = tcx.generics_of(item_def_id);
1675 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(node_id)];
1676 tcx.mk_ty_param(index, tcx.hir().name(node_id).as_interned_str())
1678 Def::SelfTy(_, Some(def_id)) => {
1679 // `Self` in impl (we know the concrete type).
1680 assert_eq!(opt_self_ty, None);
1681 self.prohibit_generics(&path.segments);
1682 tcx.at(span).type_of(def_id)
1684 Def::SelfTy(Some(_), None) => {
1686 assert_eq!(opt_self_ty, None);
1687 self.prohibit_generics(&path.segments);
1690 Def::AssociatedTy(def_id) => {
1691 debug_assert!(path.segments.len() >= 2);
1692 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1693 self.qpath_to_ty(span,
1696 &path.segments[path.segments.len() - 2],
1697 path.segments.last().unwrap())
1699 Def::PrimTy(prim_ty) => {
1700 assert_eq!(opt_self_ty, None);
1701 self.prohibit_generics(&path.segments);
1703 hir::Bool => tcx.types.bool,
1704 hir::Char => tcx.types.char,
1705 hir::Int(it) => tcx.mk_mach_int(it),
1706 hir::Uint(uit) => tcx.mk_mach_uint(uit),
1707 hir::Float(ft) => tcx.mk_mach_float(ft),
1708 hir::Str => tcx.mk_str()
1712 self.set_tainted_by_errors();
1713 return self.tcx().types.err;
1715 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1719 /// Parses the programmer's textual representation of a type into our
1720 /// internal notion of a type.
1721 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1722 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1723 ast_ty.id, ast_ty, ast_ty.node);
1725 let tcx = self.tcx();
1727 let result_ty = match ast_ty.node {
1728 hir::TyKind::Slice(ref ty) => {
1729 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1731 hir::TyKind::Ptr(ref mt) => {
1732 tcx.mk_ptr(ty::TypeAndMut {
1733 ty: self.ast_ty_to_ty(&mt.ty),
1737 hir::TyKind::Rptr(ref region, ref mt) => {
1738 let r = self.ast_region_to_region(region, None);
1739 debug!("Ref r={:?}", r);
1740 let t = self.ast_ty_to_ty(&mt.ty);
1741 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1743 hir::TyKind::Never => {
1746 hir::TyKind::Tup(ref fields) => {
1747 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1749 hir::TyKind::BareFn(ref bf) => {
1750 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1751 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1753 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1754 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1756 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1757 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1758 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1759 self.ast_ty_to_ty(qself)
1761 self.def_to_ty(opt_self_ty, path, false)
1763 hir::TyKind::Def(item_id, ref lifetimes) => {
1764 let did = tcx.hir().local_def_id(item_id.id);
1765 self.impl_trait_ty_to_ty(did, lifetimes)
1767 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1768 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1769 let ty = self.ast_ty_to_ty(qself);
1771 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1776 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1778 hir::TyKind::Array(ref ty, ref length) => {
1779 let length_def_id = tcx.hir().local_def_id(length.id);
1780 let substs = Substs::identity_for_item(tcx, length_def_id);
1781 let length = ty::LazyConst::Unevaluated(length_def_id, substs);
1782 let length = tcx.intern_lazy_const(length);
1783 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1784 self.normalize_ty(ast_ty.span, array_ty)
1786 hir::TyKind::Typeof(ref _e) => {
1787 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1788 "`typeof` is a reserved keyword but unimplemented")
1789 .span_label(ast_ty.span, "reserved keyword")
1794 hir::TyKind::Infer => {
1795 // Infer also appears as the type of arguments or return
1796 // values in a ExprKind::Closure, or as
1797 // the type of local variables. Both of these cases are
1798 // handled specially and will not descend into this routine.
1799 self.ty_infer(ast_ty.span)
1801 hir::TyKind::Err => {
1806 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1810 pub fn impl_trait_ty_to_ty(
1813 lifetimes: &[hir::GenericArg],
1815 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1816 let tcx = self.tcx();
1818 let generics = tcx.generics_of(def_id);
1820 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1821 let substs = Substs::for_item(tcx, def_id, |param, _| {
1822 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1823 // Our own parameters are the resolved lifetimes.
1825 GenericParamDefKind::Lifetime => {
1826 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1827 self.ast_region_to_region(lifetime, None).into()
1835 // Replace all parent lifetimes with 'static.
1837 GenericParamDefKind::Lifetime => {
1838 tcx.types.re_static.into()
1840 _ => tcx.mk_param_from_def(param)
1844 debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1846 let ty = tcx.mk_opaque(def_id, substs);
1847 debug!("impl_trait_ty_to_ty: {}", ty);
1851 pub fn ty_of_arg(&self,
1853 expected_ty: Option<Ty<'tcx>>)
1857 hir::TyKind::Infer if expected_ty.is_some() => {
1858 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1859 expected_ty.unwrap()
1861 _ => self.ast_ty_to_ty(ty),
1865 pub fn ty_of_fn(&self,
1866 unsafety: hir::Unsafety,
1869 -> ty::PolyFnSig<'tcx> {
1872 let tcx = self.tcx();
1874 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1876 let output_ty = match decl.output {
1877 hir::Return(ref output) => self.ast_ty_to_ty(output),
1878 hir::DefaultReturn(..) => tcx.mk_unit(),
1881 debug!("ty_of_fn: output_ty={:?}", output_ty);
1883 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1891 // Find any late-bound regions declared in return type that do
1892 // not appear in the arguments. These are not well-formed.
1895 // for<'a> fn() -> &'a str <-- 'a is bad
1896 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1897 let inputs = bare_fn_ty.inputs();
1898 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1899 &inputs.map_bound(|i| i.to_owned()));
1900 let output = bare_fn_ty.output();
1901 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1902 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1903 let lifetime_name = match *br {
1904 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1905 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1907 let mut err = struct_span_err!(tcx.sess,
1910 "return type references {} \
1911 which is not constrained by the fn input types",
1913 if let ty::BrAnon(_) = *br {
1914 // The only way for an anonymous lifetime to wind up
1915 // in the return type but **also** be unconstrained is
1916 // if it only appears in "associated types" in the
1917 // input. See #47511 for an example. In this case,
1918 // though we can easily give a hint that ought to be
1920 err.note("lifetimes appearing in an associated type \
1921 are not considered constrained");
1929 /// Given the bounds on an object, determines what single region bound (if any) we can
1930 /// use to summarize this type. The basic idea is that we will use the bound the user
1931 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1932 /// for region bounds. It may be that we can derive no bound at all, in which case
1933 /// we return `None`.
1934 fn compute_object_lifetime_bound(&self,
1936 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1937 -> Option<ty::Region<'tcx>> // if None, use the default
1939 let tcx = self.tcx();
1941 debug!("compute_opt_region_bound(existential_predicates={:?})",
1942 existential_predicates);
1944 // No explicit region bound specified. Therefore, examine trait
1945 // bounds and see if we can derive region bounds from those.
1946 let derived_region_bounds =
1947 object_region_bounds(tcx, existential_predicates);
1949 // If there are no derived region bounds, then report back that we
1950 // can find no region bound. The caller will use the default.
1951 if derived_region_bounds.is_empty() {
1955 // If any of the derived region bounds are 'static, that is always
1957 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1958 return Some(tcx.types.re_static);
1961 // Determine whether there is exactly one unique region in the set
1962 // of derived region bounds. If so, use that. Otherwise, report an
1964 let r = derived_region_bounds[0];
1965 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1966 span_err!(tcx.sess, span, E0227,
1967 "ambiguous lifetime bound, explicit lifetime bound required");
1973 /// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
1974 /// the remaining general trait bounds.
1975 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1976 trait_bounds: &'b [hir::PolyTraitRef])
1977 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1979 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1980 // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1981 match bound.trait_ref.path.def {
1982 Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
1989 let auto_traits = auto_traits.into_iter().map(|tr| {
1990 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1995 }).collect::<Vec<_>>();
1997 (auto_traits, trait_bounds)
2000 // A helper struct for conveniently grouping a set of bounds which we pass to
2001 // and return from functions in multiple places.
2002 #[derive(PartialEq, Eq, Clone, Debug)]
2003 pub struct Bounds<'tcx> {
2004 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2005 pub implicitly_sized: Option<Span>,
2006 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2007 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2010 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2011 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2012 -> Vec<(ty::Predicate<'tcx>, Span)>
2014 // If it could be sized, and is, add the sized predicate.
2015 let sized_predicate = self.implicitly_sized.and_then(|span| {
2016 tcx.lang_items().sized_trait().map(|sized| {
2017 let trait_ref = ty::TraitRef {
2019 substs: tcx.mk_substs_trait(param_ty, &[])
2021 (trait_ref.to_predicate(), span)
2025 sized_predicate.into_iter().chain(
2026 self.region_bounds.iter().map(|&(region_bound, span)| {
2027 // Account for the binder being introduced below; no need to shift `param_ty`
2028 // because, at present at least, it can only refer to early-bound regions.
2029 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2030 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2031 (ty::Binder::dummy(outlives).to_predicate(), span)
2033 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2034 (bound_trait_ref.to_predicate(), span)
2037 self.projection_bounds.iter().map(|&(projection, span)| {
2038 (projection.to_predicate(), span)