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 crate::hir::def::{CtorOf, DefKind, Res};
6 use crate::hir::def_id::DefId;
8 use crate::hir::{self, ExprKind, GenericArg, GenericArgs};
10 use crate::middle::lang_items::SizedTraitLangItem;
11 use crate::middle::resolve_lifetime as rl;
12 use crate::namespace::Namespace;
13 use crate::require_c_abi_if_c_variadic;
14 use crate::util::common::ErrorReported;
15 use crate::util::nodemap::FxHashMap;
16 use errors::{Applicability, DiagnosticId};
17 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
19 use rustc::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
20 use rustc::ty::wf::object_region_bounds;
21 use rustc::ty::{self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
22 use rustc::ty::{GenericParamDef, GenericParamDefKind};
23 use rustc_target::spec::abi;
24 use smallvec::SmallVec;
26 use syntax::errors::pluralize;
27 use syntax::feature_gate::feature_err;
28 use syntax::symbol::sym;
29 use syntax::util::lev_distance::find_best_match_for_name;
30 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
32 use std::collections::BTreeSet;
36 use rustc_data_structures::fx::FxHashSet;
38 use rustc_error_codes::*;
41 pub struct PathSeg(pub DefId, pub usize);
43 pub trait AstConv<'tcx> {
44 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
46 fn item_def_id(&self) -> Option<DefId>;
48 /// Returns predicates in scope of the form `X: Foo`, where `X` is
49 /// a type parameter `X` with the given id `def_id`. This is a
50 /// subset of the full set of predicates.
52 /// This is used for one specific purpose: resolving "short-hand"
53 /// associated type references like `T::Item`. In principle, we
54 /// would do that by first getting the full set of predicates in
55 /// scope and then filtering down to find those that apply to `T`,
56 /// but this can lead to cycle errors. The problem is that we have
57 /// to do this resolution *in order to create the predicates in
58 /// the first place*. Hence, we have this "special pass".
59 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
61 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
62 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
63 -> Option<ty::Region<'tcx>>;
65 /// Returns the type to use when a type is omitted.
66 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
68 /// Returns the const to use when a const is omitted.
72 param: Option<&ty::GenericParamDef>,
74 ) -> &'tcx Const<'tcx>;
76 /// Projecting an associated type from a (potentially)
77 /// higher-ranked trait reference is more complicated, because of
78 /// the possibility of late-bound regions appearing in the
79 /// associated type binding. This is not legal in function
80 /// signatures for that reason. In a function body, we can always
81 /// handle it because we can use inference variables to remove the
82 /// late-bound regions.
83 fn projected_ty_from_poly_trait_ref(
87 item_segment: &hir::PathSegment<'_>,
88 poly_trait_ref: ty::PolyTraitRef<'tcx>,
91 /// Normalize an associated type coming from the user.
92 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
94 /// Invoked when we encounter an error from some prior pass
95 /// (e.g., resolve) that is translated into a ty-error. This is
96 /// used to help suppress derived errors typeck might otherwise
98 fn set_tainted_by_errors(&self);
100 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
103 pub enum SizedByDefault {
108 struct ConvertedBinding<'a, 'tcx> {
109 item_name: ast::Ident,
110 kind: ConvertedBindingKind<'a, 'tcx>,
114 enum ConvertedBindingKind<'a, 'tcx> {
116 Constraint(&'a [hir::GenericBound<'a>]),
120 enum GenericArgPosition {
122 Value, // e.g., functions
126 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
127 pub fn ast_region_to_region(
129 lifetime: &hir::Lifetime,
130 def: Option<&ty::GenericParamDef>,
131 ) -> ty::Region<'tcx> {
132 let tcx = self.tcx();
133 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap());
135 let r = match tcx.named_region(lifetime.hir_id) {
136 Some(rl::Region::Static) => tcx.lifetimes.re_static,
138 Some(rl::Region::LateBound(debruijn, id, _)) => {
139 let name = lifetime_name(id);
140 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
143 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
144 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
147 Some(rl::Region::EarlyBound(index, id, _)) => {
148 let name = lifetime_name(id);
149 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
152 Some(rl::Region::Free(scope, id)) => {
153 let name = lifetime_name(id);
154 tcx.mk_region(ty::ReFree(ty::FreeRegion {
156 bound_region: ty::BrNamed(id, name),
159 // (*) -- not late-bound, won't change
163 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
164 // This indicates an illegal lifetime
165 // elision. `resolve_lifetime` should have
166 // reported an error in this case -- but if
167 // not, let's error out.
168 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
170 // Supply some dummy value. We don't have an
171 // `re_error`, annoyingly, so use `'static`.
172 tcx.lifetimes.re_static
177 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
182 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
183 /// returns an appropriate set of substitutions for this particular reference to `I`.
184 pub fn ast_path_substs_for_ty(
188 item_segment: &hir::PathSegment<'_>,
189 ) -> SubstsRef<'tcx> {
190 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
194 item_segment.generic_args(),
195 item_segment.infer_args,
199 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
204 /// Report error if there is an explicit type parameter when using `impl Trait`.
207 seg: &hir::PathSegment<'_>,
208 generics: &ty::Generics,
210 let explicit = !seg.infer_args;
211 let impl_trait = generics.params.iter().any(|param| match param.kind {
212 ty::GenericParamDefKind::Type {
213 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
219 if explicit && impl_trait {
224 .filter_map(|arg| match arg {
225 GenericArg::Type(_) => Some(arg.span()),
228 .collect::<Vec<_>>();
230 let mut err = struct_span_err! {
234 "cannot provide explicit generic arguments when `impl Trait` is \
235 used in argument position"
239 err.span_label(span, "explicit generic argument not allowed");
248 /// Checks that the correct number of generic arguments have been provided.
249 /// Used specifically for function calls.
250 pub fn check_generic_arg_count_for_call(
254 seg: &hir::PathSegment<'_>,
255 is_method_call: bool,
257 let empty_args = hir::GenericArgs::none();
258 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
259 Self::check_generic_arg_count(
263 if let Some(ref args) = seg.args { args } else { &empty_args },
264 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
265 def.parent.is_none() && def.has_self, // `has_self`
266 seg.infer_args || suppress_mismatch, // `infer_args`
271 /// Checks that the correct number of generic arguments have been provided.
272 /// This is used both for datatypes and function calls.
273 fn check_generic_arg_count(
277 args: &hir::GenericArgs<'_>,
278 position: GenericArgPosition,
281 ) -> (bool, Option<Vec<Span>>) {
282 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
283 // that lifetimes will proceed types. So it suffices to check the number of each generic
284 // arguments in order to validate them with respect to the generic parameters.
285 let param_counts = def.own_counts();
286 let arg_counts = args.own_counts();
287 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
289 let mut defaults: ty::GenericParamCount = Default::default();
290 for param in &def.params {
292 GenericParamDefKind::Lifetime => {}
293 GenericParamDefKind::Type { has_default, .. } => {
294 defaults.types += has_default as usize
296 GenericParamDefKind::Const => {
297 // FIXME(const_generics:defaults)
302 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
303 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
306 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
307 let mut reported_late_bound_region_err = None;
308 if !infer_lifetimes {
309 if let Some(span_late) = def.has_late_bound_regions {
310 let msg = "cannot specify lifetime arguments explicitly \
311 if late bound lifetime parameters are present";
312 let note = "the late bound lifetime parameter is introduced here";
313 let span = args.args[0].span();
314 if position == GenericArgPosition::Value
315 && arg_counts.lifetimes != param_counts.lifetimes
317 let mut err = tcx.sess.struct_span_err(span, msg);
318 err.span_note(span_late, note);
320 reported_late_bound_region_err = Some(true);
322 let mut multispan = MultiSpan::from_span(span);
323 multispan.push_span_label(span_late, note.to_string());
325 lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
330 reported_late_bound_region_err = Some(false);
335 let check_kind_count = |kind, required, permitted, provided, offset| {
337 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
338 kind, required, permitted, provided, offset
340 // We enforce the following: `required` <= `provided` <= `permitted`.
341 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
342 // For other kinds (i.e., types), `permitted` may be greater than `required`.
343 if required <= provided && provided <= permitted {
344 return (reported_late_bound_region_err.unwrap_or(false), None);
347 // Unfortunately lifetime and type parameter mismatches are typically styled
348 // differently in diagnostics, which means we have a few cases to consider here.
349 let (bound, quantifier) = if required != permitted {
350 if provided < required {
351 (required, "at least ")
353 // provided > permitted
354 (permitted, "at most ")
360 let mut potential_assoc_types: Option<Vec<Span>> = None;
361 let (spans, label) = if required == permitted && provided > permitted {
362 // In the case when the user has provided too many arguments,
363 // we want to point to the unexpected arguments.
364 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
366 .map(|arg| arg.span())
368 potential_assoc_types = Some(spans.clone());
369 (spans, format!("unexpected {} argument", kind))
374 "expected {}{} {} argument{}",
383 let mut err = tcx.sess.struct_span_err_with_code(
386 "wrong number of {} arguments: expected {}{}, found {}",
387 kind, quantifier, bound, provided,
389 DiagnosticId::Error("E0107".into()),
392 err.span_label(span, label.as_str());
397 provided > required, // `suppress_error`
398 potential_assoc_types,
402 if reported_late_bound_region_err.is_none()
403 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
407 param_counts.lifetimes,
408 param_counts.lifetimes,
409 arg_counts.lifetimes,
413 // FIXME(const_generics:defaults)
414 if !infer_args || arg_counts.consts > param_counts.consts {
420 arg_counts.lifetimes + arg_counts.types,
423 // Note that type errors are currently be emitted *after* const errors.
424 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
428 param_counts.types - defaults.types - has_self as usize,
429 param_counts.types - has_self as usize,
431 arg_counts.lifetimes,
434 (reported_late_bound_region_err.unwrap_or(false), None)
438 /// Creates the relevant generic argument substitutions
439 /// corresponding to a set of generic parameters. This is a
440 /// rather complex function. Let us try to explain the role
441 /// of each of its parameters:
443 /// To start, we are given the `def_id` of the thing we are
444 /// creating the substitutions for, and a partial set of
445 /// substitutions `parent_substs`. In general, the substitutions
446 /// for an item begin with substitutions for all the "parents" of
447 /// that item -- e.g., for a method it might include the
448 /// parameters from the impl.
450 /// Therefore, the method begins by walking down these parents,
451 /// starting with the outermost parent and proceed inwards until
452 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
453 /// first to see if the parent's substitutions are listed in there. If so,
454 /// we can append those and move on. Otherwise, it invokes the
455 /// three callback functions:
457 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
458 /// generic arguments that were given to that parent from within
459 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
460 /// might refer to the trait `Foo`, and the arguments might be
461 /// `[T]`. The boolean value indicates whether to infer values
462 /// for arguments whose values were not explicitly provided.
463 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
464 /// instantiate a `GenericArg`.
465 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
466 /// creates a suitable inference variable.
467 pub fn create_substs_for_generic_args<'b>(
470 parent_substs: &[subst::GenericArg<'tcx>],
472 self_ty: Option<Ty<'tcx>>,
473 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
474 provided_kind: impl Fn(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
475 mut inferred_kind: impl FnMut(
476 Option<&[subst::GenericArg<'tcx>]>,
479 ) -> subst::GenericArg<'tcx>,
480 ) -> SubstsRef<'tcx> {
481 // Collect the segments of the path; we need to substitute arguments
482 // for parameters throughout the entire path (wherever there are
483 // generic parameters).
484 let mut parent_defs = tcx.generics_of(def_id);
485 let count = parent_defs.count();
486 let mut stack = vec![(def_id, parent_defs)];
487 while let Some(def_id) = parent_defs.parent {
488 parent_defs = tcx.generics_of(def_id);
489 stack.push((def_id, parent_defs));
492 // We manually build up the substitution, rather than using convenience
493 // methods in `subst.rs`, so that we can iterate over the arguments and
494 // parameters in lock-step linearly, instead of trying to match each pair.
495 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
497 // Iterate over each segment of the path.
498 while let Some((def_id, defs)) = stack.pop() {
499 let mut params = defs.params.iter().peekable();
501 // If we have already computed substitutions for parents, we can use those directly.
502 while let Some(¶m) = params.peek() {
503 if let Some(&kind) = parent_substs.get(param.index as usize) {
511 // `Self` is handled first, unless it's been handled in `parent_substs`.
513 if let Some(¶m) = params.peek() {
514 if param.index == 0 {
515 if let GenericParamDefKind::Type { .. } = param.kind {
519 .unwrap_or_else(|| inferred_kind(None, param, true)),
527 // Check whether this segment takes generic arguments and the user has provided any.
528 let (generic_args, infer_args) = args_for_def_id(def_id);
531 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
534 // We're going to iterate through the generic arguments that the user
535 // provided, matching them with the generic parameters we expect.
536 // Mismatches can occur as a result of elided lifetimes, or for malformed
537 // input. We try to handle both sensibly.
538 match (args.peek(), params.peek()) {
539 (Some(&arg), Some(¶m)) => {
540 match (arg, ¶m.kind) {
541 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
542 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
543 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
544 substs.push(provided_kind(param, arg));
548 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
549 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
550 // We expected a lifetime argument, but got a type or const
551 // argument. That means we're inferring the lifetimes.
552 substs.push(inferred_kind(None, param, infer_args));
556 // We expected one kind of parameter, but the user provided
557 // another. This is an error, but we need to handle it
558 // gracefully so we can report sensible errors.
559 // In this case, we're simply going to infer this argument.
565 // We should never be able to reach this point with well-formed input.
566 // Getting to this point means the user supplied more arguments than
567 // there are parameters.
570 (None, Some(¶m)) => {
571 // If there are fewer arguments than parameters, it means
572 // we're inferring the remaining arguments.
573 substs.push(inferred_kind(Some(&substs), param, infer_args));
577 (None, None) => break,
582 tcx.intern_substs(&substs)
585 /// Given the type/lifetime/const arguments provided to some path (along with
586 /// an implicit `Self`, if this is a trait reference), returns the complete
587 /// set of substitutions. This may involve applying defaulted type parameters.
588 /// Also returns back constriants on associated types.
593 /// T: std::ops::Index<usize, Output = u32>
594 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
597 /// 1. The `self_ty` here would refer to the type `T`.
598 /// 2. The path in question is the path to the trait `std::ops::Index`,
599 /// which will have been resolved to a `def_id`
600 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
601 /// parameters are returned in the `SubstsRef`, the associated type bindings like
602 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
604 /// Note that the type listing given here is *exactly* what the user provided.
606 /// For (generic) associated types
609 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
612 /// We have the parent substs are the substs for the parent trait:
613 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
614 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
615 /// lists: `[Vec<u8>, u8, 'a]`.
616 fn create_substs_for_ast_path<'a>(
620 parent_substs: &[subst::GenericArg<'tcx>],
621 generic_args: &'a hir::GenericArgs<'_>,
623 self_ty: Option<Ty<'tcx>>,
624 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
625 // If the type is parameterized by this region, then replace this
626 // region with the current anon region binding (in other words,
627 // whatever & would get replaced with).
629 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
631 def_id, self_ty, generic_args
634 let tcx = self.tcx();
635 let generic_params = tcx.generics_of(def_id);
637 if generic_params.has_self {
638 if generic_params.parent.is_some() {
639 // The parent is a trait so it should have at least one subst
640 // for the `Self` type.
641 assert!(!parent_substs.is_empty())
643 // This item (presumably a trait) needs a self-type.
644 assert!(self_ty.is_some());
647 assert!(self_ty.is_none() && parent_substs.is_empty());
650 let (_, potential_assoc_types) = Self::check_generic_arg_count(
655 GenericArgPosition::Type,
660 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
661 let default_needs_object_self = |param: &ty::GenericParamDef| {
662 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
663 if is_object && has_default {
664 let self_param = tcx.types.self_param;
665 if tcx.at(span).type_of(param.def_id).walk().any(|ty| ty == self_param) {
666 // There is no suitable inference default for a type parameter
667 // that references self, in an object type.
676 let mut missing_type_params = vec![];
677 let substs = Self::create_substs_for_generic_args(
683 // Provide the generic args, and whether types should be inferred.
684 |_| (Some(generic_args), infer_args),
685 // Provide substitutions for parameters for which (valid) arguments have been provided.
686 |param, arg| match (¶m.kind, arg) {
687 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
688 self.ast_region_to_region(<, Some(param)).into()
690 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
691 self.ast_ty_to_ty(&ty).into()
693 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
694 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
698 // Provide substitutions for parameters for which arguments are inferred.
699 |substs, param, infer_args| {
701 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
702 GenericParamDefKind::Type { has_default, .. } => {
703 if !infer_args && has_default {
704 // No type parameter provided, but a default exists.
706 // If we are converting an object type, then the
707 // `Self` parameter is unknown. However, some of the
708 // other type parameters may reference `Self` in their
709 // defaults. This will lead to an ICE if we are not
711 if default_needs_object_self(param) {
712 missing_type_params.push(param.name.to_string());
715 // This is a default type parameter.
718 tcx.at(span).type_of(param.def_id).subst_spanned(
726 } else if infer_args {
727 // No type parameters were provided, we can infer all.
729 if !default_needs_object_self(param) { Some(param) } else { None };
730 self.ty_infer(param, span).into()
732 // We've already errored above about the mismatch.
736 GenericParamDefKind::Const => {
737 // FIXME(const_generics:defaults)
739 // No const parameters were provided, we can infer all.
740 let ty = tcx.at(span).type_of(param.def_id);
741 self.ct_infer(ty, Some(param), span).into()
743 // We've already errored above about the mismatch.
744 tcx.consts.err.into()
751 self.complain_about_missing_type_params(
755 generic_args.args.is_empty(),
758 // Convert associated-type bindings or constraints into a separate vector.
759 // Example: Given this:
761 // T: Iterator<Item = u32>
763 // The `T` is passed in as a self-type; the `Item = u32` is
764 // not a "type parameter" of the `Iterator` trait, but rather
765 // a restriction on `<T as Iterator>::Item`, so it is passed
767 let assoc_bindings = generic_args
771 let kind = match binding.kind {
772 hir::TypeBindingKind::Equality { ref ty } => {
773 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
775 hir::TypeBindingKind::Constraint { ref bounds } => {
776 ConvertedBindingKind::Constraint(bounds)
779 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
784 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
785 generic_params, self_ty, substs
788 (substs, assoc_bindings, potential_assoc_types)
791 crate fn create_substs_for_associated_item(
796 item_segment: &hir::PathSegment<'_>,
797 parent_substs: SubstsRef<'tcx>,
798 ) -> SubstsRef<'tcx> {
799 if tcx.generics_of(item_def_id).params.is_empty() {
800 self.prohibit_generics(slice::from_ref(item_segment));
804 self.create_substs_for_ast_path(
808 item_segment.generic_args(),
809 item_segment.infer_args,
816 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
817 /// the type parameter's name as a placeholder.
818 fn complain_about_missing_type_params(
820 missing_type_params: Vec<String>,
823 empty_generic_args: bool,
825 if missing_type_params.is_empty() {
829 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
830 let mut err = struct_span_err!(
834 "the type parameter{} {} must be explicitly specified",
835 pluralize!(missing_type_params.len()),
839 self.tcx().def_span(def_id),
841 "type parameter{} {} must be specified for this",
842 pluralize!(missing_type_params.len()),
846 let mut suggested = false;
847 if let (Ok(snippet), true) = (
848 self.tcx().sess.source_map().span_to_snippet(span),
849 // Don't suggest setting the type params if there are some already: the order is
850 // tricky to get right and the user will already know what the syntax is.
853 if snippet.ends_with('>') {
854 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
855 // we would have to preserve the right order. For now, as clearly the user is
856 // aware of the syntax, we do nothing.
858 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
859 // least we can clue them to the correct syntax `Iterator<Type>`.
863 "set the type parameter{plural} to the desired type{plural}",
864 plural = pluralize!(missing_type_params.len()),
866 format!("{}<{}>", snippet, missing_type_params.join(", ")),
867 Applicability::HasPlaceholders,
876 "missing reference{} to {}",
877 pluralize!(missing_type_params.len()),
883 "because of the default `Self` reference, type parameters must be \
884 specified on object types"
889 /// Instantiates the path for the given trait reference, assuming that it's
890 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
891 /// The type _cannot_ be a type other than a trait type.
893 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
894 /// are disallowed. Otherwise, they are pushed onto the vector given.
895 pub fn instantiate_mono_trait_ref(
897 trait_ref: &hir::TraitRef<'_>,
899 ) -> ty::TraitRef<'tcx> {
900 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
902 self.ast_path_to_mono_trait_ref(
904 trait_ref.trait_def_id(),
906 trait_ref.path.segments.last().unwrap(),
910 /// The given trait-ref must actually be a trait.
911 pub(super) fn instantiate_poly_trait_ref_inner(
913 trait_ref: &hir::TraitRef<'_>,
916 bounds: &mut Bounds<'tcx>,
918 ) -> Option<Vec<Span>> {
919 let trait_def_id = trait_ref.trait_def_id();
921 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
923 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
925 let path_span = if let [segment] = &trait_ref.path.segments[..] {
926 // FIXME: `trait_ref.path.span` can point to a full path with multiple
927 // segments, even though `trait_ref.path.segments` is of length `1`. Work
928 // around that bug here, even though it should be fixed elsewhere.
929 // This would otherwise cause an invalid suggestion. For an example, look at
930 // `src/test/ui/issues/issue-28344.rs`.
935 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
939 trait_ref.path.segments.last().unwrap(),
941 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
943 bounds.trait_bounds.push((poly_trait_ref, span));
945 let mut dup_bindings = FxHashMap::default();
946 for binding in &assoc_bindings {
947 // Specify type to assert that error was already reported in `Err` case.
948 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
949 trait_ref.hir_ref_id,
957 // Okay to ignore `Err` because of `ErrorReported` (see above).
961 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
962 trait_ref, bounds, poly_trait_ref
964 potential_assoc_types
967 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
968 /// a full trait reference. The resulting trait reference is returned. This may also generate
969 /// auxiliary bounds, which are added to `bounds`.
974 /// poly_trait_ref = Iterator<Item = u32>
978 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
980 /// **A note on binders:** against our usual convention, there is an implied bounder around
981 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
982 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
983 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
984 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
986 pub fn instantiate_poly_trait_ref(
988 poly_trait_ref: &hir::PolyTraitRef<'_>,
990 bounds: &mut Bounds<'tcx>,
991 ) -> Option<Vec<Span>> {
992 self.instantiate_poly_trait_ref_inner(
993 &poly_trait_ref.trait_ref,
1001 fn ast_path_to_mono_trait_ref(
1004 trait_def_id: DefId,
1006 trait_segment: &hir::PathSegment<'_>,
1007 ) -> ty::TraitRef<'tcx> {
1008 let (substs, assoc_bindings, _) =
1009 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1010 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
1011 ty::TraitRef::new(trait_def_id, substs)
1014 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1015 /// an error and attempt to build a reasonable structured suggestion.
1016 fn complain_about_internal_fn_trait(
1019 trait_def_id: DefId,
1020 trait_segment: &'a hir::PathSegment<'a>,
1022 let trait_def = self.tcx().trait_def(trait_def_id);
1024 if !self.tcx().features().unboxed_closures
1025 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1027 // For now, require that parenthetical notation be used only with `Fn()` etc.
1028 let (msg, sugg) = if trait_def.paren_sugar {
1030 "the precise format of `Fn`-family traits' type parameters is subject to \
1034 trait_segment.ident,
1038 .and_then(|args| args.args.get(0))
1039 .and_then(|arg| match arg {
1040 hir::GenericArg::Type(ty) => {
1041 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1045 .unwrap_or_else(|| "()".to_string()),
1050 .filter_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1051 (true, hir::TypeBindingKind::Equality { ty }) => {
1052 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1057 .unwrap_or_else(|| "()".to_string()),
1061 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1063 let sess = &self.tcx().sess.parse_sess;
1064 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1065 if let Some(sugg) = sugg {
1066 let msg = "use parenthetical notation instead";
1067 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1073 fn create_substs_for_ast_trait_ref<'a>(
1076 trait_def_id: DefId,
1078 trait_segment: &'a hir::PathSegment<'a>,
1079 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
1080 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1082 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1084 self.create_substs_for_ast_path(
1088 trait_segment.generic_args(),
1089 trait_segment.infer_args,
1094 fn trait_defines_associated_type_named(
1096 trait_def_id: DefId,
1097 assoc_name: ast::Ident,
1099 self.tcx().associated_items(trait_def_id).any(|item| {
1100 item.kind == ty::AssocKind::Type
1101 && self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
1105 // Returns `true` if a bounds list includes `?Sized`.
1106 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1107 let tcx = self.tcx();
1109 // Try to find an unbound in bounds.
1110 let mut unbound = None;
1111 for ab in ast_bounds {
1112 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1113 if unbound.is_none() {
1114 unbound = Some(&ptr.trait_ref);
1120 "type parameter has more than one relaxed default \
1121 bound, only one is supported"
1127 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1130 // FIXME(#8559) currently requires the unbound to be built-in.
1131 if let Ok(kind_id) = kind_id {
1132 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1135 "default bound relaxed for a type parameter, but \
1136 this does nothing because the given bound is not \
1137 a default; only `?Sized` is supported",
1142 _ if kind_id.is_ok() => {
1145 // No lang item for `Sized`, so we can't add it as a bound.
1152 /// This helper takes a *converted* parameter type (`param_ty`)
1153 /// and an *unconverted* list of bounds:
1156 /// fn foo<T: Debug>
1157 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1159 /// `param_ty`, in ty form
1162 /// It adds these `ast_bounds` into the `bounds` structure.
1164 /// **A note on binders:** there is an implied binder around
1165 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1166 /// for more details.
1170 ast_bounds: &[hir::GenericBound<'_>],
1171 bounds: &mut Bounds<'tcx>,
1173 let mut trait_bounds = Vec::new();
1174 let mut region_bounds = Vec::new();
1176 for ast_bound in ast_bounds {
1178 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1179 trait_bounds.push(b)
1181 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1182 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1186 for bound in trait_bounds {
1187 let _ = self.instantiate_poly_trait_ref(bound, param_ty, bounds);
1190 bounds.region_bounds.extend(
1191 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1195 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1196 /// The self-type for the bounds is given by `param_ty`.
1201 /// fn foo<T: Bar + Baz>() { }
1202 /// ^ ^^^^^^^^^ ast_bounds
1206 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1207 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1208 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1210 /// `span` should be the declaration size of the parameter.
1211 pub fn compute_bounds(
1214 ast_bounds: &[hir::GenericBound<'_>],
1215 sized_by_default: SizedByDefault,
1218 let mut bounds = Bounds::default();
1220 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1221 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1223 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1224 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1232 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1235 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1236 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1237 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1238 fn add_predicates_for_ast_type_binding(
1240 hir_ref_id: hir::HirId,
1241 trait_ref: ty::PolyTraitRef<'tcx>,
1242 binding: &ConvertedBinding<'_, 'tcx>,
1243 bounds: &mut Bounds<'tcx>,
1245 dup_bindings: &mut FxHashMap<DefId, Span>,
1247 ) -> Result<(), ErrorReported> {
1248 let tcx = self.tcx();
1251 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1252 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1253 // subtle in the event that `T` is defined in a supertrait of
1254 // `SomeTrait`, because in that case we need to upcast.
1256 // That is, consider this case:
1259 // trait SubTrait: SuperTrait<int> { }
1260 // trait SuperTrait<A> { type T; }
1262 // ... B: SubTrait<T = foo> ...
1265 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1267 // Find any late-bound regions declared in `ty` that are not
1268 // declared in the trait-ref. These are not well-formed.
1272 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1273 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1274 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1275 let late_bound_in_trait_ref =
1276 tcx.collect_constrained_late_bound_regions(&trait_ref);
1277 let late_bound_in_ty =
1278 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1279 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1280 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1281 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1282 let br_name = match *br {
1283 ty::BrNamed(_, name) => name,
1287 "anonymous bound region {:?} in binding but not trait ref",
1296 "binding for associated type `{}` references lifetime `{}`, \
1297 which does not appear in the trait input types",
1307 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1308 // Simple case: X is defined in the current trait.
1311 // Otherwise, we have to walk through the supertraits to find
1313 self.one_bound_for_assoc_type(
1314 || traits::supertraits(tcx, trait_ref),
1315 &trait_ref.print_only_trait_path().to_string(),
1318 match binding.kind {
1319 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1325 let (assoc_ident, def_scope) =
1326 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1328 .associated_items(candidate.def_id())
1329 .find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident)
1330 .expect("missing associated type");
1332 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1333 let msg = format!("associated type `{}` is private", binding.item_name);
1334 tcx.sess.span_err(binding.span, &msg);
1336 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1340 .entry(assoc_ty.def_id)
1341 .and_modify(|prev_span| {
1346 "the value of the associated type `{}` (from trait `{}`) \
1347 is already specified",
1349 tcx.def_path_str(assoc_ty.container.id())
1351 .span_label(binding.span, "re-bound here")
1352 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1355 .or_insert(binding.span);
1358 match binding.kind {
1359 ConvertedBindingKind::Equality(ref ty) => {
1360 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1361 // the "projection predicate" for:
1363 // `<T as Iterator>::Item = u32`
1364 bounds.projection_bounds.push((
1365 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1366 projection_ty: ty::ProjectionTy::from_ref_and_name(
1376 ConvertedBindingKind::Constraint(ast_bounds) => {
1377 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1379 // `<T as Iterator>::Item: Debug`
1381 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1382 // parameter to have a skipped binder.
1383 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1384 self.add_bounds(param_ty, ast_bounds, bounds);
1394 item_segment: &hir::PathSegment<'_>,
1396 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1397 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1400 fn conv_object_ty_poly_trait_ref(
1403 trait_bounds: &[hir::PolyTraitRef<'_>],
1404 lifetime: &hir::Lifetime,
1406 let tcx = self.tcx();
1408 let mut bounds = Bounds::default();
1409 let mut potential_assoc_types = Vec::new();
1410 let dummy_self = self.tcx().types.trait_object_dummy_self;
1411 for trait_bound in trait_bounds.iter().rev() {
1412 let cur_potential_assoc_types =
1413 self.instantiate_poly_trait_ref(trait_bound, dummy_self, &mut bounds);
1414 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1417 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1418 // is used and no 'maybe' bounds are used.
1419 let expanded_traits =
1420 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1421 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1422 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1423 if regular_traits.len() > 1 {
1424 let first_trait = ®ular_traits[0];
1425 let additional_trait = ®ular_traits[1];
1426 let mut err = struct_span_err!(
1428 additional_trait.bottom().1,
1430 "only auto traits can be used as additional traits in a trait object"
1432 additional_trait.label_with_exp_info(
1434 "additional non-auto trait",
1437 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1441 if regular_traits.is_empty() && auto_traits.is_empty() {
1442 span_err!(tcx.sess, span, E0224, "at least one trait is required for an object type");
1443 return tcx.types.err;
1446 // Check that there are no gross object safety violations;
1447 // most importantly, that the supertraits don't contain `Self`,
1449 for item in ®ular_traits {
1450 let object_safety_violations =
1451 tcx.astconv_object_safety_violations(item.trait_ref().def_id());
1452 if !object_safety_violations.is_empty() {
1453 tcx.report_object_safety_error(
1455 item.trait_ref().def_id(),
1456 object_safety_violations,
1459 return tcx.types.err;
1463 // Use a `BTreeSet` to keep output in a more consistent order.
1464 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1466 let regular_traits_refs_spans = bounds
1469 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1471 for (base_trait_ref, span) in regular_traits_refs_spans {
1472 for trait_ref in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1474 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1478 ty::Predicate::Trait(pred) => {
1479 associated_types.entry(span).or_default().extend(
1480 tcx.associated_items(pred.def_id())
1481 .filter(|item| item.kind == ty::AssocKind::Type)
1482 .map(|item| item.def_id),
1485 ty::Predicate::Projection(pred) => {
1486 // A `Self` within the original bound will be substituted with a
1487 // `trait_object_dummy_self`, so check for that.
1488 let references_self = pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1490 // If the projection output contains `Self`, force the user to
1491 // elaborate it explicitly to avoid a lot of complexity.
1493 // The "classicaly useful" case is the following:
1495 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1500 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1501 // but actually supporting that would "expand" to an infinitely-long type
1502 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1504 // Instead, we force the user to write
1505 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1506 // the discussion in #56288 for alternatives.
1507 if !references_self {
1508 // Include projections defined on supertraits.
1509 bounds.projection_bounds.push((pred, span));
1517 for (projection_bound, _) in &bounds.projection_bounds {
1518 for (_, def_ids) in &mut associated_types {
1519 def_ids.remove(&projection_bound.projection_def_id());
1523 self.complain_about_missing_associated_types(
1525 potential_assoc_types,
1529 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1530 // `dyn Trait + Send`.
1531 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1532 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1533 debug!("regular_traits: {:?}", regular_traits);
1534 debug!("auto_traits: {:?}", auto_traits);
1536 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1537 // removing the dummy `Self` type (`trait_object_dummy_self`).
1538 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1539 if trait_ref.self_ty() != dummy_self {
1540 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1541 // which picks up non-supertraits where clauses - but also, the object safety
1542 // completely ignores trait aliases, which could be object safety hazards. We
1543 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1544 // disabled. (#66420)
1545 tcx.sess.delay_span_bug(
1548 "trait_ref_to_existential called on {:?} with non-dummy Self",
1553 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1556 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1557 let existential_trait_refs = regular_traits
1559 .map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
1560 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1561 bound.map_bound(|b| {
1562 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1563 ty::ExistentialProjection {
1565 item_def_id: b.projection_ty.item_def_id,
1566 substs: trait_ref.substs,
1571 // Calling `skip_binder` is okay because the predicates are re-bound.
1572 let regular_trait_predicates = existential_trait_refs
1573 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1574 let auto_trait_predicates = auto_traits
1576 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1577 let mut v = regular_trait_predicates
1578 .chain(auto_trait_predicates)
1580 existential_projections
1581 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1583 .collect::<SmallVec<[_; 8]>>();
1584 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1586 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1588 // Use explicitly-specified region bound.
1589 let region_bound = if !lifetime.is_elided() {
1590 self.ast_region_to_region(lifetime, None)
1592 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1593 if tcx.named_region(lifetime.hir_id).is_some() {
1594 self.ast_region_to_region(lifetime, None)
1596 self.re_infer(None, span).unwrap_or_else(|| {
1601 "the lifetime bound for this object type cannot be deduced \
1602 from context; please supply an explicit bound"
1604 tcx.lifetimes.re_static
1609 debug!("region_bound: {:?}", region_bound);
1611 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1612 debug!("trait_object_type: {:?}", ty);
1616 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1617 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1618 /// same trait bound have the same name (as they come from different super-traits), we instead
1619 /// emit a generic note suggesting using a `where` clause to constraint instead.
1620 fn complain_about_missing_associated_types(
1622 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1623 potential_assoc_types: Vec<Span>,
1624 trait_bounds: &[hir::PolyTraitRef<'_>],
1626 if !associated_types.values().any(|v| v.len() > 0) {
1629 let tcx = self.tcx();
1630 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1631 // appropriate one, but this should be handled earlier in the span assignment.
1632 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1634 .map(|(span, def_ids)| {
1635 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1638 let mut names = vec![];
1640 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1641 // `issue-22560.rs`.
1642 let mut trait_bound_spans: Vec<Span> = vec![];
1643 for (span, items) in &associated_types {
1644 if !items.is_empty() {
1645 trait_bound_spans.push(*span);
1647 for assoc_item in items {
1648 let trait_def_id = assoc_item.container.id();
1650 "`{}` (from trait `{}`)",
1652 tcx.def_path_str(trait_def_id),
1657 match (&potential_assoc_types[..], &trait_bounds) {
1658 ([], [bound]) => match &bound.trait_ref.path.segments[..] {
1659 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1660 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1661 // around that bug here, even though it should be fixed elsewhere.
1662 // This would otherwise cause an invalid suggestion. For an example, look at
1663 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1665 // error[E0191]: the value of the associated type `Output`
1666 // (from trait `std::ops::BitXor`) must be specified
1667 // --> $DIR/issue-28344.rs:4:17
1669 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1670 // | ^^^^^^ help: specify the associated type:
1671 // | `BitXor<Output = Type>`
1675 // error[E0191]: the value of the associated type `Output`
1676 // (from trait `std::ops::BitXor`) must be specified
1677 // --> $DIR/issue-28344.rs:4:17
1679 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1680 // | ^^^^^^^^^^^^^ help: specify the associated type:
1681 // | `BitXor::bitor<Output = Type>`
1682 [segment] if segment.args.is_none() => {
1683 trait_bound_spans = vec![segment.ident.span];
1684 associated_types = associated_types
1686 .map(|(_, items)| (segment.ident.span, items))
1694 trait_bound_spans.sort();
1695 let mut err = struct_span_err!(
1699 "the value of the associated type{} {} must be specified",
1700 pluralize!(names.len()),
1703 let mut suggestions = vec![];
1704 let mut types_count = 0;
1705 let mut where_constraints = vec![];
1706 for (span, assoc_items) in &associated_types {
1707 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1708 for item in assoc_items {
1710 *names.entry(item.ident.name).or_insert(0) += 1;
1712 let mut dupes = false;
1713 for item in assoc_items {
1714 let prefix = if names[&item.ident.name] > 1 {
1715 let trait_def_id = item.container.id();
1717 format!("{}::", tcx.def_path_str(trait_def_id))
1721 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1722 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1725 if potential_assoc_types.len() == assoc_items.len() {
1726 // Only suggest when the amount of missing associated types equals the number of
1727 // extra type arguments present, as that gives us a relatively high confidence
1728 // that the user forgot to give the associtated type's name. The canonical
1729 // example would be trying to use `Iterator<isize>` instead of
1730 // `Iterator<Item = isize>`.
1731 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1732 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1733 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1736 } else if let (Ok(snippet), false) =
1737 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1740 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1741 let code = if snippet.ends_with(">") {
1742 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1743 // suggest, but at least we can clue them to the correct syntax
1744 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1746 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1748 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1749 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1750 format!("{}<{}>", snippet, types.join(", "))
1752 suggestions.push((*span, code));
1754 where_constraints.push(*span);
1757 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1758 using the fully-qualified path to the associated types";
1759 if !where_constraints.is_empty() && suggestions.is_empty() {
1760 // If there are duplicates associated type names and a single trait bound do not
1761 // use structured suggestion, it means that there are multiple super-traits with
1762 // the same associated type name.
1763 err.help(where_msg);
1765 if suggestions.len() != 1 {
1766 // We don't need this label if there's an inline suggestion, show otherwise.
1767 for (span, assoc_items) in &associated_types {
1768 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1769 for item in assoc_items {
1771 *names.entry(item.ident.name).or_insert(0) += 1;
1773 let mut label = vec![];
1774 for item in assoc_items {
1775 let postfix = if names[&item.ident.name] > 1 {
1776 let trait_def_id = item.container.id();
1777 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1781 label.push(format!("`{}`{}", item.ident, postfix));
1783 if !label.is_empty() {
1787 "associated type{} {} must be specified",
1788 pluralize!(label.len()),
1795 if !suggestions.is_empty() {
1796 err.multipart_suggestion(
1797 &format!("specify the associated type{}", pluralize!(types_count)),
1799 Applicability::HasPlaceholders,
1801 if !where_constraints.is_empty() {
1802 err.span_help(where_constraints, where_msg);
1808 fn report_ambiguous_associated_type(
1815 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1816 if let (Some(_), Ok(snippet)) = (
1817 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1818 self.tcx().sess.source_map().span_to_snippet(span),
1820 err.span_suggestion(
1822 "you are looking for the module in `std`, not the primitive type",
1823 format!("std::{}", snippet),
1824 Applicability::MachineApplicable,
1827 err.span_suggestion(
1829 "use fully-qualified syntax",
1830 format!("<{} as {}>::{}", type_str, trait_str, name),
1831 Applicability::HasPlaceholders,
1837 // Search for a bound on a type parameter which includes the associated item
1838 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1839 // This function will fail if there are no suitable bounds or there is
1841 fn find_bound_for_assoc_item(
1843 ty_param_def_id: DefId,
1844 assoc_name: ast::Ident,
1846 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1847 let tcx = self.tcx();
1850 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1851 ty_param_def_id, assoc_name, span,
1854 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1856 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1858 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1859 let param_name = tcx.hir().ty_param_name(param_hir_id);
1860 self.one_bound_for_assoc_type(
1862 traits::transitive_bounds(
1864 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1867 ¶m_name.as_str(),
1874 // Checks that `bounds` contains exactly one element and reports appropriate
1875 // errors otherwise.
1876 fn one_bound_for_assoc_type<I>(
1878 all_candidates: impl Fn() -> I,
1879 ty_param_name: &str,
1880 assoc_name: ast::Ident,
1882 is_equality: Option<String>,
1883 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1885 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1887 let mut matching_candidates = all_candidates()
1888 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1890 let bound = match matching_candidates.next() {
1891 Some(bound) => bound,
1893 self.complain_about_assoc_type_not_found(
1899 return Err(ErrorReported);
1903 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1905 if let Some(bound2) = matching_candidates.next() {
1906 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1908 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
1909 let mut err = if is_equality.is_some() {
1910 // More specific Error Index entry.
1915 "ambiguous associated type `{}` in bounds of `{}`",
1924 "ambiguous associated type `{}` in bounds of `{}`",
1929 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1931 let mut where_bounds = vec![];
1932 for bound in bounds {
1933 let bound_span = self
1935 .associated_items(bound.def_id())
1937 item.kind == ty::AssocKind::Type
1938 && self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1940 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1942 if let Some(bound_span) = bound_span {
1946 "ambiguous `{}` from `{}`",
1948 bound.print_only_trait_path(),
1951 if let Some(constraint) = &is_equality {
1952 where_bounds.push(format!(
1953 " T: {trait}::{assoc} = {constraint}",
1954 trait=bound.print_only_trait_path(),
1956 constraint=constraint,
1959 err.span_suggestion(
1961 "use fully qualified syntax to disambiguate",
1965 bound.print_only_trait_path(),
1968 Applicability::MaybeIncorrect,
1973 "associated type `{}` could derive from `{}`",
1975 bound.print_only_trait_path(),
1979 if !where_bounds.is_empty() {
1981 "consider introducing a new type parameter `T` and adding `where` constraints:\
1982 \n where\n T: {},\n{}",
1984 where_bounds.join(",\n"),
1988 if !where_bounds.is_empty() {
1989 return Err(ErrorReported);
1995 fn complain_about_assoc_type_not_found<I>(
1997 all_candidates: impl Fn() -> I,
1998 ty_param_name: &str,
1999 assoc_name: ast::Ident,
2002 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2004 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2005 // valid span, so we point at the whole path segment instead.
2006 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2007 let mut err = struct_span_err!(
2011 "associated type `{}` not found for `{}`",
2016 let all_candidate_names: Vec<_> = all_candidates()
2017 .map(|r| self.tcx().associated_items(r.def_id()))
2020 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2024 if let (Some(suggested_name), true) = (
2025 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2026 assoc_name.span != DUMMY_SP,
2028 err.span_suggestion(
2030 "there is an associated type with a similar name",
2031 suggested_name.to_string(),
2032 Applicability::MaybeIncorrect,
2035 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2041 // Create a type from a path to an associated type.
2042 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2043 // and item_segment is the path segment for `D`. We return a type and a def for
2045 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2046 // parameter or `Self`.
2047 pub fn associated_path_to_ty(
2049 hir_ref_id: hir::HirId,
2053 assoc_segment: &hir::PathSegment<'_>,
2054 permit_variants: bool,
2055 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2056 let tcx = self.tcx();
2057 let assoc_ident = assoc_segment.ident;
2059 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2061 // Check if we have an enum variant.
2062 let mut variant_resolution = None;
2063 if let ty::Adt(adt_def, _) = qself_ty.kind {
2064 if adt_def.is_enum() {
2065 let variant_def = adt_def
2068 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2069 if let Some(variant_def) = variant_def {
2070 if permit_variants {
2071 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2072 self.prohibit_generics(slice::from_ref(assoc_segment));
2073 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2075 variant_resolution = Some(variant_def.def_id);
2081 // Find the type of the associated item, and the trait where the associated
2082 // item is declared.
2083 let bound = match (&qself_ty.kind, qself_res) {
2084 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2085 // `Self` in an impl of a trait -- we have a concrete self type and a
2087 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2088 Some(trait_ref) => trait_ref,
2090 // A cycle error occurred, most likely.
2091 return Err(ErrorReported);
2095 self.one_bound_for_assoc_type(
2096 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2103 (&ty::Param(_), Res::SelfTy(Some(param_did), None))
2104 | (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
2105 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
2108 if variant_resolution.is_some() {
2109 // Variant in type position
2110 let msg = format!("expected type, found variant `{}`", assoc_ident);
2111 tcx.sess.span_err(span, &msg);
2112 } else if qself_ty.is_enum() {
2113 let mut err = tcx.sess.struct_span_err(
2115 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
2118 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2119 if let Some(suggested_name) = find_best_match_for_name(
2120 adt_def.variants.iter().map(|variant| &variant.ident.name),
2121 &assoc_ident.as_str(),
2124 err.span_suggestion(
2126 "there is a variant with a similar name",
2127 suggested_name.to_string(),
2128 Applicability::MaybeIncorrect,
2133 format!("variant not found in `{}`", qself_ty),
2137 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2138 let sp = tcx.sess.source_map().def_span(sp);
2139 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2143 } else if !qself_ty.references_error() {
2144 // Don't print `TyErr` to the user.
2145 self.report_ambiguous_associated_type(
2147 &qself_ty.to_string(),
2152 return Err(ErrorReported);
2156 let trait_did = bound.def_id();
2157 let (assoc_ident, def_scope) =
2158 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2160 .associated_items(trait_did)
2161 .find(|i| Namespace::from(i.kind) == Namespace::Type && i.ident.modern() == assoc_ident)
2162 .expect("missing associated type");
2164 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2165 let ty = self.normalize_ty(span, ty);
2167 let kind = DefKind::AssocTy;
2168 if !item.vis.is_accessible_from(def_scope, tcx) {
2169 let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
2170 tcx.sess.span_err(span, &msg);
2172 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2174 if let Some(variant_def_id) = variant_resolution {
2175 let mut err = tcx.struct_span_lint_hir(
2176 AMBIGUOUS_ASSOCIATED_ITEMS,
2179 "ambiguous associated item",
2182 let mut could_refer_to = |kind: DefKind, def_id, also| {
2183 let note_msg = format!(
2184 "`{}` could{} refer to {} defined here",
2189 err.span_note(tcx.def_span(def_id), ¬e_msg);
2191 could_refer_to(DefKind::Variant, variant_def_id, "");
2192 could_refer_to(kind, item.def_id, " also");
2194 err.span_suggestion(
2196 "use fully-qualified syntax",
2197 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2198 Applicability::MachineApplicable,
2203 Ok((ty, kind, item.def_id))
2209 opt_self_ty: Option<Ty<'tcx>>,
2211 trait_segment: &hir::PathSegment<'_>,
2212 item_segment: &hir::PathSegment<'_>,
2214 let tcx = self.tcx();
2216 let trait_def_id = tcx.parent(item_def_id).unwrap();
2218 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2220 let self_ty = if let Some(ty) = opt_self_ty {
2223 let path_str = tcx.def_path_str(trait_def_id);
2225 let def_id = self.item_def_id();
2227 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2229 let parent_def_id = def_id
2230 .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
2231 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
2233 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2235 // If the trait in segment is the same as the trait defining the item,
2236 // use the `<Self as ..>` syntax in the error.
2237 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2238 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2240 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2246 self.report_ambiguous_associated_type(
2250 item_segment.ident.name,
2252 return tcx.types.err;
2255 debug!("qpath_to_ty: self_type={:?}", self_ty);
2257 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2259 let item_substs = self.create_substs_for_associated_item(
2267 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2269 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2272 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2276 let mut has_err = false;
2277 for segment in segments {
2278 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2279 for arg in segment.generic_args().args {
2280 let (span, kind) = match arg {
2281 hir::GenericArg::Lifetime(lt) => {
2287 (lt.span, "lifetime")
2289 hir::GenericArg::Type(ty) => {
2297 hir::GenericArg::Const(ct) => {
2305 let mut err = struct_span_err!(
2309 "{} arguments are not allowed for this type",
2312 err.span_label(span, format!("{} argument not allowed", kind));
2314 if err_for_lt && err_for_ty && err_for_ct {
2318 for binding in segment.generic_args().bindings {
2320 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2327 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2328 let mut err = struct_span_err!(
2332 "associated type bindings are not allowed here"
2334 err.span_label(span, "associated type not allowed here").emit();
2337 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2338 pub fn def_ids_for_value_path_segments(
2340 segments: &[hir::PathSegment<'_>],
2341 self_ty: Option<Ty<'tcx>>,
2345 // We need to extract the type parameters supplied by the user in
2346 // the path `path`. Due to the current setup, this is a bit of a
2347 // tricky-process; the problem is that resolve only tells us the
2348 // end-point of the path resolution, and not the intermediate steps.
2349 // Luckily, we can (at least for now) deduce the intermediate steps
2350 // just from the end-point.
2352 // There are basically five cases to consider:
2354 // 1. Reference to a constructor of a struct:
2356 // struct Foo<T>(...)
2358 // In this case, the parameters are declared in the type space.
2360 // 2. Reference to a constructor of an enum variant:
2362 // enum E<T> { Foo(...) }
2364 // In this case, the parameters are defined in the type space,
2365 // but may be specified either on the type or the variant.
2367 // 3. Reference to a fn item or a free constant:
2371 // In this case, the path will again always have the form
2372 // `a::b::foo::<T>` where only the final segment should have
2373 // type parameters. However, in this case, those parameters are
2374 // declared on a value, and hence are in the `FnSpace`.
2376 // 4. Reference to a method or an associated constant:
2378 // impl<A> SomeStruct<A> {
2382 // Here we can have a path like
2383 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2384 // may appear in two places. The penultimate segment,
2385 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2386 // final segment, `foo::<B>` contains parameters in fn space.
2388 // The first step then is to categorize the segments appropriately.
2390 let tcx = self.tcx();
2392 assert!(!segments.is_empty());
2393 let last = segments.len() - 1;
2395 let mut path_segs = vec![];
2398 // Case 1. Reference to a struct constructor.
2399 DefKind::Ctor(CtorOf::Struct, ..) => {
2400 // Everything but the final segment should have no
2401 // parameters at all.
2402 let generics = tcx.generics_of(def_id);
2403 // Variant and struct constructors use the
2404 // generics of their parent type definition.
2405 let generics_def_id = generics.parent.unwrap_or(def_id);
2406 path_segs.push(PathSeg(generics_def_id, last));
2409 // Case 2. Reference to a variant constructor.
2410 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2411 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2412 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2413 debug_assert!(adt_def.is_enum());
2415 } else if last >= 1 && segments[last - 1].args.is_some() {
2416 // Everything but the penultimate segment should have no
2417 // parameters at all.
2418 let mut def_id = def_id;
2420 // `DefKind::Ctor` -> `DefKind::Variant`
2421 if let DefKind::Ctor(..) = kind {
2422 def_id = tcx.parent(def_id).unwrap()
2425 // `DefKind::Variant` -> `DefKind::Enum`
2426 let enum_def_id = tcx.parent(def_id).unwrap();
2427 (enum_def_id, last - 1)
2429 // FIXME: lint here recommending `Enum::<...>::Variant` form
2430 // instead of `Enum::Variant::<...>` form.
2432 // Everything but the final segment should have no
2433 // parameters at all.
2434 let generics = tcx.generics_of(def_id);
2435 // Variant and struct constructors use the
2436 // generics of their parent type definition.
2437 (generics.parent.unwrap_or(def_id), last)
2439 path_segs.push(PathSeg(generics_def_id, index));
2442 // Case 3. Reference to a top-level value.
2443 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2444 path_segs.push(PathSeg(def_id, last));
2447 // Case 4. Reference to a method or associated const.
2448 DefKind::Method | DefKind::AssocConst => {
2449 if segments.len() >= 2 {
2450 let generics = tcx.generics_of(def_id);
2451 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2453 path_segs.push(PathSeg(def_id, last));
2456 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2459 debug!("path_segs = {:?}", path_segs);
2464 // Check a type `Path` and convert it to a `Ty`.
2467 opt_self_ty: Option<Ty<'tcx>>,
2468 path: &hir::Path<'_>,
2469 permit_variants: bool,
2471 let tcx = self.tcx();
2474 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2475 path.res, opt_self_ty, path.segments
2478 let span = path.span;
2480 Res::Def(DefKind::OpaqueTy, did) => {
2481 // Check for desugared `impl Trait`.
2482 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2483 let item_segment = path.segments.split_last().unwrap();
2484 self.prohibit_generics(item_segment.1);
2485 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2486 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2488 Res::Def(DefKind::Enum, did)
2489 | Res::Def(DefKind::TyAlias, did)
2490 | Res::Def(DefKind::Struct, did)
2491 | Res::Def(DefKind::Union, did)
2492 | Res::Def(DefKind::ForeignTy, did) => {
2493 assert_eq!(opt_self_ty, None);
2494 self.prohibit_generics(path.segments.split_last().unwrap().1);
2495 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2497 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2498 // Convert "variant type" as if it were a real type.
2499 // The resulting `Ty` is type of the variant's enum for now.
2500 assert_eq!(opt_self_ty, None);
2503 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2504 let generic_segs: FxHashSet<_> =
2505 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2506 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2508 if !generic_segs.contains(&index) { Some(seg) } else { None }
2512 let PathSeg(def_id, index) = path_segs.last().unwrap();
2513 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2515 Res::Def(DefKind::TyParam, def_id) => {
2516 assert_eq!(opt_self_ty, None);
2517 self.prohibit_generics(path.segments);
2519 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2520 let item_id = tcx.hir().get_parent_node(hir_id);
2521 let item_def_id = tcx.hir().local_def_id(item_id);
2522 let generics = tcx.generics_of(item_def_id);
2523 let index = generics.param_def_id_to_index[&def_id];
2524 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2526 Res::SelfTy(Some(_), None) => {
2527 // `Self` in trait or type alias.
2528 assert_eq!(opt_self_ty, None);
2529 self.prohibit_generics(path.segments);
2530 tcx.types.self_param
2532 Res::SelfTy(_, Some(def_id)) => {
2533 // `Self` in impl (we know the concrete type).
2534 assert_eq!(opt_self_ty, None);
2535 self.prohibit_generics(path.segments);
2536 // Try to evaluate any array length constants.
2537 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2539 Res::Def(DefKind::AssocTy, def_id) => {
2540 debug_assert!(path.segments.len() >= 2);
2541 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2546 &path.segments[path.segments.len() - 2],
2547 path.segments.last().unwrap(),
2550 Res::PrimTy(prim_ty) => {
2551 assert_eq!(opt_self_ty, None);
2552 self.prohibit_generics(path.segments);
2554 hir::Bool => tcx.types.bool,
2555 hir::Char => tcx.types.char,
2556 hir::Int(it) => tcx.mk_mach_int(it),
2557 hir::Uint(uit) => tcx.mk_mach_uint(uit),
2558 hir::Float(ft) => tcx.mk_mach_float(ft),
2559 hir::Str => tcx.mk_str(),
2563 self.set_tainted_by_errors();
2564 return self.tcx().types.err;
2566 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2570 /// Parses the programmer's textual representation of a type into our
2571 /// internal notion of a type.
2572 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2573 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2575 let tcx = self.tcx();
2577 let result_ty = match ast_ty.kind {
2578 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2579 hir::TyKind::Ptr(ref mt) => {
2580 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2582 hir::TyKind::Rptr(ref region, ref mt) => {
2583 let r = self.ast_region_to_region(region, None);
2584 debug!("ast_ty_to_ty: r={:?}", r);
2585 let t = self.ast_ty_to_ty(&mt.ty);
2586 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2588 hir::TyKind::Never => tcx.types.never,
2589 hir::TyKind::Tup(ref fields) => {
2590 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2592 hir::TyKind::BareFn(ref bf) => {
2593 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2594 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
2596 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2597 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2599 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2600 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2601 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2602 self.res_to_ty(opt_self_ty, path, false)
2604 hir::TyKind::Def(item_id, ref lifetimes) => {
2605 let did = tcx.hir().local_def_id(item_id.id);
2606 self.impl_trait_ty_to_ty(did, lifetimes)
2608 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2609 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2610 let ty = self.ast_ty_to_ty(qself);
2612 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2617 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2618 .map(|(ty, _, _)| ty)
2619 .unwrap_or(tcx.types.err)
2621 hir::TyKind::Array(ref ty, ref length) => {
2622 let length = self.ast_const_to_const(length, tcx.types.usize);
2623 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2624 self.normalize_ty(ast_ty.span, array_ty)
2626 hir::TyKind::Typeof(ref _e) => {
2631 "`typeof` is a reserved keyword but unimplemented"
2633 .span_label(ast_ty.span, "reserved keyword")
2638 hir::TyKind::Infer => {
2639 // Infer also appears as the type of arguments or return
2640 // values in a ExprKind::Closure, or as
2641 // the type of local variables. Both of these cases are
2642 // handled specially and will not descend into this routine.
2643 self.ty_infer(None, ast_ty.span)
2645 hir::TyKind::Err => tcx.types.err,
2648 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2650 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2654 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2655 pub fn const_param_def_id(&self, expr: &hir::Expr<'_>) -> Option<DefId> {
2656 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2657 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2658 let expr = match &expr.kind {
2659 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2660 block.expr.as_ref().unwrap()
2666 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2667 Res::Def(DefKind::ConstParam, did) => Some(did),
2674 pub fn ast_const_to_const(
2676 ast_const: &hir::AnonConst,
2678 ) -> &'tcx ty::Const<'tcx> {
2679 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2681 let tcx = self.tcx();
2682 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2684 let mut const_ = ty::Const {
2685 val: ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id)),
2689 let expr = &tcx.hir().body(ast_const.body).value;
2690 if let Some(def_id) = self.const_param_def_id(expr) {
2691 // Find the name and index of the const parameter by indexing the generics of the
2692 // parent item and construct a `ParamConst`.
2693 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2694 let item_id = tcx.hir().get_parent_node(hir_id);
2695 let item_def_id = tcx.hir().local_def_id(item_id);
2696 let generics = tcx.generics_of(item_def_id);
2697 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2698 let name = tcx.hir().name(hir_id);
2699 const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2702 tcx.mk_const(const_)
2705 pub fn impl_trait_ty_to_ty(
2708 lifetimes: &[hir::GenericArg<'_>],
2710 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2711 let tcx = self.tcx();
2713 let generics = tcx.generics_of(def_id);
2715 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2716 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2717 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2718 // Our own parameters are the resolved lifetimes.
2720 GenericParamDefKind::Lifetime => {
2721 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2722 self.ast_region_to_region(lifetime, None).into()
2730 // Replace all parent lifetimes with `'static`.
2732 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2733 _ => tcx.mk_param_from_def(param),
2737 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2739 let ty = tcx.mk_opaque(def_id, substs);
2740 debug!("impl_trait_ty_to_ty: {}", ty);
2744 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2746 hir::TyKind::Infer if expected_ty.is_some() => {
2747 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2748 expected_ty.unwrap()
2750 _ => self.ast_ty_to_ty(ty),
2756 unsafety: hir::Unsafety,
2758 decl: &hir::FnDecl<'_>,
2759 ) -> ty::PolyFnSig<'tcx> {
2762 let tcx = self.tcx();
2763 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2765 let output_ty = match decl.output {
2766 hir::Return(ref output) => self.ast_ty_to_ty(output),
2767 hir::DefaultReturn(..) => tcx.mk_unit(),
2770 debug!("ty_of_fn: output_ty={:?}", output_ty);
2773 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2775 // Find any late-bound regions declared in return type that do
2776 // not appear in the arguments. These are not well-formed.
2779 // for<'a> fn() -> &'a str <-- 'a is bad
2780 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2781 let inputs = bare_fn_ty.inputs();
2782 let late_bound_in_args =
2783 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2784 let output = bare_fn_ty.output();
2785 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2786 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2787 let lifetime_name = match *br {
2788 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2789 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2791 let mut err = struct_span_err!(
2795 "return type references {} \
2796 which is not constrained by the fn input types",
2799 if let ty::BrAnon(_) = *br {
2800 // The only way for an anonymous lifetime to wind up
2801 // in the return type but **also** be unconstrained is
2802 // if it only appears in "associated types" in the
2803 // input. See #47511 for an example. In this case,
2804 // though we can easily give a hint that ought to be
2807 "lifetimes appearing in an associated type \
2808 are not considered constrained",
2817 /// Given the bounds on an object, determines what single region bound (if any) we can
2818 /// use to summarize this type. The basic idea is that we will use the bound the user
2819 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2820 /// for region bounds. It may be that we can derive no bound at all, in which case
2821 /// we return `None`.
2822 fn compute_object_lifetime_bound(
2825 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2826 ) -> Option<ty::Region<'tcx>> // if None, use the default
2828 let tcx = self.tcx();
2830 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2832 // No explicit region bound specified. Therefore, examine trait
2833 // bounds and see if we can derive region bounds from those.
2834 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2836 // If there are no derived region bounds, then report back that we
2837 // can find no region bound. The caller will use the default.
2838 if derived_region_bounds.is_empty() {
2842 // If any of the derived region bounds are 'static, that is always
2844 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2845 return Some(tcx.lifetimes.re_static);
2848 // Determine whether there is exactly one unique region in the set
2849 // of derived region bounds. If so, use that. Otherwise, report an
2851 let r = derived_region_bounds[0];
2852 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2857 "ambiguous lifetime bound, explicit lifetime bound required"
2864 /// Collects together a list of bounds that are applied to some type,
2865 /// after they've been converted into `ty` form (from the HIR
2866 /// representations). These lists of bounds occur in many places in
2870 /// trait Foo: Bar + Baz { }
2871 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2873 /// fn foo<T: Bar + Baz>() { }
2874 /// ^^^^^^^^^ bounding the type parameter `T`
2876 /// impl dyn Bar + Baz
2877 /// ^^^^^^^^^ bounding the forgotten dynamic type
2880 /// Our representation is a bit mixed here -- in some cases, we
2881 /// include the self type (e.g., `trait_bounds`) but in others we do
2882 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2883 pub struct Bounds<'tcx> {
2884 /// A list of region bounds on the (implicit) self type. So if you
2885 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2886 /// the `T` is not explicitly included).
2887 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2889 /// A list of trait bounds. So if you had `T: Debug` this would be
2890 /// `T: Debug`. Note that the self-type is explicit here.
2891 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2893 /// A list of projection equality bounds. So if you had `T:
2894 /// Iterator<Item = u32>` this would include `<T as
2895 /// Iterator>::Item => u32`. Note that the self-type is explicit
2897 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2899 /// `Some` if there is *no* `?Sized` predicate. The `span`
2900 /// is the location in the source of the `T` declaration which can
2901 /// be cited as the source of the `T: Sized` requirement.
2902 pub implicitly_sized: Option<Span>,
2905 impl<'tcx> Bounds<'tcx> {
2906 /// Converts a bounds list into a flat set of predicates (like
2907 /// where-clauses). Because some of our bounds listings (e.g.,
2908 /// regions) don't include the self-type, you must supply the
2909 /// self-type here (the `param_ty` parameter).
2914 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2915 // If it could be sized, and is, add the `Sized` predicate.
2916 let sized_predicate = self.implicitly_sized.and_then(|span| {
2917 tcx.lang_items().sized_trait().map(|sized| {
2918 let trait_ref = ty::Binder::bind(ty::TraitRef {
2920 substs: tcx.mk_substs_trait(param_ty, &[]),
2922 (trait_ref.to_predicate(), span)
2931 .map(|&(region_bound, span)| {
2932 // Account for the binder being introduced below; no need to shift `param_ty`
2933 // because, at present at least, it either only refers to early-bound regions,
2934 // or it's a generic associated type that deliberately has escaping bound vars.
2935 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2936 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2937 (ty::Binder::bind(outlives).to_predicate(), span)
2942 .map(|&(bound_trait_ref, span)| (bound_trait_ref.to_predicate(), span)),
2945 self.projection_bounds
2947 .map(|&(projection, span)| (projection.to_predicate(), span)),