1 // ignore-tidy-filelength FIXME(#67418) Split up this file.
2 //! Conversion from AST representation of types to the `ty.rs` representation.
3 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
4 //! instance of `AstConv`.
6 use crate::collect::PlaceholderHirTyCollector;
8 use crate::middle::lang_items::SizedTraitLangItem;
9 use crate::middle::resolve_lifetime as rl;
10 use crate::namespace::Namespace;
11 use crate::require_c_abi_if_c_variadic;
12 use crate::util::common::ErrorReported;
13 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
14 use rustc::session::parse::feature_err;
16 use rustc::traits::astconv_object_safety_violations;
17 use rustc::traits::error_reporting::report_object_safety_error;
18 use rustc::traits::wf::object_region_bounds;
19 use rustc::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
20 use rustc::ty::{self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
21 use rustc::ty::{GenericParamDef, GenericParamDefKind};
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId};
25 use rustc_hir::def::{CtorOf, DefKind, Res};
26 use rustc_hir::def_id::DefId;
27 use rustc_hir::intravisit::Visitor;
29 use rustc_hir::{ExprKind, GenericArg, GenericArgs};
30 use rustc_span::symbol::sym;
31 use rustc_span::{MultiSpan, Span, DUMMY_SP};
32 use rustc_target::spec::abi;
33 use smallvec::SmallVec;
35 use syntax::util::lev_distance::find_best_match_for_name;
37 use std::collections::BTreeSet;
41 use rustc::mir::interpret::LitToConstInput;
42 use rustc_error_codes::*;
45 pub struct PathSeg(pub DefId, pub usize);
47 pub trait AstConv<'tcx> {
48 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
50 fn item_def_id(&self) -> Option<DefId>;
52 /// Returns predicates in scope of the form `X: Foo`, where `X` is
53 /// a type parameter `X` with the given id `def_id`. This is a
54 /// subset of the full set of predicates.
56 /// This is used for one specific purpose: resolving "short-hand"
57 /// associated type references like `T::Item`. In principle, we
58 /// would do that by first getting the full set of predicates in
59 /// scope and then filtering down to find those that apply to `T`,
60 /// but this can lead to cycle errors. The problem is that we have
61 /// to do this resolution *in order to create the predicates in
62 /// the first place*. Hence, we have this "special pass".
63 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
65 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
66 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
67 -> Option<ty::Region<'tcx>>;
69 /// Returns the type to use when a type is omitted.
70 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
72 /// Returns `true` if `_` is allowed in type signatures in the current context.
73 fn allow_ty_infer(&self) -> bool;
75 /// Returns the const to use when a const is omitted.
79 param: Option<&ty::GenericParamDef>,
81 ) -> &'tcx Const<'tcx>;
83 /// Projecting an associated type from a (potentially)
84 /// higher-ranked trait reference is more complicated, because of
85 /// the possibility of late-bound regions appearing in the
86 /// associated type binding. This is not legal in function
87 /// signatures for that reason. In a function body, we can always
88 /// handle it because we can use inference variables to remove the
89 /// late-bound regions.
90 fn projected_ty_from_poly_trait_ref(
94 item_segment: &hir::PathSegment<'_>,
95 poly_trait_ref: ty::PolyTraitRef<'tcx>,
98 /// Normalize an associated type coming from the user.
99 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
101 /// Invoked when we encounter an error from some prior pass
102 /// (e.g., resolve) that is translated into a ty-error. This is
103 /// used to help suppress derived errors typeck might otherwise
105 fn set_tainted_by_errors(&self);
107 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
110 pub enum SizedByDefault {
115 struct ConvertedBinding<'a, 'tcx> {
116 item_name: ast::Ident,
117 kind: ConvertedBindingKind<'a, 'tcx>,
121 enum ConvertedBindingKind<'a, 'tcx> {
123 Constraint(&'a [hir::GenericBound<'a>]),
127 enum GenericArgPosition {
129 Value, // e.g., functions
133 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
134 pub fn ast_region_to_region(
136 lifetime: &hir::Lifetime,
137 def: Option<&ty::GenericParamDef>,
138 ) -> ty::Region<'tcx> {
139 let tcx = self.tcx();
140 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap());
142 let r = match tcx.named_region(lifetime.hir_id) {
143 Some(rl::Region::Static) => tcx.lifetimes.re_static,
145 Some(rl::Region::LateBound(debruijn, id, _)) => {
146 let name = lifetime_name(id);
147 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
150 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
151 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
154 Some(rl::Region::EarlyBound(index, id, _)) => {
155 let name = lifetime_name(id);
156 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
159 Some(rl::Region::Free(scope, id)) => {
160 let name = lifetime_name(id);
161 tcx.mk_region(ty::ReFree(ty::FreeRegion {
163 bound_region: ty::BrNamed(id, name),
166 // (*) -- not late-bound, won't change
170 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
171 // This indicates an illegal lifetime
172 // elision. `resolve_lifetime` should have
173 // reported an error in this case -- but if
174 // not, let's error out.
175 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
177 // Supply some dummy value. We don't have an
178 // `re_error`, annoyingly, so use `'static`.
179 tcx.lifetimes.re_static
184 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
189 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
190 /// returns an appropriate set of substitutions for this particular reference to `I`.
191 pub fn ast_path_substs_for_ty(
195 item_segment: &hir::PathSegment<'_>,
196 ) -> SubstsRef<'tcx> {
197 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
201 item_segment.generic_args(),
202 item_segment.infer_args,
206 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
211 /// Report error if there is an explicit type parameter when using `impl Trait`.
214 seg: &hir::PathSegment<'_>,
215 generics: &ty::Generics,
217 let explicit = !seg.infer_args;
218 let impl_trait = generics.params.iter().any(|param| match param.kind {
219 ty::GenericParamDefKind::Type {
220 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
226 if explicit && impl_trait {
231 .filter_map(|arg| match arg {
232 GenericArg::Type(_) => Some(arg.span()),
235 .collect::<Vec<_>>();
237 let mut err = struct_span_err! {
241 "cannot provide explicit generic arguments when `impl Trait` is \
242 used in argument position"
246 err.span_label(span, "explicit generic argument not allowed");
255 /// Checks that the correct number of generic arguments have been provided.
256 /// Used specifically for function calls.
257 pub fn check_generic_arg_count_for_call(
261 seg: &hir::PathSegment<'_>,
262 is_method_call: bool,
264 let empty_args = hir::GenericArgs::none();
265 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
266 Self::check_generic_arg_count(
270 if let Some(ref args) = seg.args { args } else { &empty_args },
271 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
272 def.parent.is_none() && def.has_self, // `has_self`
273 seg.infer_args || suppress_mismatch, // `infer_args`
278 /// Checks that the correct number of generic arguments have been provided.
279 /// This is used both for datatypes and function calls.
280 fn check_generic_arg_count(
284 args: &hir::GenericArgs<'_>,
285 position: GenericArgPosition,
288 ) -> (bool, Option<Vec<Span>>) {
289 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
290 // that lifetimes will proceed types. So it suffices to check the number of each generic
291 // arguments in order to validate them with respect to the generic parameters.
292 let param_counts = def.own_counts();
293 let arg_counts = args.own_counts();
294 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
296 let mut defaults: ty::GenericParamCount = Default::default();
297 for param in &def.params {
299 GenericParamDefKind::Lifetime => {}
300 GenericParamDefKind::Type { has_default, .. } => {
301 defaults.types += has_default as usize
303 GenericParamDefKind::Const => {
304 // FIXME(const_generics:defaults)
309 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
310 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
313 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
314 let mut reported_late_bound_region_err = None;
315 if !infer_lifetimes {
316 if let Some(span_late) = def.has_late_bound_regions {
317 let msg = "cannot specify lifetime arguments explicitly \
318 if late bound lifetime parameters are present";
319 let note = "the late bound lifetime parameter is introduced here";
320 let span = args.args[0].span();
321 if position == GenericArgPosition::Value
322 && arg_counts.lifetimes != param_counts.lifetimes
324 let mut err = tcx.sess.struct_span_err(span, msg);
325 err.span_note(span_late, note);
327 reported_late_bound_region_err = Some(true);
329 let mut multispan = MultiSpan::from_span(span);
330 multispan.push_span_label(span_late, note.to_string());
332 lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
337 reported_late_bound_region_err = Some(false);
342 let check_kind_count = |kind, required, permitted, provided, offset| {
344 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
345 kind, required, permitted, provided, offset
347 // We enforce the following: `required` <= `provided` <= `permitted`.
348 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
349 // For other kinds (i.e., types), `permitted` may be greater than `required`.
350 if required <= provided && provided <= permitted {
351 return (reported_late_bound_region_err.unwrap_or(false), None);
354 // Unfortunately lifetime and type parameter mismatches are typically styled
355 // differently in diagnostics, which means we have a few cases to consider here.
356 let (bound, quantifier) = if required != permitted {
357 if provided < required {
358 (required, "at least ")
360 // provided > permitted
361 (permitted, "at most ")
367 let mut potential_assoc_types: Option<Vec<Span>> = None;
368 let (spans, label) = if required == permitted && provided > permitted {
369 // In the case when the user has provided too many arguments,
370 // we want to point to the unexpected arguments.
371 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
373 .map(|arg| arg.span())
375 potential_assoc_types = Some(spans.clone());
376 (spans, format!("unexpected {} argument", kind))
381 "expected {}{} {} argument{}",
390 let mut err = tcx.sess.struct_span_err_with_code(
393 "wrong number of {} arguments: expected {}{}, found {}",
394 kind, quantifier, bound, provided,
396 DiagnosticId::Error("E0107".into()),
399 err.span_label(span, label.as_str());
404 provided > required, // `suppress_error`
405 potential_assoc_types,
409 if reported_late_bound_region_err.is_none()
410 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
414 param_counts.lifetimes,
415 param_counts.lifetimes,
416 arg_counts.lifetimes,
420 // FIXME(const_generics:defaults)
421 if !infer_args || arg_counts.consts > param_counts.consts {
427 arg_counts.lifetimes + arg_counts.types,
430 // Note that type errors are currently be emitted *after* const errors.
431 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
435 param_counts.types - defaults.types - has_self as usize,
436 param_counts.types - has_self as usize,
438 arg_counts.lifetimes,
441 (reported_late_bound_region_err.unwrap_or(false), None)
445 /// Creates the relevant generic argument substitutions
446 /// corresponding to a set of generic parameters. This is a
447 /// rather complex function. Let us try to explain the role
448 /// of each of its parameters:
450 /// To start, we are given the `def_id` of the thing we are
451 /// creating the substitutions for, and a partial set of
452 /// substitutions `parent_substs`. In general, the substitutions
453 /// for an item begin with substitutions for all the "parents" of
454 /// that item -- e.g., for a method it might include the
455 /// parameters from the impl.
457 /// Therefore, the method begins by walking down these parents,
458 /// starting with the outermost parent and proceed inwards until
459 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
460 /// first to see if the parent's substitutions are listed in there. If so,
461 /// we can append those and move on. Otherwise, it invokes the
462 /// three callback functions:
464 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
465 /// generic arguments that were given to that parent from within
466 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
467 /// might refer to the trait `Foo`, and the arguments might be
468 /// `[T]`. The boolean value indicates whether to infer values
469 /// for arguments whose values were not explicitly provided.
470 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
471 /// instantiate a `GenericArg`.
472 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
473 /// creates a suitable inference variable.
474 pub fn create_substs_for_generic_args<'b>(
477 parent_substs: &[subst::GenericArg<'tcx>],
479 self_ty: Option<Ty<'tcx>>,
480 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
481 provided_kind: impl Fn(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
482 mut inferred_kind: impl FnMut(
483 Option<&[subst::GenericArg<'tcx>]>,
486 ) -> subst::GenericArg<'tcx>,
487 ) -> SubstsRef<'tcx> {
488 // Collect the segments of the path; we need to substitute arguments
489 // for parameters throughout the entire path (wherever there are
490 // generic parameters).
491 let mut parent_defs = tcx.generics_of(def_id);
492 let count = parent_defs.count();
493 let mut stack = vec![(def_id, parent_defs)];
494 while let Some(def_id) = parent_defs.parent {
495 parent_defs = tcx.generics_of(def_id);
496 stack.push((def_id, parent_defs));
499 // We manually build up the substitution, rather than using convenience
500 // methods in `subst.rs`, so that we can iterate over the arguments and
501 // parameters in lock-step linearly, instead of trying to match each pair.
502 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
504 // Iterate over each segment of the path.
505 while let Some((def_id, defs)) = stack.pop() {
506 let mut params = defs.params.iter().peekable();
508 // If we have already computed substitutions for parents, we can use those directly.
509 while let Some(¶m) = params.peek() {
510 if let Some(&kind) = parent_substs.get(param.index as usize) {
518 // `Self` is handled first, unless it's been handled in `parent_substs`.
520 if let Some(¶m) = params.peek() {
521 if param.index == 0 {
522 if let GenericParamDefKind::Type { .. } = param.kind {
526 .unwrap_or_else(|| inferred_kind(None, param, true)),
534 // Check whether this segment takes generic arguments and the user has provided any.
535 let (generic_args, infer_args) = args_for_def_id(def_id);
538 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
541 // We're going to iterate through the generic arguments that the user
542 // provided, matching them with the generic parameters we expect.
543 // Mismatches can occur as a result of elided lifetimes, or for malformed
544 // input. We try to handle both sensibly.
545 match (args.peek(), params.peek()) {
546 (Some(&arg), Some(¶m)) => {
547 match (arg, ¶m.kind) {
548 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
549 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
550 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
551 substs.push(provided_kind(param, arg));
555 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
556 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
557 // We expected a lifetime argument, but got a type or const
558 // argument. That means we're inferring the lifetimes.
559 substs.push(inferred_kind(None, param, infer_args));
563 // We expected one kind of parameter, but the user provided
564 // another. This is an error, but we need to handle it
565 // gracefully so we can report sensible errors.
566 // In this case, we're simply going to infer this argument.
572 // We should never be able to reach this point with well-formed input.
573 // Getting to this point means the user supplied more arguments than
574 // there are parameters.
577 (None, Some(¶m)) => {
578 // If there are fewer arguments than parameters, it means
579 // we're inferring the remaining arguments.
580 substs.push(inferred_kind(Some(&substs), param, infer_args));
584 (None, None) => break,
589 tcx.intern_substs(&substs)
592 /// Given the type/lifetime/const arguments provided to some path (along with
593 /// an implicit `Self`, if this is a trait reference), returns the complete
594 /// set of substitutions. This may involve applying defaulted type parameters.
595 /// Also returns back constriants on associated types.
600 /// T: std::ops::Index<usize, Output = u32>
601 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
604 /// 1. The `self_ty` here would refer to the type `T`.
605 /// 2. The path in question is the path to the trait `std::ops::Index`,
606 /// which will have been resolved to a `def_id`
607 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
608 /// parameters are returned in the `SubstsRef`, the associated type bindings like
609 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
611 /// Note that the type listing given here is *exactly* what the user provided.
613 /// For (generic) associated types
616 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
619 /// We have the parent substs are the substs for the parent trait:
620 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
621 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
622 /// lists: `[Vec<u8>, u8, 'a]`.
623 fn create_substs_for_ast_path<'a>(
627 parent_substs: &[subst::GenericArg<'tcx>],
628 generic_args: &'a hir::GenericArgs<'_>,
630 self_ty: Option<Ty<'tcx>>,
631 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
632 // If the type is parameterized by this region, then replace this
633 // region with the current anon region binding (in other words,
634 // whatever & would get replaced with).
636 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
638 def_id, self_ty, generic_args
641 let tcx = self.tcx();
642 let generic_params = tcx.generics_of(def_id);
644 if generic_params.has_self {
645 if generic_params.parent.is_some() {
646 // The parent is a trait so it should have at least one subst
647 // for the `Self` type.
648 assert!(!parent_substs.is_empty())
650 // This item (presumably a trait) needs a self-type.
651 assert!(self_ty.is_some());
654 assert!(self_ty.is_none() && parent_substs.is_empty());
657 let (_, potential_assoc_types) = Self::check_generic_arg_count(
662 GenericArgPosition::Type,
667 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
668 let default_needs_object_self = |param: &ty::GenericParamDef| {
669 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
670 if is_object && has_default {
671 let self_param = tcx.types.self_param;
672 if tcx.at(span).type_of(param.def_id).walk().any(|ty| ty == self_param) {
673 // There is no suitable inference default for a type parameter
674 // that references self, in an object type.
683 let mut missing_type_params = vec![];
684 let substs = Self::create_substs_for_generic_args(
690 // Provide the generic args, and whether types should be inferred.
691 |_| (Some(generic_args), infer_args),
692 // Provide substitutions for parameters for which (valid) arguments have been provided.
693 |param, arg| match (¶m.kind, arg) {
694 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
695 self.ast_region_to_region(<, Some(param)).into()
697 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
698 self.ast_ty_to_ty(&ty).into()
700 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
701 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
705 // Provide substitutions for parameters for which arguments are inferred.
706 |substs, param, infer_args| {
708 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
709 GenericParamDefKind::Type { has_default, .. } => {
710 if !infer_args && has_default {
711 // No type parameter provided, but a default exists.
713 // If we are converting an object type, then the
714 // `Self` parameter is unknown. However, some of the
715 // other type parameters may reference `Self` in their
716 // defaults. This will lead to an ICE if we are not
718 if default_needs_object_self(param) {
719 missing_type_params.push(param.name.to_string());
722 // This is a default type parameter.
725 tcx.at(span).type_of(param.def_id).subst_spanned(
733 } else if infer_args {
734 // No type parameters were provided, we can infer all.
736 if !default_needs_object_self(param) { Some(param) } else { None };
737 self.ty_infer(param, span).into()
739 // We've already errored above about the mismatch.
743 GenericParamDefKind::Const => {
744 // FIXME(const_generics:defaults)
746 // No const parameters were provided, we can infer all.
747 let ty = tcx.at(span).type_of(param.def_id);
748 self.ct_infer(ty, Some(param), span).into()
750 // We've already errored above about the mismatch.
751 tcx.consts.err.into()
758 self.complain_about_missing_type_params(
762 generic_args.args.is_empty(),
765 // Convert associated-type bindings or constraints into a separate vector.
766 // Example: Given this:
768 // T: Iterator<Item = u32>
770 // The `T` is passed in as a self-type; the `Item = u32` is
771 // not a "type parameter" of the `Iterator` trait, but rather
772 // a restriction on `<T as Iterator>::Item`, so it is passed
774 let assoc_bindings = generic_args
778 let kind = match binding.kind {
779 hir::TypeBindingKind::Equality { ref ty } => {
780 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
782 hir::TypeBindingKind::Constraint { ref bounds } => {
783 ConvertedBindingKind::Constraint(bounds)
786 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
791 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
792 generic_params, self_ty, substs
795 (substs, assoc_bindings, potential_assoc_types)
798 crate fn create_substs_for_associated_item(
803 item_segment: &hir::PathSegment<'_>,
804 parent_substs: SubstsRef<'tcx>,
805 ) -> SubstsRef<'tcx> {
806 if tcx.generics_of(item_def_id).params.is_empty() {
807 self.prohibit_generics(slice::from_ref(item_segment));
811 self.create_substs_for_ast_path(
815 item_segment.generic_args(),
816 item_segment.infer_args,
823 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
824 /// the type parameter's name as a placeholder.
825 fn complain_about_missing_type_params(
827 missing_type_params: Vec<String>,
830 empty_generic_args: bool,
832 if missing_type_params.is_empty() {
836 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
837 let mut err = struct_span_err!(
841 "the type parameter{} {} must be explicitly specified",
842 pluralize!(missing_type_params.len()),
846 self.tcx().def_span(def_id),
848 "type parameter{} {} must be specified for this",
849 pluralize!(missing_type_params.len()),
853 let mut suggested = false;
854 if let (Ok(snippet), true) = (
855 self.tcx().sess.source_map().span_to_snippet(span),
856 // Don't suggest setting the type params if there are some already: the order is
857 // tricky to get right and the user will already know what the syntax is.
860 if snippet.ends_with('>') {
861 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
862 // we would have to preserve the right order. For now, as clearly the user is
863 // aware of the syntax, we do nothing.
865 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
866 // least we can clue them to the correct syntax `Iterator<Type>`.
870 "set the type parameter{plural} to the desired type{plural}",
871 plural = pluralize!(missing_type_params.len()),
873 format!("{}<{}>", snippet, missing_type_params.join(", ")),
874 Applicability::HasPlaceholders,
883 "missing reference{} to {}",
884 pluralize!(missing_type_params.len()),
890 "because of the default `Self` reference, type parameters must be \
891 specified on object types"
896 /// Instantiates the path for the given trait reference, assuming that it's
897 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
898 /// The type _cannot_ be a type other than a trait type.
900 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
901 /// are disallowed. Otherwise, they are pushed onto the vector given.
902 pub fn instantiate_mono_trait_ref(
904 trait_ref: &hir::TraitRef<'_>,
906 ) -> ty::TraitRef<'tcx> {
907 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
909 self.ast_path_to_mono_trait_ref(
911 trait_ref.trait_def_id(),
913 trait_ref.path.segments.last().unwrap(),
917 /// The given trait-ref must actually be a trait.
918 pub(super) fn instantiate_poly_trait_ref_inner(
920 trait_ref: &hir::TraitRef<'_>,
923 bounds: &mut Bounds<'tcx>,
925 ) -> Option<Vec<Span>> {
926 let trait_def_id = trait_ref.trait_def_id();
928 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
930 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
932 let path_span = if let [segment] = &trait_ref.path.segments[..] {
933 // FIXME: `trait_ref.path.span` can point to a full path with multiple
934 // segments, even though `trait_ref.path.segments` is of length `1`. Work
935 // around that bug here, even though it should be fixed elsewhere.
936 // This would otherwise cause an invalid suggestion. For an example, look at
937 // `src/test/ui/issues/issue-28344.rs`.
942 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
946 trait_ref.path.segments.last().unwrap(),
948 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
950 bounds.trait_bounds.push((poly_trait_ref, span));
952 let mut dup_bindings = FxHashMap::default();
953 for binding in &assoc_bindings {
954 // Specify type to assert that error was already reported in `Err` case.
955 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
956 trait_ref.hir_ref_id,
964 // Okay to ignore `Err` because of `ErrorReported` (see above).
968 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
969 trait_ref, bounds, poly_trait_ref
971 potential_assoc_types
974 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
975 /// a full trait reference. The resulting trait reference is returned. This may also generate
976 /// auxiliary bounds, which are added to `bounds`.
981 /// poly_trait_ref = Iterator<Item = u32>
985 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
987 /// **A note on binders:** against our usual convention, there is an implied bounder around
988 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
989 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
990 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
991 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
993 pub fn instantiate_poly_trait_ref(
995 poly_trait_ref: &hir::PolyTraitRef<'_>,
997 bounds: &mut Bounds<'tcx>,
998 ) -> Option<Vec<Span>> {
999 self.instantiate_poly_trait_ref_inner(
1000 &poly_trait_ref.trait_ref,
1001 poly_trait_ref.span,
1008 fn ast_path_to_mono_trait_ref(
1011 trait_def_id: DefId,
1013 trait_segment: &hir::PathSegment<'_>,
1014 ) -> ty::TraitRef<'tcx> {
1015 let (substs, assoc_bindings, _) =
1016 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1017 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
1018 ty::TraitRef::new(trait_def_id, substs)
1021 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1022 /// an error and attempt to build a reasonable structured suggestion.
1023 fn complain_about_internal_fn_trait(
1026 trait_def_id: DefId,
1027 trait_segment: &'a hir::PathSegment<'a>,
1029 let trait_def = self.tcx().trait_def(trait_def_id);
1031 if !self.tcx().features().unboxed_closures
1032 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1034 // For now, require that parenthetical notation be used only with `Fn()` etc.
1035 let (msg, sugg) = if trait_def.paren_sugar {
1037 "the precise format of `Fn`-family traits' type parameters is subject to \
1041 trait_segment.ident,
1045 .and_then(|args| args.args.get(0))
1046 .and_then(|arg| match arg {
1047 hir::GenericArg::Type(ty) => {
1048 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1052 .unwrap_or_else(|| "()".to_string()),
1057 .filter_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1058 (true, hir::TypeBindingKind::Equality { ty }) => {
1059 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1064 .unwrap_or_else(|| "()".to_string()),
1068 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1070 let sess = &self.tcx().sess.parse_sess;
1071 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1072 if let Some(sugg) = sugg {
1073 let msg = "use parenthetical notation instead";
1074 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1080 fn create_substs_for_ast_trait_ref<'a>(
1083 trait_def_id: DefId,
1085 trait_segment: &'a hir::PathSegment<'a>,
1086 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
1087 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1089 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1091 self.create_substs_for_ast_path(
1095 trait_segment.generic_args(),
1096 trait_segment.infer_args,
1101 fn trait_defines_associated_type_named(
1103 trait_def_id: DefId,
1104 assoc_name: ast::Ident,
1106 self.tcx().associated_items(trait_def_id).any(|item| {
1107 item.kind == ty::AssocKind::Type
1108 && self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
1112 // Returns `true` if a bounds list includes `?Sized`.
1113 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1114 let tcx = self.tcx();
1116 // Try to find an unbound in bounds.
1117 let mut unbound = None;
1118 for ab in ast_bounds {
1119 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1120 if unbound.is_none() {
1121 unbound = Some(&ptr.trait_ref);
1127 "type parameter has more than one relaxed default \
1128 bound, only one is supported"
1135 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1138 // FIXME(#8559) currently requires the unbound to be built-in.
1139 if let Ok(kind_id) = kind_id {
1140 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1143 "default bound relaxed for a type parameter, but \
1144 this does nothing because the given bound is not \
1145 a default; only `?Sized` is supported",
1150 _ if kind_id.is_ok() => {
1153 // No lang item for `Sized`, so we can't add it as a bound.
1160 /// This helper takes a *converted* parameter type (`param_ty`)
1161 /// and an *unconverted* list of bounds:
1164 /// fn foo<T: Debug>
1165 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1167 /// `param_ty`, in ty form
1170 /// It adds these `ast_bounds` into the `bounds` structure.
1172 /// **A note on binders:** there is an implied binder around
1173 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1174 /// for more details.
1178 ast_bounds: &[hir::GenericBound<'_>],
1179 bounds: &mut Bounds<'tcx>,
1181 let mut trait_bounds = Vec::new();
1182 let mut region_bounds = Vec::new();
1184 for ast_bound in ast_bounds {
1186 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1187 trait_bounds.push(b)
1189 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1190 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1194 for bound in trait_bounds {
1195 let _ = self.instantiate_poly_trait_ref(bound, param_ty, bounds);
1198 bounds.region_bounds.extend(
1199 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1203 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1204 /// The self-type for the bounds is given by `param_ty`.
1209 /// fn foo<T: Bar + Baz>() { }
1210 /// ^ ^^^^^^^^^ ast_bounds
1214 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1215 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1216 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1218 /// `span` should be the declaration size of the parameter.
1219 pub fn compute_bounds(
1222 ast_bounds: &[hir::GenericBound<'_>],
1223 sized_by_default: SizedByDefault,
1226 let mut bounds = Bounds::default();
1228 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1229 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1231 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1232 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1240 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1243 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1244 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1245 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1246 fn add_predicates_for_ast_type_binding(
1248 hir_ref_id: hir::HirId,
1249 trait_ref: ty::PolyTraitRef<'tcx>,
1250 binding: &ConvertedBinding<'_, 'tcx>,
1251 bounds: &mut Bounds<'tcx>,
1253 dup_bindings: &mut FxHashMap<DefId, Span>,
1255 ) -> Result<(), ErrorReported> {
1256 let tcx = self.tcx();
1259 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1260 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1261 // subtle in the event that `T` is defined in a supertrait of
1262 // `SomeTrait`, because in that case we need to upcast.
1264 // That is, consider this case:
1267 // trait SubTrait: SuperTrait<int> { }
1268 // trait SuperTrait<A> { type T; }
1270 // ... B: SubTrait<T = foo> ...
1273 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1275 // Find any late-bound regions declared in `ty` that are not
1276 // declared in the trait-ref. These are not well-formed.
1280 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1281 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1282 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1283 let late_bound_in_trait_ref =
1284 tcx.collect_constrained_late_bound_regions(&trait_ref);
1285 let late_bound_in_ty =
1286 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1287 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1288 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1289 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1290 let br_name = match *br {
1291 ty::BrNamed(_, name) => name,
1295 "anonymous bound region {:?} in binding but not trait ref",
1304 "binding for associated type `{}` references lifetime `{}`, \
1305 which does not appear in the trait input types",
1315 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1316 // Simple case: X is defined in the current trait.
1319 // Otherwise, we have to walk through the supertraits to find
1321 self.one_bound_for_assoc_type(
1322 || traits::supertraits(tcx, trait_ref),
1323 &trait_ref.print_only_trait_path().to_string(),
1326 match binding.kind {
1327 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1333 let (assoc_ident, def_scope) =
1334 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1336 .associated_items(candidate.def_id())
1337 .find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident)
1338 .expect("missing associated type");
1340 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1341 let msg = format!("associated type `{}` is private", binding.item_name);
1342 tcx.sess.span_err(binding.span, &msg);
1344 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1348 .entry(assoc_ty.def_id)
1349 .and_modify(|prev_span| {
1354 "the value of the associated type `{}` (from trait `{}`) \
1355 is already specified",
1357 tcx.def_path_str(assoc_ty.container.id())
1359 .span_label(binding.span, "re-bound here")
1360 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1363 .or_insert(binding.span);
1366 match binding.kind {
1367 ConvertedBindingKind::Equality(ref ty) => {
1368 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1369 // the "projection predicate" for:
1371 // `<T as Iterator>::Item = u32`
1372 bounds.projection_bounds.push((
1373 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1374 projection_ty: ty::ProjectionTy::from_ref_and_name(
1384 ConvertedBindingKind::Constraint(ast_bounds) => {
1385 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1387 // `<T as Iterator>::Item: Debug`
1389 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1390 // parameter to have a skipped binder.
1391 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1392 self.add_bounds(param_ty, ast_bounds, bounds);
1402 item_segment: &hir::PathSegment<'_>,
1404 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1405 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1408 fn conv_object_ty_poly_trait_ref(
1411 trait_bounds: &[hir::PolyTraitRef<'_>],
1412 lifetime: &hir::Lifetime,
1414 let tcx = self.tcx();
1416 let mut bounds = Bounds::default();
1417 let mut potential_assoc_types = Vec::new();
1418 let dummy_self = self.tcx().types.trait_object_dummy_self;
1419 for trait_bound in trait_bounds.iter().rev() {
1420 let cur_potential_assoc_types =
1421 self.instantiate_poly_trait_ref(trait_bound, dummy_self, &mut bounds);
1422 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1425 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1426 // is used and no 'maybe' bounds are used.
1427 let expanded_traits =
1428 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1429 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1430 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1431 if regular_traits.len() > 1 {
1432 let first_trait = ®ular_traits[0];
1433 let additional_trait = ®ular_traits[1];
1434 let mut err = struct_span_err!(
1436 additional_trait.bottom().1,
1438 "only auto traits can be used as additional traits in a trait object"
1440 additional_trait.label_with_exp_info(
1442 "additional non-auto trait",
1445 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1449 if regular_traits.is_empty() && auto_traits.is_empty() {
1454 "at least one trait is required for an object type"
1457 return tcx.types.err;
1460 // Check that there are no gross object safety violations;
1461 // most importantly, that the supertraits don't contain `Self`,
1463 for item in ®ular_traits {
1464 let object_safety_violations =
1465 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1466 if !object_safety_violations.is_empty() {
1467 report_object_safety_error(
1470 item.trait_ref().def_id(),
1471 object_safety_violations,
1474 return tcx.types.err;
1478 // Use a `BTreeSet` to keep output in a more consistent order.
1479 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1481 let regular_traits_refs_spans = bounds
1484 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1486 for (base_trait_ref, span) in regular_traits_refs_spans {
1487 for trait_ref in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1489 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1493 ty::Predicate::Trait(pred) => {
1494 associated_types.entry(span).or_default().extend(
1495 tcx.associated_items(pred.def_id())
1496 .filter(|item| item.kind == ty::AssocKind::Type)
1497 .map(|item| item.def_id),
1500 ty::Predicate::Projection(pred) => {
1501 // A `Self` within the original bound will be substituted with a
1502 // `trait_object_dummy_self`, so check for that.
1503 let references_self = pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1505 // If the projection output contains `Self`, force the user to
1506 // elaborate it explicitly to avoid a lot of complexity.
1508 // The "classicaly useful" case is the following:
1510 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1515 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1516 // but actually supporting that would "expand" to an infinitely-long type
1517 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1519 // Instead, we force the user to write
1520 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1521 // the discussion in #56288 for alternatives.
1522 if !references_self {
1523 // Include projections defined on supertraits.
1524 bounds.projection_bounds.push((pred, span));
1532 for (projection_bound, _) in &bounds.projection_bounds {
1533 for (_, def_ids) in &mut associated_types {
1534 def_ids.remove(&projection_bound.projection_def_id());
1538 self.complain_about_missing_associated_types(
1540 potential_assoc_types,
1544 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1545 // `dyn Trait + Send`.
1546 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1547 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1548 debug!("regular_traits: {:?}", regular_traits);
1549 debug!("auto_traits: {:?}", auto_traits);
1551 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1552 // removing the dummy `Self` type (`trait_object_dummy_self`).
1553 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1554 if trait_ref.self_ty() != dummy_self {
1555 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1556 // which picks up non-supertraits where clauses - but also, the object safety
1557 // completely ignores trait aliases, which could be object safety hazards. We
1558 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1559 // disabled. (#66420)
1560 tcx.sess.delay_span_bug(
1563 "trait_ref_to_existential called on {:?} with non-dummy Self",
1568 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1571 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1572 let existential_trait_refs = regular_traits
1574 .map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
1575 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1576 bound.map_bound(|b| {
1577 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1578 ty::ExistentialProjection {
1580 item_def_id: b.projection_ty.item_def_id,
1581 substs: trait_ref.substs,
1586 // Calling `skip_binder` is okay because the predicates are re-bound.
1587 let regular_trait_predicates = existential_trait_refs
1588 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1589 let auto_trait_predicates = auto_traits
1591 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1592 let mut v = regular_trait_predicates
1593 .chain(auto_trait_predicates)
1595 existential_projections
1596 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1598 .collect::<SmallVec<[_; 8]>>();
1599 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1601 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1603 // Use explicitly-specified region bound.
1604 let region_bound = if !lifetime.is_elided() {
1605 self.ast_region_to_region(lifetime, None)
1607 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1608 if tcx.named_region(lifetime.hir_id).is_some() {
1609 self.ast_region_to_region(lifetime, None)
1611 self.re_infer(None, span).unwrap_or_else(|| {
1616 "the lifetime bound for this object type cannot be deduced \
1617 from context; please supply an explicit bound"
1620 tcx.lifetimes.re_static
1625 debug!("region_bound: {:?}", region_bound);
1627 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1628 debug!("trait_object_type: {:?}", ty);
1632 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1633 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1634 /// same trait bound have the same name (as they come from different super-traits), we instead
1635 /// emit a generic note suggesting using a `where` clause to constraint instead.
1636 fn complain_about_missing_associated_types(
1638 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1639 potential_assoc_types: Vec<Span>,
1640 trait_bounds: &[hir::PolyTraitRef<'_>],
1642 if !associated_types.values().any(|v| v.len() > 0) {
1645 let tcx = self.tcx();
1646 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1647 // appropriate one, but this should be handled earlier in the span assignment.
1648 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1650 .map(|(span, def_ids)| {
1651 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1654 let mut names = vec![];
1656 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1657 // `issue-22560.rs`.
1658 let mut trait_bound_spans: Vec<Span> = vec![];
1659 for (span, items) in &associated_types {
1660 if !items.is_empty() {
1661 trait_bound_spans.push(*span);
1663 for assoc_item in items {
1664 let trait_def_id = assoc_item.container.id();
1666 "`{}` (from trait `{}`)",
1668 tcx.def_path_str(trait_def_id),
1673 match (&potential_assoc_types[..], &trait_bounds) {
1674 ([], [bound]) => match &bound.trait_ref.path.segments[..] {
1675 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1676 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1677 // around that bug here, even though it should be fixed elsewhere.
1678 // This would otherwise cause an invalid suggestion. For an example, look at
1679 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1681 // error[E0191]: the value of the associated type `Output`
1682 // (from trait `std::ops::BitXor`) must be specified
1683 // --> $DIR/issue-28344.rs:4:17
1685 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1686 // | ^^^^^^ help: specify the associated type:
1687 // | `BitXor<Output = Type>`
1691 // error[E0191]: the value of the associated type `Output`
1692 // (from trait `std::ops::BitXor`) must be specified
1693 // --> $DIR/issue-28344.rs:4:17
1695 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1696 // | ^^^^^^^^^^^^^ help: specify the associated type:
1697 // | `BitXor::bitor<Output = Type>`
1698 [segment] if segment.args.is_none() => {
1699 trait_bound_spans = vec![segment.ident.span];
1700 associated_types = associated_types
1702 .map(|(_, items)| (segment.ident.span, items))
1710 trait_bound_spans.sort();
1711 let mut err = struct_span_err!(
1715 "the value of the associated type{} {} must be specified",
1716 pluralize!(names.len()),
1719 let mut suggestions = vec![];
1720 let mut types_count = 0;
1721 let mut where_constraints = vec![];
1722 for (span, assoc_items) in &associated_types {
1723 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1724 for item in assoc_items {
1726 *names.entry(item.ident.name).or_insert(0) += 1;
1728 let mut dupes = false;
1729 for item in assoc_items {
1730 let prefix = if names[&item.ident.name] > 1 {
1731 let trait_def_id = item.container.id();
1733 format!("{}::", tcx.def_path_str(trait_def_id))
1737 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1738 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1741 if potential_assoc_types.len() == assoc_items.len() {
1742 // Only suggest when the amount of missing associated types equals the number of
1743 // extra type arguments present, as that gives us a relatively high confidence
1744 // that the user forgot to give the associtated type's name. The canonical
1745 // example would be trying to use `Iterator<isize>` instead of
1746 // `Iterator<Item = isize>`.
1747 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1748 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1749 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1752 } else if let (Ok(snippet), false) =
1753 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1756 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1757 let code = if snippet.ends_with(">") {
1758 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1759 // suggest, but at least we can clue them to the correct syntax
1760 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1762 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1764 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1765 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1766 format!("{}<{}>", snippet, types.join(", "))
1768 suggestions.push((*span, code));
1770 where_constraints.push(*span);
1773 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1774 using the fully-qualified path to the associated types";
1775 if !where_constraints.is_empty() && suggestions.is_empty() {
1776 // If there are duplicates associated type names and a single trait bound do not
1777 // use structured suggestion, it means that there are multiple super-traits with
1778 // the same associated type name.
1779 err.help(where_msg);
1781 if suggestions.len() != 1 {
1782 // We don't need this label if there's an inline suggestion, show otherwise.
1783 for (span, assoc_items) in &associated_types {
1784 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1785 for item in assoc_items {
1787 *names.entry(item.ident.name).or_insert(0) += 1;
1789 let mut label = vec![];
1790 for item in assoc_items {
1791 let postfix = if names[&item.ident.name] > 1 {
1792 let trait_def_id = item.container.id();
1793 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1797 label.push(format!("`{}`{}", item.ident, postfix));
1799 if !label.is_empty() {
1803 "associated type{} {} must be specified",
1804 pluralize!(label.len()),
1811 if !suggestions.is_empty() {
1812 err.multipart_suggestion(
1813 &format!("specify the associated type{}", pluralize!(types_count)),
1815 Applicability::HasPlaceholders,
1817 if !where_constraints.is_empty() {
1818 err.span_help(where_constraints, where_msg);
1824 fn report_ambiguous_associated_type(
1831 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1832 if let (Some(_), Ok(snippet)) = (
1833 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1834 self.tcx().sess.source_map().span_to_snippet(span),
1836 err.span_suggestion(
1838 "you are looking for the module in `std`, not the primitive type",
1839 format!("std::{}", snippet),
1840 Applicability::MachineApplicable,
1843 err.span_suggestion(
1845 "use fully-qualified syntax",
1846 format!("<{} as {}>::{}", type_str, trait_str, name),
1847 Applicability::HasPlaceholders,
1853 // Search for a bound on a type parameter which includes the associated item
1854 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1855 // This function will fail if there are no suitable bounds or there is
1857 fn find_bound_for_assoc_item(
1859 ty_param_def_id: DefId,
1860 assoc_name: ast::Ident,
1862 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1863 let tcx = self.tcx();
1866 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1867 ty_param_def_id, assoc_name, span,
1870 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1872 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1874 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1875 let param_name = tcx.hir().ty_param_name(param_hir_id);
1876 self.one_bound_for_assoc_type(
1878 traits::transitive_bounds(
1880 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1883 ¶m_name.as_str(),
1890 // Checks that `bounds` contains exactly one element and reports appropriate
1891 // errors otherwise.
1892 fn one_bound_for_assoc_type<I>(
1894 all_candidates: impl Fn() -> I,
1895 ty_param_name: &str,
1896 assoc_name: ast::Ident,
1898 is_equality: Option<String>,
1899 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1901 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1903 let mut matching_candidates = all_candidates()
1904 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1906 let bound = match matching_candidates.next() {
1907 Some(bound) => bound,
1909 self.complain_about_assoc_type_not_found(
1915 return Err(ErrorReported);
1919 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1921 if let Some(bound2) = matching_candidates.next() {
1922 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1924 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
1925 let mut err = if is_equality.is_some() {
1926 // More specific Error Index entry.
1931 "ambiguous associated type `{}` in bounds of `{}`",
1940 "ambiguous associated type `{}` in bounds of `{}`",
1945 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1947 let mut where_bounds = vec![];
1948 for bound in bounds {
1949 let bound_span = self
1951 .associated_items(bound.def_id())
1953 item.kind == ty::AssocKind::Type
1954 && self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1956 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1958 if let Some(bound_span) = bound_span {
1962 "ambiguous `{}` from `{}`",
1964 bound.print_only_trait_path(),
1967 if let Some(constraint) = &is_equality {
1968 where_bounds.push(format!(
1969 " T: {trait}::{assoc} = {constraint}",
1970 trait=bound.print_only_trait_path(),
1972 constraint=constraint,
1975 err.span_suggestion(
1977 "use fully qualified syntax to disambiguate",
1981 bound.print_only_trait_path(),
1984 Applicability::MaybeIncorrect,
1989 "associated type `{}` could derive from `{}`",
1991 bound.print_only_trait_path(),
1995 if !where_bounds.is_empty() {
1997 "consider introducing a new type parameter `T` and adding `where` constraints:\
1998 \n where\n T: {},\n{}",
2000 where_bounds.join(",\n"),
2004 if !where_bounds.is_empty() {
2005 return Err(ErrorReported);
2011 fn complain_about_assoc_type_not_found<I>(
2013 all_candidates: impl Fn() -> I,
2014 ty_param_name: &str,
2015 assoc_name: ast::Ident,
2018 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2020 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2021 // valid span, so we point at the whole path segment instead.
2022 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2023 let mut err = struct_span_err!(
2027 "associated type `{}` not found for `{}`",
2032 let all_candidate_names: Vec<_> = all_candidates()
2033 .map(|r| self.tcx().associated_items(r.def_id()))
2036 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2040 if let (Some(suggested_name), true) = (
2041 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2042 assoc_name.span != DUMMY_SP,
2044 err.span_suggestion(
2046 "there is an associated type with a similar name",
2047 suggested_name.to_string(),
2048 Applicability::MaybeIncorrect,
2051 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2057 // Create a type from a path to an associated type.
2058 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2059 // and item_segment is the path segment for `D`. We return a type and a def for
2061 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2062 // parameter or `Self`.
2063 pub fn associated_path_to_ty(
2065 hir_ref_id: hir::HirId,
2069 assoc_segment: &hir::PathSegment<'_>,
2070 permit_variants: bool,
2071 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2072 let tcx = self.tcx();
2073 let assoc_ident = assoc_segment.ident;
2075 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2077 // Check if we have an enum variant.
2078 let mut variant_resolution = None;
2079 if let ty::Adt(adt_def, _) = qself_ty.kind {
2080 if adt_def.is_enum() {
2081 let variant_def = adt_def
2084 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2085 if let Some(variant_def) = variant_def {
2086 if permit_variants {
2087 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2088 self.prohibit_generics(slice::from_ref(assoc_segment));
2089 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2091 variant_resolution = Some(variant_def.def_id);
2097 // Find the type of the associated item, and the trait where the associated
2098 // item is declared.
2099 let bound = match (&qself_ty.kind, qself_res) {
2100 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2101 // `Self` in an impl of a trait -- we have a concrete self type and a
2103 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2104 Some(trait_ref) => trait_ref,
2106 // A cycle error occurred, most likely.
2107 return Err(ErrorReported);
2111 self.one_bound_for_assoc_type(
2112 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2119 (&ty::Param(_), Res::SelfTy(Some(param_did), None))
2120 | (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
2121 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
2124 if variant_resolution.is_some() {
2125 // Variant in type position
2126 let msg = format!("expected type, found variant `{}`", assoc_ident);
2127 tcx.sess.span_err(span, &msg);
2128 } else if qself_ty.is_enum() {
2129 let mut err = struct_span_err!(
2133 "no variant named `{}` found for enum `{}`",
2138 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2139 if let Some(suggested_name) = find_best_match_for_name(
2140 adt_def.variants.iter().map(|variant| &variant.ident.name),
2141 &assoc_ident.as_str(),
2144 err.span_suggestion(
2146 "there is a variant with a similar name",
2147 suggested_name.to_string(),
2148 Applicability::MaybeIncorrect,
2153 format!("variant not found in `{}`", qself_ty),
2157 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2158 let sp = tcx.sess.source_map().def_span(sp);
2159 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2163 } else if !qself_ty.references_error() {
2164 // Don't print `TyErr` to the user.
2165 self.report_ambiguous_associated_type(
2167 &qself_ty.to_string(),
2172 return Err(ErrorReported);
2176 let trait_did = bound.def_id();
2177 let (assoc_ident, def_scope) =
2178 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2180 .associated_items(trait_did)
2181 .find(|i| Namespace::from(i.kind) == Namespace::Type && i.ident.modern() == assoc_ident)
2182 .expect("missing associated type");
2184 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2185 let ty = self.normalize_ty(span, ty);
2187 let kind = DefKind::AssocTy;
2188 if !item.vis.is_accessible_from(def_scope, tcx) {
2189 let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
2190 tcx.sess.span_err(span, &msg);
2192 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2194 if let Some(variant_def_id) = variant_resolution {
2195 let mut err = tcx.struct_span_lint_hir(
2196 AMBIGUOUS_ASSOCIATED_ITEMS,
2199 "ambiguous associated item",
2202 let mut could_refer_to = |kind: DefKind, def_id, also| {
2203 let note_msg = format!(
2204 "`{}` could{} refer to {} defined here",
2209 err.span_note(tcx.def_span(def_id), ¬e_msg);
2211 could_refer_to(DefKind::Variant, variant_def_id, "");
2212 could_refer_to(kind, item.def_id, " also");
2214 err.span_suggestion(
2216 "use fully-qualified syntax",
2217 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2218 Applicability::MachineApplicable,
2223 Ok((ty, kind, item.def_id))
2229 opt_self_ty: Option<Ty<'tcx>>,
2231 trait_segment: &hir::PathSegment<'_>,
2232 item_segment: &hir::PathSegment<'_>,
2234 let tcx = self.tcx();
2236 let trait_def_id = tcx.parent(item_def_id).unwrap();
2238 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2240 let self_ty = if let Some(ty) = opt_self_ty {
2243 let path_str = tcx.def_path_str(trait_def_id);
2245 let def_id = self.item_def_id();
2247 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2249 let parent_def_id = def_id
2250 .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
2251 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
2253 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2255 // If the trait in segment is the same as the trait defining the item,
2256 // use the `<Self as ..>` syntax in the error.
2257 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2258 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2260 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2266 self.report_ambiguous_associated_type(
2270 item_segment.ident.name,
2272 return tcx.types.err;
2275 debug!("qpath_to_ty: self_type={:?}", self_ty);
2277 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2279 let item_substs = self.create_substs_for_associated_item(
2287 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2289 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2292 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2296 let mut has_err = false;
2297 for segment in segments {
2298 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2299 for arg in segment.generic_args().args {
2300 let (span, kind) = match arg {
2301 hir::GenericArg::Lifetime(lt) => {
2307 (lt.span, "lifetime")
2309 hir::GenericArg::Type(ty) => {
2317 hir::GenericArg::Const(ct) => {
2325 let mut err = struct_span_err!(
2329 "{} arguments are not allowed for this type",
2332 err.span_label(span, format!("{} argument not allowed", kind));
2334 if err_for_lt && err_for_ty && err_for_ct {
2338 for binding in segment.generic_args().bindings {
2340 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2347 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2348 let mut err = struct_span_err!(
2352 "associated type bindings are not allowed here"
2354 err.span_label(span, "associated type not allowed here").emit();
2357 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2358 pub fn def_ids_for_value_path_segments(
2360 segments: &[hir::PathSegment<'_>],
2361 self_ty: Option<Ty<'tcx>>,
2365 // We need to extract the type parameters supplied by the user in
2366 // the path `path`. Due to the current setup, this is a bit of a
2367 // tricky-process; the problem is that resolve only tells us the
2368 // end-point of the path resolution, and not the intermediate steps.
2369 // Luckily, we can (at least for now) deduce the intermediate steps
2370 // just from the end-point.
2372 // There are basically five cases to consider:
2374 // 1. Reference to a constructor of a struct:
2376 // struct Foo<T>(...)
2378 // In this case, the parameters are declared in the type space.
2380 // 2. Reference to a constructor of an enum variant:
2382 // enum E<T> { Foo(...) }
2384 // In this case, the parameters are defined in the type space,
2385 // but may be specified either on the type or the variant.
2387 // 3. Reference to a fn item or a free constant:
2391 // In this case, the path will again always have the form
2392 // `a::b::foo::<T>` where only the final segment should have
2393 // type parameters. However, in this case, those parameters are
2394 // declared on a value, and hence are in the `FnSpace`.
2396 // 4. Reference to a method or an associated constant:
2398 // impl<A> SomeStruct<A> {
2402 // Here we can have a path like
2403 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2404 // may appear in two places. The penultimate segment,
2405 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2406 // final segment, `foo::<B>` contains parameters in fn space.
2408 // The first step then is to categorize the segments appropriately.
2410 let tcx = self.tcx();
2412 assert!(!segments.is_empty());
2413 let last = segments.len() - 1;
2415 let mut path_segs = vec![];
2418 // Case 1. Reference to a struct constructor.
2419 DefKind::Ctor(CtorOf::Struct, ..) => {
2420 // Everything but the final segment should have no
2421 // parameters at all.
2422 let generics = tcx.generics_of(def_id);
2423 // Variant and struct constructors use the
2424 // generics of their parent type definition.
2425 let generics_def_id = generics.parent.unwrap_or(def_id);
2426 path_segs.push(PathSeg(generics_def_id, last));
2429 // Case 2. Reference to a variant constructor.
2430 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2431 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2432 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2433 debug_assert!(adt_def.is_enum());
2435 } else if last >= 1 && segments[last - 1].args.is_some() {
2436 // Everything but the penultimate segment should have no
2437 // parameters at all.
2438 let mut def_id = def_id;
2440 // `DefKind::Ctor` -> `DefKind::Variant`
2441 if let DefKind::Ctor(..) = kind {
2442 def_id = tcx.parent(def_id).unwrap()
2445 // `DefKind::Variant` -> `DefKind::Enum`
2446 let enum_def_id = tcx.parent(def_id).unwrap();
2447 (enum_def_id, last - 1)
2449 // FIXME: lint here recommending `Enum::<...>::Variant` form
2450 // instead of `Enum::Variant::<...>` form.
2452 // Everything but the final segment should have no
2453 // parameters at all.
2454 let generics = tcx.generics_of(def_id);
2455 // Variant and struct constructors use the
2456 // generics of their parent type definition.
2457 (generics.parent.unwrap_or(def_id), last)
2459 path_segs.push(PathSeg(generics_def_id, index));
2462 // Case 3. Reference to a top-level value.
2463 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2464 path_segs.push(PathSeg(def_id, last));
2467 // Case 4. Reference to a method or associated const.
2468 DefKind::Method | DefKind::AssocConst => {
2469 if segments.len() >= 2 {
2470 let generics = tcx.generics_of(def_id);
2471 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2473 path_segs.push(PathSeg(def_id, last));
2476 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2479 debug!("path_segs = {:?}", path_segs);
2484 // Check a type `Path` and convert it to a `Ty`.
2487 opt_self_ty: Option<Ty<'tcx>>,
2488 path: &hir::Path<'_>,
2489 permit_variants: bool,
2491 let tcx = self.tcx();
2494 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2495 path.res, opt_self_ty, path.segments
2498 let span = path.span;
2500 Res::Def(DefKind::OpaqueTy, did) => {
2501 // Check for desugared `impl Trait`.
2502 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2503 let item_segment = path.segments.split_last().unwrap();
2504 self.prohibit_generics(item_segment.1);
2505 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2506 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2508 Res::Def(DefKind::Enum, did)
2509 | Res::Def(DefKind::TyAlias, did)
2510 | Res::Def(DefKind::Struct, did)
2511 | Res::Def(DefKind::Union, did)
2512 | Res::Def(DefKind::ForeignTy, did) => {
2513 assert_eq!(opt_self_ty, None);
2514 self.prohibit_generics(path.segments.split_last().unwrap().1);
2515 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2517 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2518 // Convert "variant type" as if it were a real type.
2519 // The resulting `Ty` is type of the variant's enum for now.
2520 assert_eq!(opt_self_ty, None);
2523 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2524 let generic_segs: FxHashSet<_> =
2525 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2526 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2528 if !generic_segs.contains(&index) { Some(seg) } else { None }
2532 let PathSeg(def_id, index) = path_segs.last().unwrap();
2533 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2535 Res::Def(DefKind::TyParam, def_id) => {
2536 assert_eq!(opt_self_ty, None);
2537 self.prohibit_generics(path.segments);
2539 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2540 let item_id = tcx.hir().get_parent_node(hir_id);
2541 let item_def_id = tcx.hir().local_def_id(item_id);
2542 let generics = tcx.generics_of(item_def_id);
2543 let index = generics.param_def_id_to_index[&def_id];
2544 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2546 Res::SelfTy(Some(_), None) => {
2547 // `Self` in trait or type alias.
2548 assert_eq!(opt_self_ty, None);
2549 self.prohibit_generics(path.segments);
2550 tcx.types.self_param
2552 Res::SelfTy(_, Some(def_id)) => {
2553 // `Self` in impl (we know the concrete type).
2554 assert_eq!(opt_self_ty, None);
2555 self.prohibit_generics(path.segments);
2556 // Try to evaluate any array length constants.
2557 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2559 Res::Def(DefKind::AssocTy, def_id) => {
2560 debug_assert!(path.segments.len() >= 2);
2561 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2566 &path.segments[path.segments.len() - 2],
2567 path.segments.last().unwrap(),
2570 Res::PrimTy(prim_ty) => {
2571 assert_eq!(opt_self_ty, None);
2572 self.prohibit_generics(path.segments);
2574 hir::PrimTy::Bool => tcx.types.bool,
2575 hir::PrimTy::Char => tcx.types.char,
2576 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2577 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2578 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2579 hir::PrimTy::Str => tcx.mk_str(),
2583 self.set_tainted_by_errors();
2584 return self.tcx().types.err;
2586 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2590 /// Parses the programmer's textual representation of a type into our
2591 /// internal notion of a type.
2592 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2593 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2595 let tcx = self.tcx();
2597 let result_ty = match ast_ty.kind {
2598 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2599 hir::TyKind::Ptr(ref mt) => {
2600 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2602 hir::TyKind::Rptr(ref region, ref mt) => {
2603 let r = self.ast_region_to_region(region, None);
2604 debug!("ast_ty_to_ty: r={:?}", r);
2605 let t = self.ast_ty_to_ty(&mt.ty);
2606 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2608 hir::TyKind::Never => tcx.types.never,
2609 hir::TyKind::Tup(ref fields) => {
2610 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2612 hir::TyKind::BareFn(ref bf) => {
2613 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2614 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl, &[], None))
2616 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2617 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2619 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2620 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2621 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2622 self.res_to_ty(opt_self_ty, path, false)
2624 hir::TyKind::Def(item_id, ref lifetimes) => {
2625 let did = tcx.hir().local_def_id(item_id.id);
2626 self.impl_trait_ty_to_ty(did, lifetimes)
2628 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2629 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2630 let ty = self.ast_ty_to_ty(qself);
2632 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2637 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2638 .map(|(ty, _, _)| ty)
2639 .unwrap_or(tcx.types.err)
2641 hir::TyKind::Array(ref ty, ref length) => {
2642 let length = self.ast_const_to_const(length, tcx.types.usize);
2643 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2644 self.normalize_ty(ast_ty.span, array_ty)
2646 hir::TyKind::Typeof(ref _e) => {
2651 "`typeof` is a reserved keyword but unimplemented"
2653 .span_label(ast_ty.span, "reserved keyword")
2658 hir::TyKind::Infer => {
2659 // Infer also appears as the type of arguments or return
2660 // values in a ExprKind::Closure, or as
2661 // the type of local variables. Both of these cases are
2662 // handled specially and will not descend into this routine.
2663 self.ty_infer(None, ast_ty.span)
2665 hir::TyKind::Err => tcx.types.err,
2668 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2670 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2674 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2675 pub fn const_param_def_id(&self, expr: &hir::Expr<'_>) -> Option<DefId> {
2676 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2677 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2678 let expr = match &expr.kind {
2679 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2680 block.expr.as_ref().unwrap()
2686 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2687 Res::Def(DefKind::ConstParam, did) => Some(did),
2694 pub fn ast_const_to_const(
2696 ast_const: &hir::AnonConst,
2698 ) -> &'tcx ty::Const<'tcx> {
2699 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2701 let tcx = self.tcx();
2702 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2704 let expr = &tcx.hir().body(ast_const.body).value;
2706 let lit_input = match expr.kind {
2707 hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2708 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => match expr.kind {
2709 hir::ExprKind::Lit(ref lit) => {
2710 Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2717 if let Some(lit_input) = lit_input {
2718 // If an error occurred, ignore that it's a literal and leave reporting the error up to
2720 if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
2725 let kind = if let Some(def_id) = self.const_param_def_id(expr) {
2726 // Find the name and index of the const parameter by indexing the generics of the
2727 // parent item and construct a `ParamConst`.
2728 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2729 let item_id = tcx.hir().get_parent_node(hir_id);
2730 let item_def_id = tcx.hir().local_def_id(item_id);
2731 let generics = tcx.generics_of(item_def_id);
2732 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2733 let name = tcx.hir().name(hir_id);
2734 ty::ConstKind::Param(ty::ParamConst::new(index, name))
2736 ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id), None)
2738 tcx.mk_const(ty::Const { val: kind, ty })
2741 pub fn impl_trait_ty_to_ty(
2744 lifetimes: &[hir::GenericArg<'_>],
2746 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2747 let tcx = self.tcx();
2749 let generics = tcx.generics_of(def_id);
2751 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2752 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2753 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2754 // Our own parameters are the resolved lifetimes.
2756 GenericParamDefKind::Lifetime => {
2757 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2758 self.ast_region_to_region(lifetime, None).into()
2766 // Replace all parent lifetimes with `'static`.
2768 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2769 _ => tcx.mk_param_from_def(param),
2773 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2775 let ty = tcx.mk_opaque(def_id, substs);
2776 debug!("impl_trait_ty_to_ty: {}", ty);
2780 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2782 hir::TyKind::Infer if expected_ty.is_some() => {
2783 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2784 expected_ty.unwrap()
2786 _ => self.ast_ty_to_ty(ty),
2792 unsafety: hir::Unsafety,
2794 decl: &hir::FnDecl<'_>,
2795 generic_params: &[hir::GenericParam<'_>],
2796 ident_span: Option<Span>,
2797 ) -> ty::PolyFnSig<'tcx> {
2800 let tcx = self.tcx();
2802 // We proactively collect all the infered type params to emit a single error per fn def.
2803 let mut visitor = PlaceholderHirTyCollector::default();
2804 for ty in decl.inputs {
2805 visitor.visit_ty(ty);
2807 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2808 let output_ty = match decl.output {
2809 hir::FunctionRetTy::Return(ref output) => {
2810 visitor.visit_ty(output);
2811 self.ast_ty_to_ty(output)
2813 hir::FunctionRetTy::DefaultReturn(..) => tcx.mk_unit(),
2816 debug!("ty_of_fn: output_ty={:?}", output_ty);
2819 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2821 if !self.allow_ty_infer() {
2822 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2823 // only want to emit an error complaining about them if infer types (`_`) are not
2824 // allowed. `allow_ty_infer` gates this behavior.
2825 crate::collect::placeholder_type_error(
2827 ident_span.map(|sp| sp.shrink_to_hi()).unwrap_or(DUMMY_SP),
2830 ident_span.is_some(),
2834 // Find any late-bound regions declared in return type that do
2835 // not appear in the arguments. These are not well-formed.
2838 // for<'a> fn() -> &'a str <-- 'a is bad
2839 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2840 let inputs = bare_fn_ty.inputs();
2841 let late_bound_in_args =
2842 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2843 let output = bare_fn_ty.output();
2844 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2845 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2846 let lifetime_name = match *br {
2847 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2848 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2850 let mut err = struct_span_err!(
2854 "return type references {} \
2855 which is not constrained by the fn input types",
2858 if let ty::BrAnon(_) = *br {
2859 // The only way for an anonymous lifetime to wind up
2860 // in the return type but **also** be unconstrained is
2861 // if it only appears in "associated types" in the
2862 // input. See #47511 for an example. In this case,
2863 // though we can easily give a hint that ought to be
2866 "lifetimes appearing in an associated type \
2867 are not considered constrained",
2876 /// Given the bounds on an object, determines what single region bound (if any) we can
2877 /// use to summarize this type. The basic idea is that we will use the bound the user
2878 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2879 /// for region bounds. It may be that we can derive no bound at all, in which case
2880 /// we return `None`.
2881 fn compute_object_lifetime_bound(
2884 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2885 ) -> Option<ty::Region<'tcx>> // if None, use the default
2887 let tcx = self.tcx();
2889 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2891 // No explicit region bound specified. Therefore, examine trait
2892 // bounds and see if we can derive region bounds from those.
2893 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2895 // If there are no derived region bounds, then report back that we
2896 // can find no region bound. The caller will use the default.
2897 if derived_region_bounds.is_empty() {
2901 // If any of the derived region bounds are 'static, that is always
2903 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2904 return Some(tcx.lifetimes.re_static);
2907 // Determine whether there is exactly one unique region in the set
2908 // of derived region bounds. If so, use that. Otherwise, report an
2910 let r = derived_region_bounds[0];
2911 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2916 "ambiguous lifetime bound, explicit lifetime bound required"
2924 /// Collects together a list of bounds that are applied to some type,
2925 /// after they've been converted into `ty` form (from the HIR
2926 /// representations). These lists of bounds occur in many places in
2930 /// trait Foo: Bar + Baz { }
2931 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2933 /// fn foo<T: Bar + Baz>() { }
2934 /// ^^^^^^^^^ bounding the type parameter `T`
2936 /// impl dyn Bar + Baz
2937 /// ^^^^^^^^^ bounding the forgotten dynamic type
2940 /// Our representation is a bit mixed here -- in some cases, we
2941 /// include the self type (e.g., `trait_bounds`) but in others we do
2942 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2943 pub struct Bounds<'tcx> {
2944 /// A list of region bounds on the (implicit) self type. So if you
2945 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2946 /// the `T` is not explicitly included).
2947 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2949 /// A list of trait bounds. So if you had `T: Debug` this would be
2950 /// `T: Debug`. Note that the self-type is explicit here.
2951 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2953 /// A list of projection equality bounds. So if you had `T:
2954 /// Iterator<Item = u32>` this would include `<T as
2955 /// Iterator>::Item => u32`. Note that the self-type is explicit
2957 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2959 /// `Some` if there is *no* `?Sized` predicate. The `span`
2960 /// is the location in the source of the `T` declaration which can
2961 /// be cited as the source of the `T: Sized` requirement.
2962 pub implicitly_sized: Option<Span>,
2965 impl<'tcx> Bounds<'tcx> {
2966 /// Converts a bounds list into a flat set of predicates (like
2967 /// where-clauses). Because some of our bounds listings (e.g.,
2968 /// regions) don't include the self-type, you must supply the
2969 /// self-type here (the `param_ty` parameter).
2974 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2975 // If it could be sized, and is, add the `Sized` predicate.
2976 let sized_predicate = self.implicitly_sized.and_then(|span| {
2977 tcx.lang_items().sized_trait().map(|sized| {
2978 let trait_ref = ty::Binder::bind(ty::TraitRef {
2980 substs: tcx.mk_substs_trait(param_ty, &[]),
2982 (trait_ref.to_predicate(), span)
2991 .map(|&(region_bound, span)| {
2992 // Account for the binder being introduced below; no need to shift `param_ty`
2993 // because, at present at least, it either only refers to early-bound regions,
2994 // or it's a generic associated type that deliberately has escaping bound vars.
2995 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2996 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2997 (ty::Binder::bind(outlives).to_predicate(), span)
3002 .map(|&(bound_trait_ref, span)| (bound_trait_ref.to_predicate(), span)),
3005 self.projection_bounds
3007 .map(|&(projection, span)| (projection.to_predicate(), span)),