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};
7 use crate::hir::def::Def;
8 use crate::hir::def_id::DefId;
9 use crate::hir::HirVec;
11 use crate::middle::resolve_lifetime as rl;
12 use crate::namespace::Namespace;
13 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
15 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
16 use rustc::ty::{GenericParamDef, GenericParamDefKind};
17 use rustc::ty::subst::{Kind, Subst, Substs};
18 use rustc::ty::wf::object_region_bounds;
19 use rustc_data_structures::sync::Lrc;
20 use rustc_target::spec::abi;
21 use crate::require_c_abi_if_variadic;
22 use smallvec::SmallVec;
24 use syntax::feature_gate::{GateIssue, emit_feature_err};
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
28 use crate::util::common::ErrorReported;
29 use crate::util::nodemap::FxHashMap;
31 use std::collections::BTreeSet;
35 use super::{check_type_alias_enum_variants_enabled};
36 use rustc_data_structures::fx::FxHashSet;
39 pub struct PathSeg(pub DefId, pub usize);
41 pub trait AstConv<'gcx, 'tcx> {
42 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
44 /// Returns the set of bounds in scope for the type parameter with
46 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
47 -> Lrc<ty::GenericPredicates<'tcx>>;
49 /// What lifetime should we use when a lifetime is omitted (and not elided)?
50 fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
51 -> Option<ty::Region<'tcx>>;
53 /// What type should we use when a type is omitted?
54 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
56 /// Same as ty_infer, but with a known type parameter definition.
57 fn ty_infer_for_def(&self,
58 _def: &ty::GenericParamDef,
59 span: Span) -> Ty<'tcx> {
63 /// Projecting an associated type from a (potentially)
64 /// higher-ranked trait reference is more complicated, because of
65 /// the possibility of late-bound regions appearing in the
66 /// associated type binding. This is not legal in function
67 /// signatures for that reason. In a function body, we can always
68 /// handle it because we can use inference variables to remove the
69 /// late-bound regions.
70 fn projected_ty_from_poly_trait_ref(&self,
73 poly_trait_ref: ty::PolyTraitRef<'tcx>)
76 /// Normalize an associated type coming from the user.
77 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
79 /// Invoked when we encounter an error from some prior pass
80 /// (e.g., resolve) that is translated into a ty-error. This is
81 /// used to help suppress derived errors typeck might otherwise
83 fn set_tainted_by_errors(&self);
85 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
88 struct ConvertedBinding<'tcx> {
89 item_name: ast::Ident,
95 enum GenericArgPosition {
97 Value, // e.g., functions
101 /// Dummy type used for the `Self` of a `TraitRef` created for converting
102 /// a trait object, and which gets removed in `ExistentialTraitRef`.
103 /// This type must not appear anywhere in other converted types.
104 const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
106 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
107 pub fn ast_region_to_region(&self,
108 lifetime: &hir::Lifetime,
109 def: Option<&ty::GenericParamDef>)
112 let tcx = self.tcx();
113 let lifetime_name = |def_id| {
114 tcx.hir().name_by_hir_id(tcx.hir().as_local_hir_id(def_id).unwrap()).as_interned_str()
117 let r = match tcx.named_region(lifetime.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`.
199 tcx: TyCtxt<'_, '_, '_>,
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 /// Checks 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(
230 tcx: TyCtxt<'_, '_, '_>,
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 /// Checks 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(
262 tcx: TyCtxt<'_, '_, '_>,
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_hir(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 function. Let us try to explain the role
404 /// 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 `DefId` `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 `DefId`
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::Type(_), GenericParamDefKind::Lifetime)
504 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
505 // We expected a lifetime argument, but got a type or const
506 // argument. That means we're inferring the lifetimes.
507 substs.push(inferred_kind(None, param, infer_types));
511 // We expected one kind of parameter, but the user provided
512 // another. This is an error, but we need to handle it
513 // gracefully so we can report sensible errors.
514 // In this case, we're simply going to infer this argument.
520 // We should never be able to reach this point with well-formed input.
521 // Getting to this point means the user supplied more arguments than
522 // there are parameters.
525 (None, Some(¶m)) => {
526 // If there are fewer arguments than parameters, it means
527 // we're inferring the remaining arguments.
528 substs.push(inferred_kind(Some(&substs), param, infer_types));
532 (None, None) => break,
537 tcx.intern_substs(&substs)
540 /// Given the type/region arguments provided to some path (along with
541 /// an implicit `Self`, if this is a trait reference) returns the complete
542 /// set of substitutions. This may involve applying defaulted type parameters.
544 /// Note that the type listing given here is *exactly* what the user provided.
545 fn create_substs_for_ast_path(&self,
548 generic_args: &hir::GenericArgs,
550 self_ty: Option<Ty<'tcx>>)
551 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
553 // If the type is parameterized by this region, then replace this
554 // region with the current anon region binding (in other words,
555 // whatever & would get replaced with).
556 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
558 def_id, self_ty, generic_args);
560 let tcx = self.tcx();
561 let generic_params = tcx.generics_of(def_id);
563 // If a self-type was declared, one should be provided.
564 assert_eq!(generic_params.has_self, self_ty.is_some());
566 let has_self = generic_params.has_self;
567 let (_, potential_assoc_types) = Self::check_generic_arg_count(
572 GenericArgPosition::Type,
577 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
578 let default_needs_object_self = |param: &ty::GenericParamDef| {
579 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
580 if is_object && has_default {
581 if tcx.at(span).type_of(param.def_id).has_self_ty() {
582 // There is no suitable inference default for a type parameter
583 // that references self, in an object type.
592 let substs = Self::create_substs_for_generic_args(
598 // Provide the generic args, and whether types should be inferred.
599 |_| (Some(generic_args), infer_types),
600 // Provide substitutions for parameters for which (valid) arguments have been provided.
602 match (¶m.kind, arg) {
603 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
604 self.ast_region_to_region(<, Some(param)).into()
606 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
607 self.ast_ty_to_ty(&ty).into()
612 // Provide substitutions for parameters for which arguments are inferred.
613 |substs, param, infer_types| {
615 GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
616 GenericParamDefKind::Type { has_default, .. } => {
617 if !infer_types && has_default {
618 // No type parameter provided, but a default exists.
620 // If we are converting an object type, then the
621 // `Self` parameter is unknown. However, some of the
622 // other type parameters may reference `Self` in their
623 // defaults. This will lead to an ICE if we are not
625 if default_needs_object_self(param) {
626 struct_span_err!(tcx.sess, span, E0393,
627 "the type parameter `{}` must be explicitly \
631 format!("missing reference to `{}`", param.name))
632 .note(&format!("because of the default `Self` reference, \
633 type parameters must be specified on object \
638 // This is a default type parameter.
641 tcx.at(span).type_of(param.def_id)
642 .subst_spanned(tcx, substs.unwrap(), Some(span))
645 } else if infer_types {
646 // No type parameters were provided, we can infer all.
647 if !default_needs_object_self(param) {
648 self.ty_infer_for_def(param, span).into()
650 self.ty_infer(span).into()
653 // We've already errored above about the mismatch.
661 let assoc_bindings = generic_args.bindings.iter().map(|binding| {
663 item_name: binding.ident,
664 ty: self.ast_ty_to_ty(&binding.ty),
669 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
670 generic_params, self_ty, substs);
672 (substs, assoc_bindings, potential_assoc_types)
675 /// Instantiates the path for the given trait reference, assuming that it's
676 /// bound to a valid trait type. Returns the def_id for the defining trait.
677 /// The type _cannot_ be a type other than a trait type.
679 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
680 /// are disallowed. Otherwise, they are pushed onto the vector given.
681 pub fn instantiate_mono_trait_ref(&self,
682 trait_ref: &hir::TraitRef,
684 -> ty::TraitRef<'tcx>
686 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
688 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
689 trait_ref.trait_def_id(),
691 trait_ref.path.segments.last().unwrap())
694 /// The given trait-ref must actually be a trait.
695 pub(super) fn instantiate_poly_trait_ref_inner(&self,
696 trait_ref: &hir::TraitRef,
698 poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
700 -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
702 let trait_def_id = trait_ref.trait_def_id();
704 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
706 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
708 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
712 trait_ref.path.segments.last().unwrap(),
714 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
716 let mut dup_bindings = FxHashMap::default();
717 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
718 // specify type to assert that error was already reported in Err case:
719 let predicate: Result<_, ErrorReported> =
720 self.ast_type_binding_to_poly_projection_predicate(
721 trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
722 // okay to ignore Err because of ErrorReported (see above)
723 Some((predicate.ok()?, binding.span))
726 debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
727 trait_ref, poly_projections, poly_trait_ref);
728 (poly_trait_ref, potential_assoc_types)
731 pub fn instantiate_poly_trait_ref(&self,
732 poly_trait_ref: &hir::PolyTraitRef,
734 poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
735 -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
737 self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
738 poly_projections, false)
741 fn ast_path_to_mono_trait_ref(&self,
745 trait_segment: &hir::PathSegment)
746 -> ty::TraitRef<'tcx>
748 let (substs, assoc_bindings, _) =
749 self.create_substs_for_ast_trait_ref(span,
753 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
754 ty::TraitRef::new(trait_def_id, substs)
757 fn create_substs_for_ast_trait_ref(
762 trait_segment: &hir::PathSegment,
763 ) -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
764 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
767 let trait_def = self.tcx().trait_def(trait_def_id);
769 if !self.tcx().features().unboxed_closures &&
770 trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
771 != trait_def.paren_sugar {
772 // For now, require that parenthetical notation be used only with `Fn()` etc.
773 let msg = if trait_def.paren_sugar {
774 "the precise format of `Fn`-family traits' type parameters is subject to change. \
775 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
777 "parenthetical notation is only stable when used with `Fn`-family traits"
779 emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
780 span, GateIssue::Language, msg);
783 trait_segment.with_generic_args(|generic_args| {
784 self.create_substs_for_ast_path(span,
787 trait_segment.infer_types,
792 fn trait_defines_associated_type_named(&self,
794 assoc_name: ast::Ident)
797 self.tcx().associated_items(trait_def_id).any(|item| {
798 item.kind == ty::AssociatedKind::Type &&
799 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
803 fn ast_type_binding_to_poly_projection_predicate(
806 trait_ref: ty::PolyTraitRef<'tcx>,
807 binding: &ConvertedBinding<'tcx>,
809 dup_bindings: &mut FxHashMap<DefId, Span>)
810 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
812 let tcx = self.tcx();
815 // Given something like `U: SomeTrait<T = X>`, we want to produce a
816 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
817 // subtle in the event that `T` is defined in a supertrait of
818 // `SomeTrait`, because in that case we need to upcast.
820 // That is, consider this case:
823 // trait SubTrait: SuperTrait<int> { }
824 // trait SuperTrait<A> { type T; }
826 // ... B : SubTrait<T=foo> ...
829 // We want to produce `<B as SuperTrait<int>>::T == foo`.
831 // Find any late-bound regions declared in `ty` that are not
832 // declared in the trait-ref. These are not wellformed.
836 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
837 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
838 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
839 let late_bound_in_ty =
840 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
841 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
842 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
843 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
844 let br_name = match *br {
845 ty::BrNamed(_, name) => name,
849 "anonymous bound region {:?} in binding but not trait ref",
853 struct_span_err!(tcx.sess,
856 "binding for associated type `{}` references lifetime `{}`, \
857 which does not appear in the trait input types",
858 binding.item_name, br_name)
863 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
865 // Simple case: X is defined in the current trait.
868 // Otherwise, we have to walk through the supertraits to find
870 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
871 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
873 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
874 binding.item_name, binding.span)
877 let hir_ref_id = self.tcx().hir().node_to_hir_id(ref_id);
878 let (assoc_ident, def_scope) =
879 tcx.adjust_ident(binding.item_name, candidate.def_id(), hir_ref_id);
880 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
881 i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
882 }).expect("missing associated type");
884 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
885 let msg = format!("associated type `{}` is private", binding.item_name);
886 tcx.sess.span_err(binding.span, &msg);
888 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
891 dup_bindings.entry(assoc_ty.def_id)
892 .and_modify(|prev_span| {
893 struct_span_err!(self.tcx().sess, binding.span, E0719,
894 "the value of the associated type `{}` (from the trait `{}`) \
895 is already specified",
897 tcx.item_path_str(assoc_ty.container.id()))
898 .span_label(binding.span, "re-bound here")
899 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
902 .or_insert(binding.span);
905 Ok(candidate.map_bound(|trait_ref| {
906 ty::ProjectionPredicate {
907 projection_ty: ty::ProjectionTy::from_ref_and_name(
917 fn ast_path_to_ty(&self,
920 item_segment: &hir::PathSegment)
923 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
926 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
930 /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
931 /// removing the dummy `Self` type (`TRAIT_OBJECT_DUMMY_SELF`).
932 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
933 -> ty::ExistentialTraitRef<'tcx> {
934 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
935 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
938 fn conv_object_ty_poly_trait_ref(&self,
940 trait_bounds: &[hir::PolyTraitRef],
941 lifetime: &hir::Lifetime)
944 let tcx = self.tcx();
946 if trait_bounds.is_empty() {
947 span_err!(tcx.sess, span, E0224,
948 "at least one non-builtin trait is required for an object type");
949 return tcx.types.err;
952 let mut projection_bounds = Vec::new();
953 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
954 let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
957 &mut projection_bounds,
959 debug!("principal: {:?}", principal);
961 for trait_bound in trait_bounds[1..].iter() {
962 // sanity check for non-principal trait bounds
963 self.instantiate_poly_trait_ref(trait_bound,
968 let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
970 if !trait_bounds.is_empty() {
971 let b = &trait_bounds[0];
972 let span = b.trait_ref.path.span;
973 struct_span_err!(self.tcx().sess, span, E0225,
974 "only auto traits can be used as additional traits in a trait object")
975 .span_label(span, "non-auto additional trait")
979 // Check that there are no gross object safety violations;
980 // most importantly, that the supertraits don't contain `Self`,
982 let object_safety_violations =
983 tcx.global_tcx().astconv_object_safety_violations(principal.def_id());
984 if !object_safety_violations.is_empty() {
985 tcx.report_object_safety_error(
986 span, principal.def_id(), object_safety_violations)
988 return tcx.types.err;
991 // Use a `BTreeSet` to keep output in a more consistent order.
992 let mut associated_types = BTreeSet::default();
994 for tr in traits::elaborate_trait_ref(tcx, principal) {
995 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", tr);
997 ty::Predicate::Trait(pred) => {
998 associated_types.extend(tcx.associated_items(pred.def_id())
999 .filter(|item| item.kind == ty::AssociatedKind::Type)
1000 .map(|item| item.def_id));
1002 ty::Predicate::Projection(pred) => {
1003 // A `Self` within the original bound will be substituted with a
1004 // `TRAIT_OBJECT_DUMMY_SELF`, so check for that.
1005 let references_self =
1006 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1008 // If the projection output contains `Self`, force the user to
1009 // elaborate it explicitly to avoid a bunch of complexity.
1011 // The "classicaly useful" case is the following:
1013 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1018 // Here, the user could theoretically write `dyn MyTrait<Output=X>`,
1019 // but actually supporting that would "expand" to an infinitely-long type
1020 // `fix $ τ → dyn MyTrait<MyOutput=X, Output=<τ as MyTrait>::MyOutput`.
1022 // Instead, we force the user to write `dyn MyTrait<MyOutput=X, Output=X>`,
1023 // which is uglier but works. See the discussion in #56288 for alternatives.
1024 if !references_self {
1025 // Include projections defined on supertraits,
1026 projection_bounds.push((pred, DUMMY_SP))
1033 for (projection_bound, _) in &projection_bounds {
1034 associated_types.remove(&projection_bound.projection_def_id());
1037 if !associated_types.is_empty() {
1038 let names = associated_types.iter().map(|item_def_id| {
1039 let assoc_item = tcx.associated_item(*item_def_id);
1040 let trait_def_id = assoc_item.container.id();
1042 "`{}` (from the trait `{}`)",
1044 tcx.item_path_str(trait_def_id),
1046 }).collect::<Vec<_>>().join(", ");
1047 let mut err = struct_span_err!(
1051 "the value of the associated type{} {} must be specified",
1052 if associated_types.len() == 1 { "" } else { "s" },
1055 let mut suggest = false;
1056 let mut potential_assoc_types_spans = vec![];
1057 if let Some(potential_assoc_types) = potential_assoc_types {
1058 if potential_assoc_types.len() == associated_types.len() {
1059 // Only suggest when the amount of missing associated types is equals to the
1060 // extra type arguments present, as that gives us a relatively high confidence
1061 // that the user forgot to give the associtated type's name. The canonical
1062 // example would be trying to use `Iterator<isize>` instead of
1063 // `Iterator<Item=isize>`.
1065 potential_assoc_types_spans = potential_assoc_types;
1068 let mut suggestions = vec![];
1069 for (i, item_def_id) in associated_types.iter().enumerate() {
1070 let assoc_item = tcx.associated_item(*item_def_id);
1073 format!("associated type `{}` must be specified", assoc_item.ident),
1075 if item_def_id.is_local() {
1077 tcx.def_span(*item_def_id),
1078 format!("`{}` defined here", assoc_item.ident),
1082 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1083 potential_assoc_types_spans[i],
1086 potential_assoc_types_spans[i],
1087 format!("{} = {}", assoc_item.ident, snippet),
1092 if !suggestions.is_empty() {
1093 let msg = format!("if you meant to specify the associated {}, write",
1094 if suggestions.len() == 1 { "type" } else { "types" });
1095 err.multipart_suggestion(
1098 Applicability::MaybeIncorrect,
1104 // Erase the `dummy_self` (`TRAIT_OBJECT_DUMMY_SELF`) used above.
1105 let existential_principal = principal.map_bound(|trait_ref| {
1106 self.trait_ref_to_existential(trait_ref)
1108 let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1109 bound.map_bound(|b| {
1110 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1111 ty::ExistentialProjection {
1113 item_def_id: b.projection_ty.item_def_id,
1114 substs: trait_ref.substs,
1119 // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1121 auto_traits.dedup();
1123 // Calling `skip_binder` is okay, because the predicates are re-bound.
1124 let principal = if tcx.trait_is_auto(existential_principal.def_id()) {
1125 ty::ExistentialPredicate::AutoTrait(existential_principal.def_id())
1127 ty::ExistentialPredicate::Trait(*existential_principal.skip_binder())
1130 iter::once(principal)
1131 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1132 .chain(existential_projections
1133 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1134 .collect::<SmallVec<[_; 8]>>();
1135 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1137 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1139 // Use explicitly-specified region bound.
1140 let region_bound = if !lifetime.is_elided() {
1141 self.ast_region_to_region(lifetime, None)
1143 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1144 if tcx.named_region(lifetime.hir_id).is_some() {
1145 self.ast_region_to_region(lifetime, None)
1147 self.re_infer(span, None).unwrap_or_else(|| {
1148 span_err!(tcx.sess, span, E0228,
1149 "the lifetime bound for this object type cannot be deduced \
1150 from context; please supply an explicit bound");
1157 debug!("region_bound: {:?}", region_bound);
1159 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1160 debug!("trait_object_type: {:?}", ty);
1164 fn report_ambiguous_associated_type(&self,
1169 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1172 "use fully-qualified syntax",
1173 format!("<{} as {}>::{}", type_str, trait_str, name),
1174 Applicability::HasPlaceholders
1178 // Search for a bound on a type parameter which includes the associated item
1179 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1180 // This function will fail if there are no suitable bounds or there is
1182 fn find_bound_for_assoc_item(&self,
1183 ty_param_def_id: DefId,
1184 assoc_name: ast::Ident,
1186 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1188 let tcx = self.tcx();
1190 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1191 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1193 // Check that there is exactly one way to find an associated type with the
1195 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1196 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1198 let param_node_id = tcx.hir().as_local_node_id(ty_param_def_id).unwrap();
1199 let param_name = tcx.hir().ty_param_name(param_node_id);
1200 self.one_bound_for_assoc_type(suitable_bounds,
1201 ¶m_name.as_str(),
1206 // Checks that `bounds` contains exactly one element and reports appropriate
1207 // errors otherwise.
1208 fn one_bound_for_assoc_type<I>(&self,
1210 ty_param_name: &str,
1211 assoc_name: ast::Ident,
1213 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1214 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1216 let bound = match bounds.next() {
1217 Some(bound) => bound,
1219 struct_span_err!(self.tcx().sess, span, E0220,
1220 "associated type `{}` not found for `{}`",
1223 .span_label(span, format!("associated type `{}` not found", assoc_name))
1225 return Err(ErrorReported);
1229 if let Some(bound2) = bounds.next() {
1230 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1231 let mut err = struct_span_err!(
1232 self.tcx().sess, span, E0221,
1233 "ambiguous associated type `{}` in bounds of `{}`",
1236 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1238 for bound in bounds {
1239 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1240 item.kind == ty::AssociatedKind::Type &&
1241 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1243 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1245 if let Some(span) = bound_span {
1246 err.span_label(span, format!("ambiguous `{}` from `{}`",
1250 span_note!(&mut err, span,
1251 "associated type `{}` could derive from `{}`",
1262 // Create a type from a path to an associated type.
1263 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1264 // and item_segment is the path segment for `D`. We return a type and a def for
1266 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1267 // parameter or `Self`.
1268 pub fn associated_path_to_ty(
1270 hir_ref_id: hir::HirId,
1274 assoc_segment: &hir::PathSegment,
1275 permit_variants: bool,
1276 ) -> (Ty<'tcx>, Def) {
1277 let tcx = self.tcx();
1278 let assoc_ident = assoc_segment.ident;
1280 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1282 self.prohibit_generics(slice::from_ref(assoc_segment));
1284 // Check if we have an enum variant.
1285 let mut variant_resolution = None;
1286 if let ty::Adt(adt_def, _) = qself_ty.sty {
1287 if adt_def.is_enum() {
1288 let variant_def = adt_def.variants.iter().find(|vd| {
1289 tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1291 if let Some(variant_def) = variant_def {
1292 let def = Def::Variant(variant_def.did);
1293 if permit_variants {
1294 check_type_alias_enum_variants_enabled(tcx, span);
1295 tcx.check_stability(variant_def.did, Some(hir_ref_id), span);
1296 return (qself_ty, def);
1298 variant_resolution = Some(def);
1304 // Find the type of the associated item, and the trait where the associated
1305 // item is declared.
1306 let bound = match (&qself_ty.sty, qself_def) {
1307 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1308 // `Self` in an impl of a trait -- we have a concrete self type and a
1310 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1311 Some(trait_ref) => trait_ref,
1313 // A cycle error occurred, most likely.
1314 return (tcx.types.err, Def::Err);
1318 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1319 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1321 match self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span) {
1323 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1326 (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1327 (&ty::Param(_), Def::TyParam(param_did)) => {
1328 match self.find_bound_for_assoc_item(param_did, assoc_ident, span) {
1330 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1334 if variant_resolution.is_some() {
1335 // Variant in type position
1336 let msg = format!("expected type, found variant `{}`", assoc_ident);
1337 tcx.sess.span_err(span, &msg);
1338 } else if qself_ty.is_enum() {
1339 // Report as incorrect enum variant rather than ambiguous type.
1340 let mut err = tcx.sess.struct_span_err(
1342 &format!("no variant `{}` on enum `{}`", &assoc_ident.as_str(), qself_ty),
1344 // Check if it was a typo.
1345 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1346 if let Some(suggested_name) = find_best_match_for_name(
1347 adt_def.variants.iter().map(|variant| &variant.ident.name),
1348 &assoc_ident.as_str(),
1351 err.span_suggestion(
1354 format!("{}::{}", qself_ty, suggested_name),
1355 Applicability::MaybeIncorrect,
1358 err.span_label(span, "unknown variant");
1361 } else if !qself_ty.references_error() {
1362 // Don't print `TyErr` to the user.
1363 self.report_ambiguous_associated_type(span,
1364 &qself_ty.to_string(),
1366 &assoc_ident.as_str());
1368 return (tcx.types.err, Def::Err);
1372 let trait_did = bound.def_id();
1373 let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_ident, trait_did, hir_ref_id);
1374 let item = tcx.associated_items(trait_did).find(|i| {
1375 Namespace::from(i.kind) == Namespace::Type &&
1376 i.ident.modern() == assoc_ident
1377 }).expect("missing associated type");
1379 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1380 let ty = self.normalize_ty(span, ty);
1382 let def = Def::AssociatedTy(item.def_id);
1383 if !item.vis.is_accessible_from(def_scope, tcx) {
1384 let msg = format!("{} `{}` is private", def.kind_name(), assoc_ident);
1385 tcx.sess.span_err(span, &msg);
1387 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1389 if let Some(variant_def) = variant_resolution {
1390 let mut err = tcx.struct_span_lint_hir(
1391 AMBIGUOUS_ASSOCIATED_ITEMS,
1394 "ambiguous associated item",
1397 let mut could_refer_to = |def: Def, also| {
1398 let note_msg = format!("`{}` could{} refer to {} defined here",
1399 assoc_ident, also, def.kind_name());
1400 err.span_note(tcx.def_span(def.def_id()), ¬e_msg);
1402 could_refer_to(variant_def, "");
1403 could_refer_to(def, " also");
1405 err.span_suggestion(
1407 "use fully-qualified syntax",
1408 format!("<{} as {}>::{}", qself_ty, "Trait", assoc_ident),
1409 Applicability::HasPlaceholders,
1416 fn qpath_to_ty(&self,
1418 opt_self_ty: Option<Ty<'tcx>>,
1420 trait_segment: &hir::PathSegment,
1421 item_segment: &hir::PathSegment)
1424 let tcx = self.tcx();
1425 let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1427 self.prohibit_generics(slice::from_ref(item_segment));
1429 let self_ty = if let Some(ty) = opt_self_ty {
1432 let path_str = tcx.item_path_str(trait_def_id);
1433 self.report_ambiguous_associated_type(span,
1436 &item_segment.ident.as_str());
1437 return tcx.types.err;
1440 debug!("qpath_to_ty: self_type={:?}", self_ty);
1442 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1447 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1449 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1452 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1453 &self, segments: T) -> bool {
1454 let mut has_err = false;
1455 for segment in segments {
1456 segment.with_generic_args(|generic_args| {
1457 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1458 for arg in &generic_args.args {
1459 let (mut span_err, span, kind) = match arg {
1460 // FIXME(varkor): unify E0109, E0110 and E0111.
1461 hir::GenericArg::Lifetime(lt) => {
1462 if err_for_lt { continue }
1465 (struct_span_err!(self.tcx().sess, lt.span, E0110,
1466 "lifetime arguments are not allowed on this entity"),
1470 hir::GenericArg::Type(ty) => {
1471 if err_for_ty { continue }
1474 (struct_span_err!(self.tcx().sess, ty.span, E0109,
1475 "type arguments are not allowed on this entity"),
1479 hir::GenericArg::Const(ct) => {
1480 if err_for_ct { continue }
1482 (struct_span_err!(self.tcx().sess, ct.span, E0111,
1483 "const parameters are not allowed on this type"),
1488 span_err.span_label(span, format!("{} argument not allowed", kind))
1490 if err_for_lt && err_for_ty && err_for_ct {
1494 for binding in &generic_args.bindings {
1496 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1504 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_, '_, '_>, span: Span) {
1505 let mut err = struct_span_err!(tcx.sess, span, E0229,
1506 "associated type bindings are not allowed here");
1507 err.span_label(span, "associated type not allowed here").emit();
1510 pub fn def_ids_for_path_segments(&self,
1511 segments: &[hir::PathSegment],
1512 self_ty: Option<Ty<'tcx>>,
1515 // We need to extract the type parameters supplied by the user in
1516 // the path `path`. Due to the current setup, this is a bit of a
1517 // tricky-process; the problem is that resolve only tells us the
1518 // end-point of the path resolution, and not the intermediate steps.
1519 // Luckily, we can (at least for now) deduce the intermediate steps
1520 // just from the end-point.
1522 // There are basically five cases to consider:
1524 // 1. Reference to a constructor of a struct:
1526 // struct Foo<T>(...)
1528 // In this case, the parameters are declared in the type space.
1530 // 2. Reference to a constructor of an enum variant:
1532 // enum E<T> { Foo(...) }
1534 // In this case, the parameters are defined in the type space,
1535 // but may be specified either on the type or the variant.
1537 // 3. Reference to a fn item or a free constant:
1541 // In this case, the path will again always have the form
1542 // `a::b::foo::<T>` where only the final segment should have
1543 // type parameters. However, in this case, those parameters are
1544 // declared on a value, and hence are in the `FnSpace`.
1546 // 4. Reference to a method or an associated constant:
1548 // impl<A> SomeStruct<A> {
1552 // Here we can have a path like
1553 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1554 // may appear in two places. The penultimate segment,
1555 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1556 // final segment, `foo::<B>` contains parameters in fn space.
1558 // 5. Reference to a local variable
1560 // Local variables can't have any type parameters.
1562 // The first step then is to categorize the segments appropriately.
1564 let tcx = self.tcx();
1566 assert!(!segments.is_empty());
1567 let last = segments.len() - 1;
1569 let mut path_segs = vec![];
1572 // Case 1. Reference to a struct constructor.
1573 Def::StructCtor(def_id, ..) |
1574 Def::SelfCtor(.., def_id) => {
1575 // Everything but the final segment should have no
1576 // parameters at all.
1577 let generics = tcx.generics_of(def_id);
1578 // Variant and struct constructors use the
1579 // generics of their parent type definition.
1580 let generics_def_id = generics.parent.unwrap_or(def_id);
1581 path_segs.push(PathSeg(generics_def_id, last));
1584 // Case 2. Reference to a variant constructor.
1585 Def::Variant(def_id) |
1586 Def::VariantCtor(def_id, ..) => {
1587 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1588 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1589 debug_assert!(adt_def.is_enum());
1591 } else if last >= 1 && segments[last - 1].args.is_some() {
1592 // Everything but the penultimate segment should have no
1593 // parameters at all.
1594 let enum_def_id = tcx.parent_def_id(def_id).unwrap();
1595 (enum_def_id, last - 1)
1597 // FIXME: lint here recommending `Enum::<...>::Variant` form
1598 // instead of `Enum::Variant::<...>` form.
1600 // Everything but the final segment should have no
1601 // parameters at all.
1602 let generics = tcx.generics_of(def_id);
1603 // Variant and struct constructors use the
1604 // generics of their parent type definition.
1605 (generics.parent.unwrap_or(def_id), last)
1607 path_segs.push(PathSeg(generics_def_id, index));
1610 // Case 3. Reference to a top-level value.
1612 Def::Const(def_id) |
1613 Def::Static(def_id, _) => {
1614 path_segs.push(PathSeg(def_id, last));
1617 // Case 4. Reference to a method or associated const.
1618 Def::Method(def_id) |
1619 Def::AssociatedConst(def_id) => {
1620 if segments.len() >= 2 {
1621 let generics = tcx.generics_of(def_id);
1622 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1624 path_segs.push(PathSeg(def_id, last));
1627 // Case 5. Local variable, no generics.
1628 Def::Local(..) | Def::Upvar(..) => {}
1630 _ => bug!("unexpected definition: {:?}", def),
1633 debug!("path_segs = {:?}", path_segs);
1638 // Check a type `Path` and convert it to a `Ty`.
1639 pub fn def_to_ty(&self,
1640 opt_self_ty: Option<Ty<'tcx>>,
1642 permit_variants: bool)
1644 let tcx = self.tcx();
1646 debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1647 path.def, opt_self_ty, path.segments);
1649 let span = path.span;
1651 Def::Existential(did) => {
1652 // Check for desugared impl trait.
1653 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1654 let item_segment = path.segments.split_last().unwrap();
1655 self.prohibit_generics(item_segment.1);
1656 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1659 tcx.mk_opaque(did, substs),
1662 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1663 Def::Union(did) | Def::ForeignTy(did) => {
1664 assert_eq!(opt_self_ty, None);
1665 self.prohibit_generics(path.segments.split_last().unwrap().1);
1666 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1668 Def::Variant(_) if permit_variants => {
1669 // Convert "variant type" as if it were a real type.
1670 // The resulting `Ty` is type of the variant's enum for now.
1671 assert_eq!(opt_self_ty, None);
1673 let path_segs = self.def_ids_for_path_segments(&path.segments, None, path.def);
1674 let generic_segs: FxHashSet<_> =
1675 path_segs.iter().map(|PathSeg(_, index)| index).collect();
1676 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1677 if !generic_segs.contains(&index) {
1684 let PathSeg(def_id, index) = path_segs.last().unwrap();
1685 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1687 Def::TyParam(did) => {
1688 assert_eq!(opt_self_ty, None);
1689 self.prohibit_generics(&path.segments);
1691 let hir_id = tcx.hir().as_local_hir_id(did).unwrap();
1692 let item_id = tcx.hir().get_parent_node_by_hir_id(hir_id);
1693 let item_def_id = tcx.hir().local_def_id_from_hir_id(item_id);
1694 let generics = tcx.generics_of(item_def_id);
1695 let index = generics.param_def_id_to_index[
1696 &tcx.hir().local_def_id_from_hir_id(hir_id)];
1697 tcx.mk_ty_param(index, tcx.hir().name_by_hir_id(hir_id).as_interned_str())
1699 Def::SelfTy(_, Some(def_id)) => {
1700 // `Self` in impl (we know the concrete type).
1701 assert_eq!(opt_self_ty, None);
1702 self.prohibit_generics(&path.segments);
1703 tcx.at(span).type_of(def_id)
1705 Def::SelfTy(Some(_), None) => {
1707 assert_eq!(opt_self_ty, None);
1708 self.prohibit_generics(&path.segments);
1711 Def::AssociatedTy(def_id) => {
1712 debug_assert!(path.segments.len() >= 2);
1713 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1714 self.qpath_to_ty(span,
1717 &path.segments[path.segments.len() - 2],
1718 path.segments.last().unwrap())
1720 Def::PrimTy(prim_ty) => {
1721 assert_eq!(opt_self_ty, None);
1722 self.prohibit_generics(&path.segments);
1724 hir::Bool => tcx.types.bool,
1725 hir::Char => tcx.types.char,
1726 hir::Int(it) => tcx.mk_mach_int(it),
1727 hir::Uint(uit) => tcx.mk_mach_uint(uit),
1728 hir::Float(ft) => tcx.mk_mach_float(ft),
1729 hir::Str => tcx.mk_str()
1733 self.set_tainted_by_errors();
1734 return self.tcx().types.err;
1736 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1740 /// Parses the programmer's textual representation of a type into our
1741 /// internal notion of a type.
1742 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1743 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1744 ast_ty.hir_id, ast_ty, ast_ty.node);
1746 let tcx = self.tcx();
1748 let result_ty = match ast_ty.node {
1749 hir::TyKind::Slice(ref ty) => {
1750 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1752 hir::TyKind::Ptr(ref mt) => {
1753 tcx.mk_ptr(ty::TypeAndMut {
1754 ty: self.ast_ty_to_ty(&mt.ty),
1758 hir::TyKind::Rptr(ref region, ref mt) => {
1759 let r = self.ast_region_to_region(region, None);
1760 debug!("Ref r={:?}", r);
1761 let t = self.ast_ty_to_ty(&mt.ty);
1762 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1764 hir::TyKind::Never => {
1767 hir::TyKind::Tup(ref fields) => {
1768 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1770 hir::TyKind::BareFn(ref bf) => {
1771 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1772 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1774 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1775 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1777 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1778 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1779 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1780 self.ast_ty_to_ty(qself)
1782 self.def_to_ty(opt_self_ty, path, false)
1784 hir::TyKind::Def(item_id, ref lifetimes) => {
1785 let did = tcx.hir().local_def_id(item_id.id);
1786 self.impl_trait_ty_to_ty(did, lifetimes)
1788 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1789 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1790 let ty = self.ast_ty_to_ty(qself);
1792 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1797 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, def, segment, false).0
1799 hir::TyKind::Array(ref ty, ref length) => {
1800 let length_def_id = tcx.hir().local_def_id(length.id);
1801 let substs = Substs::identity_for_item(tcx, length_def_id);
1802 let length = ty::LazyConst::Unevaluated(length_def_id, substs);
1803 let length = tcx.mk_lazy_const(length);
1804 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1805 self.normalize_ty(ast_ty.span, array_ty)
1807 hir::TyKind::Typeof(ref _e) => {
1808 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1809 "`typeof` is a reserved keyword but unimplemented")
1810 .span_label(ast_ty.span, "reserved keyword")
1815 hir::TyKind::Infer => {
1816 // Infer also appears as the type of arguments or return
1817 // values in a ExprKind::Closure, or as
1818 // the type of local variables. Both of these cases are
1819 // handled specially and will not descend into this routine.
1820 self.ty_infer(ast_ty.span)
1822 hir::TyKind::Err => {
1827 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1831 pub fn impl_trait_ty_to_ty(
1834 lifetimes: &[hir::GenericArg],
1836 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1837 let tcx = self.tcx();
1839 let generics = tcx.generics_of(def_id);
1841 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1842 let substs = Substs::for_item(tcx, def_id, |param, _| {
1843 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1844 // Our own parameters are the resolved lifetimes.
1846 GenericParamDefKind::Lifetime => {
1847 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1848 self.ast_region_to_region(lifetime, None).into()
1856 // Replace all parent lifetimes with 'static.
1858 GenericParamDefKind::Lifetime => {
1859 tcx.types.re_static.into()
1861 _ => tcx.mk_param_from_def(param)
1865 debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1867 let ty = tcx.mk_opaque(def_id, substs);
1868 debug!("impl_trait_ty_to_ty: {}", ty);
1872 pub fn ty_of_arg(&self,
1874 expected_ty: Option<Ty<'tcx>>)
1878 hir::TyKind::Infer if expected_ty.is_some() => {
1879 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1880 expected_ty.unwrap()
1882 _ => self.ast_ty_to_ty(ty),
1886 pub fn ty_of_fn(&self,
1887 unsafety: hir::Unsafety,
1890 -> ty::PolyFnSig<'tcx> {
1893 let tcx = self.tcx();
1895 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1897 let output_ty = match decl.output {
1898 hir::Return(ref output) => self.ast_ty_to_ty(output),
1899 hir::DefaultReturn(..) => tcx.mk_unit(),
1902 debug!("ty_of_fn: output_ty={:?}", output_ty);
1904 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1912 // Find any late-bound regions declared in return type that do
1913 // not appear in the arguments. These are not well-formed.
1916 // for<'a> fn() -> &'a str <-- 'a is bad
1917 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1918 let inputs = bare_fn_ty.inputs();
1919 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1920 &inputs.map_bound(|i| i.to_owned()));
1921 let output = bare_fn_ty.output();
1922 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1923 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1924 let lifetime_name = match *br {
1925 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1926 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1928 let mut err = struct_span_err!(tcx.sess,
1931 "return type references {} \
1932 which is not constrained by the fn input types",
1934 if let ty::BrAnon(_) = *br {
1935 // The only way for an anonymous lifetime to wind up
1936 // in the return type but **also** be unconstrained is
1937 // if it only appears in "associated types" in the
1938 // input. See #47511 for an example. In this case,
1939 // though we can easily give a hint that ought to be
1941 err.note("lifetimes appearing in an associated type \
1942 are not considered constrained");
1950 /// Given the bounds on an object, determines what single region bound (if any) we can
1951 /// use to summarize this type. The basic idea is that we will use the bound the user
1952 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1953 /// for region bounds. It may be that we can derive no bound at all, in which case
1954 /// we return `None`.
1955 fn compute_object_lifetime_bound(&self,
1957 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1958 -> Option<ty::Region<'tcx>> // if None, use the default
1960 let tcx = self.tcx();
1962 debug!("compute_opt_region_bound(existential_predicates={:?})",
1963 existential_predicates);
1965 // No explicit region bound specified. Therefore, examine trait
1966 // bounds and see if we can derive region bounds from those.
1967 let derived_region_bounds =
1968 object_region_bounds(tcx, existential_predicates);
1970 // If there are no derived region bounds, then report back that we
1971 // can find no region bound. The caller will use the default.
1972 if derived_region_bounds.is_empty() {
1976 // If any of the derived region bounds are 'static, that is always
1978 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1979 return Some(tcx.types.re_static);
1982 // Determine whether there is exactly one unique region in the set
1983 // of derived region bounds. If so, use that. Otherwise, report an
1985 let r = derived_region_bounds[0];
1986 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1987 span_err!(tcx.sess, span, E0227,
1988 "ambiguous lifetime bound, explicit lifetime bound required");
1994 /// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
1995 /// the remaining general trait bounds.
1996 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1997 trait_bounds: &'b [hir::PolyTraitRef])
1998 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
2000 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
2001 // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
2002 match bound.trait_ref.path.def {
2003 Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
2010 let auto_traits = auto_traits.into_iter().map(|tr| {
2011 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
2016 }).collect::<Vec<_>>();
2018 (auto_traits, trait_bounds)
2021 // A helper struct for conveniently grouping a set of bounds which we pass to
2022 // and return from functions in multiple places.
2023 #[derive(PartialEq, Eq, Clone, Debug)]
2024 pub struct Bounds<'tcx> {
2025 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2026 pub implicitly_sized: Option<Span>,
2027 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2028 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2031 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2032 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2033 -> Vec<(ty::Predicate<'tcx>, Span)>
2035 // If it could be sized, and is, add the sized predicate.
2036 let sized_predicate = self.implicitly_sized.and_then(|span| {
2037 tcx.lang_items().sized_trait().map(|sized| {
2038 let trait_ref = ty::TraitRef {
2040 substs: tcx.mk_substs_trait(param_ty, &[])
2042 (trait_ref.to_predicate(), span)
2046 sized_predicate.into_iter().chain(
2047 self.region_bounds.iter().map(|&(region_bound, span)| {
2048 // Account for the binder being introduced below; no need to shift `param_ty`
2049 // because, at present at least, it can only refer to early-bound regions.
2050 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2051 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2052 (ty::Binder::dummy(outlives).to_predicate(), span)
2054 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2055 (bound_trait_ref.to_predicate(), span)
2058 self.projection_bounds.iter().map(|&(projection, span)| {
2059 (projection.to_predicate(), span)