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::collect::PlaceholderHirTyCollector;
7 use crate::middle::lang_items::SizedTraitLangItem;
8 use crate::middle::resolve_lifetime as rl;
9 use crate::namespace::Namespace;
10 use crate::require_c_abi_if_c_variadic;
11 use crate::util::common::ErrorReported;
12 use errors::{Applicability, DiagnosticId};
13 use rustc::hir::intravisit::Visitor;
14 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
16 use rustc::traits::error_reporting::report_object_safety_error;
17 use rustc::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
18 use rustc::ty::wf::object_region_bounds;
19 use rustc::ty::{self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
20 use rustc::ty::{GenericParamDef, GenericParamDefKind};
21 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_hir::def::{CtorOf, DefKind, Res};
24 use rustc_hir::def_id::DefId;
26 use rustc_hir::{ExprKind, GenericArg, GenericArgs};
27 use rustc_span::symbol::sym;
28 use rustc_span::{MultiSpan, Span, DUMMY_SP};
29 use rustc_target::spec::abi;
30 use smallvec::SmallVec;
32 use syntax::errors::pluralize;
33 use syntax::feature_gate::feature_err;
34 use syntax::util::lev_distance::find_best_match_for_name;
36 use std::collections::BTreeSet;
40 use rustc_error_codes::*;
43 pub struct PathSeg(pub DefId, pub usize);
45 pub trait AstConv<'tcx> {
46 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
48 fn item_def_id(&self) -> Option<DefId>;
50 /// Returns predicates in scope of the form `X: Foo`, where `X` is
51 /// a type parameter `X` with the given id `def_id`. This is a
52 /// subset of the full set of predicates.
54 /// This is used for one specific purpose: resolving "short-hand"
55 /// associated type references like `T::Item`. In principle, we
56 /// would do that by first getting the full set of predicates in
57 /// scope and then filtering down to find those that apply to `T`,
58 /// but this can lead to cycle errors. The problem is that we have
59 /// to do this resolution *in order to create the predicates in
60 /// the first place*. Hence, we have this "special pass".
61 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
63 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
64 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
65 -> Option<ty::Region<'tcx>>;
67 /// Returns the type to use when a type is omitted.
68 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
70 /// Returns `true` if `_` is allowed in type signatures in the current context.
71 fn allow_ty_infer(&self) -> bool;
73 /// Returns the const to use when a const is omitted.
77 param: Option<&ty::GenericParamDef>,
79 ) -> &'tcx Const<'tcx>;
81 /// Projecting an associated type from a (potentially)
82 /// higher-ranked trait reference is more complicated, because of
83 /// the possibility of late-bound regions appearing in the
84 /// associated type binding. This is not legal in function
85 /// signatures for that reason. In a function body, we can always
86 /// handle it because we can use inference variables to remove the
87 /// late-bound regions.
88 fn projected_ty_from_poly_trait_ref(
92 item_segment: &hir::PathSegment<'_>,
93 poly_trait_ref: ty::PolyTraitRef<'tcx>,
96 /// Normalize an associated type coming from the user.
97 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
99 /// Invoked when we encounter an error from some prior pass
100 /// (e.g., resolve) that is translated into a ty-error. This is
101 /// used to help suppress derived errors typeck might otherwise
103 fn set_tainted_by_errors(&self);
105 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
108 pub enum SizedByDefault {
113 struct ConvertedBinding<'a, 'tcx> {
114 item_name: ast::Ident,
115 kind: ConvertedBindingKind<'a, 'tcx>,
119 enum ConvertedBindingKind<'a, 'tcx> {
121 Constraint(&'a [hir::GenericBound<'a>]),
125 enum GenericArgPosition {
127 Value, // e.g., functions
131 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
132 pub fn ast_region_to_region(
134 lifetime: &hir::Lifetime,
135 def: Option<&ty::GenericParamDef>,
136 ) -> ty::Region<'tcx> {
137 let tcx = self.tcx();
138 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap());
140 let r = match tcx.named_region(lifetime.hir_id) {
141 Some(rl::Region::Static) => tcx.lifetimes.re_static,
143 Some(rl::Region::LateBound(debruijn, id, _)) => {
144 let name = lifetime_name(id);
145 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
148 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
149 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
152 Some(rl::Region::EarlyBound(index, id, _)) => {
153 let name = lifetime_name(id);
154 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
157 Some(rl::Region::Free(scope, id)) => {
158 let name = lifetime_name(id);
159 tcx.mk_region(ty::ReFree(ty::FreeRegion {
161 bound_region: ty::BrNamed(id, name),
164 // (*) -- not late-bound, won't change
168 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
169 // This indicates an illegal lifetime
170 // elision. `resolve_lifetime` should have
171 // reported an error in this case -- but if
172 // not, let's error out.
173 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
175 // Supply some dummy value. We don't have an
176 // `re_error`, annoyingly, so use `'static`.
177 tcx.lifetimes.re_static
182 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
187 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
188 /// returns an appropriate set of substitutions for this particular reference to `I`.
189 pub fn ast_path_substs_for_ty(
193 item_segment: &hir::PathSegment<'_>,
194 ) -> SubstsRef<'tcx> {
195 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
199 item_segment.generic_args(),
200 item_segment.infer_args,
204 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
209 /// Report error if there is an explicit type parameter when using `impl Trait`.
212 seg: &hir::PathSegment<'_>,
213 generics: &ty::Generics,
215 let explicit = !seg.infer_args;
216 let impl_trait = generics.params.iter().any(|param| match param.kind {
217 ty::GenericParamDefKind::Type {
218 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
224 if explicit && impl_trait {
229 .filter_map(|arg| match arg {
230 GenericArg::Type(_) => Some(arg.span()),
233 .collect::<Vec<_>>();
235 let mut err = struct_span_err! {
239 "cannot provide explicit generic arguments when `impl Trait` is \
240 used in argument position"
244 err.span_label(span, "explicit generic argument not allowed");
253 /// Checks that the correct number of generic arguments have been provided.
254 /// Used specifically for function calls.
255 pub fn check_generic_arg_count_for_call(
259 seg: &hir::PathSegment<'_>,
260 is_method_call: bool,
262 let empty_args = hir::GenericArgs::none();
263 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
264 Self::check_generic_arg_count(
268 if let Some(ref args) = seg.args { args } else { &empty_args },
269 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
270 def.parent.is_none() && def.has_self, // `has_self`
271 seg.infer_args || suppress_mismatch, // `infer_args`
276 /// Checks that the correct number of generic arguments have been provided.
277 /// This is used both for datatypes and function calls.
278 fn check_generic_arg_count(
282 args: &hir::GenericArgs<'_>,
283 position: GenericArgPosition,
286 ) -> (bool, Option<Vec<Span>>) {
287 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
288 // that lifetimes will proceed types. So it suffices to check the number of each generic
289 // arguments in order to validate them with respect to the generic parameters.
290 let param_counts = def.own_counts();
291 let arg_counts = args.own_counts();
292 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
294 let mut defaults: ty::GenericParamCount = Default::default();
295 for param in &def.params {
297 GenericParamDefKind::Lifetime => {}
298 GenericParamDefKind::Type { has_default, .. } => {
299 defaults.types += has_default as usize
301 GenericParamDefKind::Const => {
302 // FIXME(const_generics:defaults)
307 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
308 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
311 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
312 let mut reported_late_bound_region_err = None;
313 if !infer_lifetimes {
314 if let Some(span_late) = def.has_late_bound_regions {
315 let msg = "cannot specify lifetime arguments explicitly \
316 if late bound lifetime parameters are present";
317 let note = "the late bound lifetime parameter is introduced here";
318 let span = args.args[0].span();
319 if position == GenericArgPosition::Value
320 && arg_counts.lifetimes != param_counts.lifetimes
322 let mut err = tcx.sess.struct_span_err(span, msg);
323 err.span_note(span_late, note);
325 reported_late_bound_region_err = Some(true);
327 let mut multispan = MultiSpan::from_span(span);
328 multispan.push_span_label(span_late, note.to_string());
330 lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
335 reported_late_bound_region_err = Some(false);
340 let check_kind_count = |kind, required, permitted, provided, offset| {
342 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
343 kind, required, permitted, provided, offset
345 // We enforce the following: `required` <= `provided` <= `permitted`.
346 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
347 // For other kinds (i.e., types), `permitted` may be greater than `required`.
348 if required <= provided && provided <= permitted {
349 return (reported_late_bound_region_err.unwrap_or(false), None);
352 // Unfortunately lifetime and type parameter mismatches are typically styled
353 // differently in diagnostics, which means we have a few cases to consider here.
354 let (bound, quantifier) = if required != permitted {
355 if provided < required {
356 (required, "at least ")
358 // provided > permitted
359 (permitted, "at most ")
365 let mut potential_assoc_types: Option<Vec<Span>> = None;
366 let (spans, label) = if required == permitted && provided > permitted {
367 // In the case when the user has provided too many arguments,
368 // we want to point to the unexpected arguments.
369 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
371 .map(|arg| arg.span())
373 potential_assoc_types = Some(spans.clone());
374 (spans, format!("unexpected {} argument", kind))
379 "expected {}{} {} argument{}",
388 let mut err = tcx.sess.struct_span_err_with_code(
391 "wrong number of {} arguments: expected {}{}, found {}",
392 kind, quantifier, bound, provided,
394 DiagnosticId::Error("E0107".into()),
397 err.span_label(span, label.as_str());
402 provided > required, // `suppress_error`
403 potential_assoc_types,
407 if reported_late_bound_region_err.is_none()
408 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
412 param_counts.lifetimes,
413 param_counts.lifetimes,
414 arg_counts.lifetimes,
418 // FIXME(const_generics:defaults)
419 if !infer_args || arg_counts.consts > param_counts.consts {
425 arg_counts.lifetimes + arg_counts.types,
428 // Note that type errors are currently be emitted *after* const errors.
429 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
433 param_counts.types - defaults.types - has_self as usize,
434 param_counts.types - has_self as usize,
436 arg_counts.lifetimes,
439 (reported_late_bound_region_err.unwrap_or(false), None)
443 /// Creates the relevant generic argument substitutions
444 /// corresponding to a set of generic parameters. This is a
445 /// rather complex function. Let us try to explain the role
446 /// of each of its parameters:
448 /// To start, we are given the `def_id` of the thing we are
449 /// creating the substitutions for, and a partial set of
450 /// substitutions `parent_substs`. In general, the substitutions
451 /// for an item begin with substitutions for all the "parents" of
452 /// that item -- e.g., for a method it might include the
453 /// parameters from the impl.
455 /// Therefore, the method begins by walking down these parents,
456 /// starting with the outermost parent and proceed inwards until
457 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
458 /// first to see if the parent's substitutions are listed in there. If so,
459 /// we can append those and move on. Otherwise, it invokes the
460 /// three callback functions:
462 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
463 /// generic arguments that were given to that parent from within
464 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
465 /// might refer to the trait `Foo`, and the arguments might be
466 /// `[T]`. The boolean value indicates whether to infer values
467 /// for arguments whose values were not explicitly provided.
468 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
469 /// instantiate a `GenericArg`.
470 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
471 /// creates a suitable inference variable.
472 pub fn create_substs_for_generic_args<'b>(
475 parent_substs: &[subst::GenericArg<'tcx>],
477 self_ty: Option<Ty<'tcx>>,
478 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
479 provided_kind: impl Fn(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
480 mut inferred_kind: impl FnMut(
481 Option<&[subst::GenericArg<'tcx>]>,
484 ) -> subst::GenericArg<'tcx>,
485 ) -> SubstsRef<'tcx> {
486 // Collect the segments of the path; we need to substitute arguments
487 // for parameters throughout the entire path (wherever there are
488 // generic parameters).
489 let mut parent_defs = tcx.generics_of(def_id);
490 let count = parent_defs.count();
491 let mut stack = vec![(def_id, parent_defs)];
492 while let Some(def_id) = parent_defs.parent {
493 parent_defs = tcx.generics_of(def_id);
494 stack.push((def_id, parent_defs));
497 // We manually build up the substitution, rather than using convenience
498 // methods in `subst.rs`, so that we can iterate over the arguments and
499 // parameters in lock-step linearly, instead of trying to match each pair.
500 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
502 // Iterate over each segment of the path.
503 while let Some((def_id, defs)) = stack.pop() {
504 let mut params = defs.params.iter().peekable();
506 // If we have already computed substitutions for parents, we can use those directly.
507 while let Some(¶m) = params.peek() {
508 if let Some(&kind) = parent_substs.get(param.index as usize) {
516 // `Self` is handled first, unless it's been handled in `parent_substs`.
518 if let Some(¶m) = params.peek() {
519 if param.index == 0 {
520 if let GenericParamDefKind::Type { .. } = param.kind {
524 .unwrap_or_else(|| inferred_kind(None, param, true)),
532 // Check whether this segment takes generic arguments and the user has provided any.
533 let (generic_args, infer_args) = args_for_def_id(def_id);
536 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
539 // We're going to iterate through the generic arguments that the user
540 // provided, matching them with the generic parameters we expect.
541 // Mismatches can occur as a result of elided lifetimes, or for malformed
542 // input. We try to handle both sensibly.
543 match (args.peek(), params.peek()) {
544 (Some(&arg), Some(¶m)) => {
545 match (arg, ¶m.kind) {
546 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
547 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
548 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
549 substs.push(provided_kind(param, arg));
553 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
554 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
555 // We expected a lifetime argument, but got a type or const
556 // argument. That means we're inferring the lifetimes.
557 substs.push(inferred_kind(None, param, infer_args));
561 // We expected one kind of parameter, but the user provided
562 // another. This is an error, but we need to handle it
563 // gracefully so we can report sensible errors.
564 // In this case, we're simply going to infer this argument.
570 // We should never be able to reach this point with well-formed input.
571 // Getting to this point means the user supplied more arguments than
572 // there are parameters.
575 (None, Some(¶m)) => {
576 // If there are fewer arguments than parameters, it means
577 // we're inferring the remaining arguments.
578 substs.push(inferred_kind(Some(&substs), param, infer_args));
582 (None, None) => break,
587 tcx.intern_substs(&substs)
590 /// Given the type/lifetime/const arguments provided to some path (along with
591 /// an implicit `Self`, if this is a trait reference), returns the complete
592 /// set of substitutions. This may involve applying defaulted type parameters.
593 /// Also returns back constriants on associated types.
598 /// T: std::ops::Index<usize, Output = u32>
599 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
602 /// 1. The `self_ty` here would refer to the type `T`.
603 /// 2. The path in question is the path to the trait `std::ops::Index`,
604 /// which will have been resolved to a `def_id`
605 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
606 /// parameters are returned in the `SubstsRef`, the associated type bindings like
607 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
609 /// Note that the type listing given here is *exactly* what the user provided.
611 /// For (generic) associated types
614 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
617 /// We have the parent substs are the substs for the parent trait:
618 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
619 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
620 /// lists: `[Vec<u8>, u8, 'a]`.
621 fn create_substs_for_ast_path<'a>(
625 parent_substs: &[subst::GenericArg<'tcx>],
626 generic_args: &'a hir::GenericArgs<'_>,
628 self_ty: Option<Ty<'tcx>>,
629 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
630 // If the type is parameterized by this region, then replace this
631 // region with the current anon region binding (in other words,
632 // whatever & would get replaced with).
634 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
636 def_id, self_ty, generic_args
639 let tcx = self.tcx();
640 let generic_params = tcx.generics_of(def_id);
642 if generic_params.has_self {
643 if generic_params.parent.is_some() {
644 // The parent is a trait so it should have at least one subst
645 // for the `Self` type.
646 assert!(!parent_substs.is_empty())
648 // This item (presumably a trait) needs a self-type.
649 assert!(self_ty.is_some());
652 assert!(self_ty.is_none() && parent_substs.is_empty());
655 let (_, potential_assoc_types) = Self::check_generic_arg_count(
660 GenericArgPosition::Type,
665 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
666 let default_needs_object_self = |param: &ty::GenericParamDef| {
667 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
668 if is_object && has_default {
669 let self_param = tcx.types.self_param;
670 if tcx.at(span).type_of(param.def_id).walk().any(|ty| ty == self_param) {
671 // There is no suitable inference default for a type parameter
672 // that references self, in an object type.
681 let mut missing_type_params = vec![];
682 let substs = Self::create_substs_for_generic_args(
688 // Provide the generic args, and whether types should be inferred.
689 |_| (Some(generic_args), infer_args),
690 // Provide substitutions for parameters for which (valid) arguments have been provided.
691 |param, arg| match (¶m.kind, arg) {
692 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
693 self.ast_region_to_region(<, Some(param)).into()
695 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
696 self.ast_ty_to_ty(&ty).into()
698 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
699 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
703 // Provide substitutions for parameters for which arguments are inferred.
704 |substs, param, infer_args| {
706 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
707 GenericParamDefKind::Type { has_default, .. } => {
708 if !infer_args && has_default {
709 // No type parameter provided, but a default exists.
711 // If we are converting an object type, then the
712 // `Self` parameter is unknown. However, some of the
713 // other type parameters may reference `Self` in their
714 // defaults. This will lead to an ICE if we are not
716 if default_needs_object_self(param) {
717 missing_type_params.push(param.name.to_string());
720 // This is a default type parameter.
723 tcx.at(span).type_of(param.def_id).subst_spanned(
731 } else if infer_args {
732 // No type parameters were provided, we can infer all.
734 if !default_needs_object_self(param) { Some(param) } else { None };
735 self.ty_infer(param, span).into()
737 // We've already errored above about the mismatch.
741 GenericParamDefKind::Const => {
742 // FIXME(const_generics:defaults)
744 // No const parameters were provided, we can infer all.
745 let ty = tcx.at(span).type_of(param.def_id);
746 self.ct_infer(ty, Some(param), span).into()
748 // We've already errored above about the mismatch.
749 tcx.consts.err.into()
756 self.complain_about_missing_type_params(
760 generic_args.args.is_empty(),
763 // Convert associated-type bindings or constraints into a separate vector.
764 // Example: Given this:
766 // T: Iterator<Item = u32>
768 // The `T` is passed in as a self-type; the `Item = u32` is
769 // not a "type parameter" of the `Iterator` trait, but rather
770 // a restriction on `<T as Iterator>::Item`, so it is passed
772 let assoc_bindings = generic_args
776 let kind = match binding.kind {
777 hir::TypeBindingKind::Equality { ref ty } => {
778 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
780 hir::TypeBindingKind::Constraint { ref bounds } => {
781 ConvertedBindingKind::Constraint(bounds)
784 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
789 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
790 generic_params, self_ty, substs
793 (substs, assoc_bindings, potential_assoc_types)
796 crate fn create_substs_for_associated_item(
801 item_segment: &hir::PathSegment<'_>,
802 parent_substs: SubstsRef<'tcx>,
803 ) -> SubstsRef<'tcx> {
804 if tcx.generics_of(item_def_id).params.is_empty() {
805 self.prohibit_generics(slice::from_ref(item_segment));
809 self.create_substs_for_ast_path(
813 item_segment.generic_args(),
814 item_segment.infer_args,
821 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
822 /// the type parameter's name as a placeholder.
823 fn complain_about_missing_type_params(
825 missing_type_params: Vec<String>,
828 empty_generic_args: bool,
830 if missing_type_params.is_empty() {
834 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
835 let mut err = struct_span_err!(
839 "the type parameter{} {} must be explicitly specified",
840 pluralize!(missing_type_params.len()),
844 self.tcx().def_span(def_id),
846 "type parameter{} {} must be specified for this",
847 pluralize!(missing_type_params.len()),
851 let mut suggested = false;
852 if let (Ok(snippet), true) = (
853 self.tcx().sess.source_map().span_to_snippet(span),
854 // Don't suggest setting the type params if there are some already: the order is
855 // tricky to get right and the user will already know what the syntax is.
858 if snippet.ends_with('>') {
859 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
860 // we would have to preserve the right order. For now, as clearly the user is
861 // aware of the syntax, we do nothing.
863 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
864 // least we can clue them to the correct syntax `Iterator<Type>`.
868 "set the type parameter{plural} to the desired type{plural}",
869 plural = pluralize!(missing_type_params.len()),
871 format!("{}<{}>", snippet, missing_type_params.join(", ")),
872 Applicability::HasPlaceholders,
881 "missing reference{} to {}",
882 pluralize!(missing_type_params.len()),
888 "because of the default `Self` reference, type parameters must be \
889 specified on object types"
894 /// Instantiates the path for the given trait reference, assuming that it's
895 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
896 /// The type _cannot_ be a type other than a trait type.
898 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
899 /// are disallowed. Otherwise, they are pushed onto the vector given.
900 pub fn instantiate_mono_trait_ref(
902 trait_ref: &hir::TraitRef<'_>,
904 ) -> ty::TraitRef<'tcx> {
905 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
907 self.ast_path_to_mono_trait_ref(
909 trait_ref.trait_def_id(),
911 trait_ref.path.segments.last().unwrap(),
915 /// The given trait-ref must actually be a trait.
916 pub(super) fn instantiate_poly_trait_ref_inner(
918 trait_ref: &hir::TraitRef<'_>,
921 bounds: &mut Bounds<'tcx>,
923 ) -> Option<Vec<Span>> {
924 let trait_def_id = trait_ref.trait_def_id();
926 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
928 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
930 let path_span = if let [segment] = &trait_ref.path.segments[..] {
931 // FIXME: `trait_ref.path.span` can point to a full path with multiple
932 // segments, even though `trait_ref.path.segments` is of length `1`. Work
933 // around that bug here, even though it should be fixed elsewhere.
934 // This would otherwise cause an invalid suggestion. For an example, look at
935 // `src/test/ui/issues/issue-28344.rs`.
940 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
944 trait_ref.path.segments.last().unwrap(),
946 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
948 bounds.trait_bounds.push((poly_trait_ref, span));
950 let mut dup_bindings = FxHashMap::default();
951 for binding in &assoc_bindings {
952 // Specify type to assert that error was already reported in `Err` case.
953 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
954 trait_ref.hir_ref_id,
962 // Okay to ignore `Err` because of `ErrorReported` (see above).
966 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
967 trait_ref, bounds, poly_trait_ref
969 potential_assoc_types
972 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
973 /// a full trait reference. The resulting trait reference is returned. This may also generate
974 /// auxiliary bounds, which are added to `bounds`.
979 /// poly_trait_ref = Iterator<Item = u32>
983 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
985 /// **A note on binders:** against our usual convention, there is an implied bounder around
986 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
987 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
988 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
989 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
991 pub fn instantiate_poly_trait_ref(
993 poly_trait_ref: &hir::PolyTraitRef<'_>,
995 bounds: &mut Bounds<'tcx>,
996 ) -> Option<Vec<Span>> {
997 self.instantiate_poly_trait_ref_inner(
998 &poly_trait_ref.trait_ref,
1006 fn ast_path_to_mono_trait_ref(
1009 trait_def_id: DefId,
1011 trait_segment: &hir::PathSegment<'_>,
1012 ) -> ty::TraitRef<'tcx> {
1013 let (substs, assoc_bindings, _) =
1014 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1015 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
1016 ty::TraitRef::new(trait_def_id, substs)
1019 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1020 /// an error and attempt to build a reasonable structured suggestion.
1021 fn complain_about_internal_fn_trait(
1024 trait_def_id: DefId,
1025 trait_segment: &'a hir::PathSegment<'a>,
1027 let trait_def = self.tcx().trait_def(trait_def_id);
1029 if !self.tcx().features().unboxed_closures
1030 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1032 // For now, require that parenthetical notation be used only with `Fn()` etc.
1033 let (msg, sugg) = if trait_def.paren_sugar {
1035 "the precise format of `Fn`-family traits' type parameters is subject to \
1039 trait_segment.ident,
1043 .and_then(|args| args.args.get(0))
1044 .and_then(|arg| match arg {
1045 hir::GenericArg::Type(ty) => {
1046 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1050 .unwrap_or_else(|| "()".to_string()),
1055 .filter_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1056 (true, hir::TypeBindingKind::Equality { ty }) => {
1057 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1062 .unwrap_or_else(|| "()".to_string()),
1066 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1068 let sess = &self.tcx().sess.parse_sess;
1069 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1070 if let Some(sugg) = sugg {
1071 let msg = "use parenthetical notation instead";
1072 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1078 fn create_substs_for_ast_trait_ref<'a>(
1081 trait_def_id: DefId,
1083 trait_segment: &'a hir::PathSegment<'a>,
1084 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
1085 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1087 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1089 self.create_substs_for_ast_path(
1093 trait_segment.generic_args(),
1094 trait_segment.infer_args,
1099 fn trait_defines_associated_type_named(
1101 trait_def_id: DefId,
1102 assoc_name: ast::Ident,
1104 self.tcx().associated_items(trait_def_id).any(|item| {
1105 item.kind == ty::AssocKind::Type
1106 && self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
1110 // Returns `true` if a bounds list includes `?Sized`.
1111 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1112 let tcx = self.tcx();
1114 // Try to find an unbound in bounds.
1115 let mut unbound = None;
1116 for ab in ast_bounds {
1117 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1118 if unbound.is_none() {
1119 unbound = Some(&ptr.trait_ref);
1125 "type parameter has more than one relaxed default \
1126 bound, only one is supported"
1132 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1135 // FIXME(#8559) currently requires the unbound to be built-in.
1136 if let Ok(kind_id) = kind_id {
1137 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1140 "default bound relaxed for a type parameter, but \
1141 this does nothing because the given bound is not \
1142 a default; only `?Sized` is supported",
1147 _ if kind_id.is_ok() => {
1150 // No lang item for `Sized`, so we can't add it as a bound.
1157 /// This helper takes a *converted* parameter type (`param_ty`)
1158 /// and an *unconverted* list of bounds:
1161 /// fn foo<T: Debug>
1162 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1164 /// `param_ty`, in ty form
1167 /// It adds these `ast_bounds` into the `bounds` structure.
1169 /// **A note on binders:** there is an implied binder around
1170 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1171 /// for more details.
1175 ast_bounds: &[hir::GenericBound<'_>],
1176 bounds: &mut Bounds<'tcx>,
1178 let mut trait_bounds = Vec::new();
1179 let mut region_bounds = Vec::new();
1181 for ast_bound in ast_bounds {
1183 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1184 trait_bounds.push(b)
1186 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1187 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1191 for bound in trait_bounds {
1192 let _ = self.instantiate_poly_trait_ref(bound, param_ty, bounds);
1195 bounds.region_bounds.extend(
1196 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1200 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1201 /// The self-type for the bounds is given by `param_ty`.
1206 /// fn foo<T: Bar + Baz>() { }
1207 /// ^ ^^^^^^^^^ ast_bounds
1211 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1212 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1213 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1215 /// `span` should be the declaration size of the parameter.
1216 pub fn compute_bounds(
1219 ast_bounds: &[hir::GenericBound<'_>],
1220 sized_by_default: SizedByDefault,
1223 let mut bounds = Bounds::default();
1225 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1226 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1228 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1229 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1237 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1240 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1241 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1242 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1243 fn add_predicates_for_ast_type_binding(
1245 hir_ref_id: hir::HirId,
1246 trait_ref: ty::PolyTraitRef<'tcx>,
1247 binding: &ConvertedBinding<'_, 'tcx>,
1248 bounds: &mut Bounds<'tcx>,
1250 dup_bindings: &mut FxHashMap<DefId, Span>,
1252 ) -> Result<(), ErrorReported> {
1253 let tcx = self.tcx();
1256 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1257 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1258 // subtle in the event that `T` is defined in a supertrait of
1259 // `SomeTrait`, because in that case we need to upcast.
1261 // That is, consider this case:
1264 // trait SubTrait: SuperTrait<int> { }
1265 // trait SuperTrait<A> { type T; }
1267 // ... B: SubTrait<T = foo> ...
1270 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1272 // Find any late-bound regions declared in `ty` that are not
1273 // declared in the trait-ref. These are not well-formed.
1277 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1278 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1279 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1280 let late_bound_in_trait_ref =
1281 tcx.collect_constrained_late_bound_regions(&trait_ref);
1282 let late_bound_in_ty =
1283 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1284 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1285 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1286 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1287 let br_name = match *br {
1288 ty::BrNamed(_, name) => name,
1292 "anonymous bound region {:?} in binding but not trait ref",
1301 "binding for associated type `{}` references lifetime `{}`, \
1302 which does not appear in the trait input types",
1312 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1313 // Simple case: X is defined in the current trait.
1316 // Otherwise, we have to walk through the supertraits to find
1318 self.one_bound_for_assoc_type(
1319 || traits::supertraits(tcx, trait_ref),
1320 &trait_ref.print_only_trait_path().to_string(),
1323 match binding.kind {
1324 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1330 let (assoc_ident, def_scope) =
1331 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1333 .associated_items(candidate.def_id())
1334 .find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident)
1335 .expect("missing associated type");
1337 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1338 let msg = format!("associated type `{}` is private", binding.item_name);
1339 tcx.sess.span_err(binding.span, &msg);
1341 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1345 .entry(assoc_ty.def_id)
1346 .and_modify(|prev_span| {
1351 "the value of the associated type `{}` (from trait `{}`) \
1352 is already specified",
1354 tcx.def_path_str(assoc_ty.container.id())
1356 .span_label(binding.span, "re-bound here")
1357 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1360 .or_insert(binding.span);
1363 match binding.kind {
1364 ConvertedBindingKind::Equality(ref ty) => {
1365 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1366 // the "projection predicate" for:
1368 // `<T as Iterator>::Item = u32`
1369 bounds.projection_bounds.push((
1370 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1371 projection_ty: ty::ProjectionTy::from_ref_and_name(
1381 ConvertedBindingKind::Constraint(ast_bounds) => {
1382 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1384 // `<T as Iterator>::Item: Debug`
1386 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1387 // parameter to have a skipped binder.
1388 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1389 self.add_bounds(param_ty, ast_bounds, bounds);
1399 item_segment: &hir::PathSegment<'_>,
1401 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1402 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1405 fn conv_object_ty_poly_trait_ref(
1408 trait_bounds: &[hir::PolyTraitRef<'_>],
1409 lifetime: &hir::Lifetime,
1411 let tcx = self.tcx();
1413 let mut bounds = Bounds::default();
1414 let mut potential_assoc_types = Vec::new();
1415 let dummy_self = self.tcx().types.trait_object_dummy_self;
1416 for trait_bound in trait_bounds.iter().rev() {
1417 let cur_potential_assoc_types =
1418 self.instantiate_poly_trait_ref(trait_bound, dummy_self, &mut bounds);
1419 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1422 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1423 // is used and no 'maybe' bounds are used.
1424 let expanded_traits =
1425 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1426 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1427 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1428 if regular_traits.len() > 1 {
1429 let first_trait = ®ular_traits[0];
1430 let additional_trait = ®ular_traits[1];
1431 let mut err = struct_span_err!(
1433 additional_trait.bottom().1,
1435 "only auto traits can be used as additional traits in a trait object"
1437 additional_trait.label_with_exp_info(
1439 "additional non-auto trait",
1442 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1446 if regular_traits.is_empty() && auto_traits.is_empty() {
1447 span_err!(tcx.sess, span, E0224, "at least one trait is required for an object type");
1448 return tcx.types.err;
1451 // Check that there are no gross object safety violations;
1452 // most importantly, that the supertraits don't contain `Self`,
1454 for item in ®ular_traits {
1455 let object_safety_violations =
1456 tcx.astconv_object_safety_violations(item.trait_ref().def_id());
1457 if !object_safety_violations.is_empty() {
1458 report_object_safety_error(
1461 item.trait_ref().def_id(),
1462 object_safety_violations,
1465 return tcx.types.err;
1469 // Use a `BTreeSet` to keep output in a more consistent order.
1470 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1472 let regular_traits_refs_spans = bounds
1475 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1477 for (base_trait_ref, span) in regular_traits_refs_spans {
1478 for trait_ref in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1480 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1484 ty::Predicate::Trait(pred) => {
1485 associated_types.entry(span).or_default().extend(
1486 tcx.associated_items(pred.def_id())
1487 .filter(|item| item.kind == ty::AssocKind::Type)
1488 .map(|item| item.def_id),
1491 ty::Predicate::Projection(pred) => {
1492 // A `Self` within the original bound will be substituted with a
1493 // `trait_object_dummy_self`, so check for that.
1494 let references_self = pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1496 // If the projection output contains `Self`, force the user to
1497 // elaborate it explicitly to avoid a lot of complexity.
1499 // The "classicaly useful" case is the following:
1501 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1506 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1507 // but actually supporting that would "expand" to an infinitely-long type
1508 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1510 // Instead, we force the user to write
1511 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1512 // the discussion in #56288 for alternatives.
1513 if !references_self {
1514 // Include projections defined on supertraits.
1515 bounds.projection_bounds.push((pred, span));
1523 for (projection_bound, _) in &bounds.projection_bounds {
1524 for (_, def_ids) in &mut associated_types {
1525 def_ids.remove(&projection_bound.projection_def_id());
1529 self.complain_about_missing_associated_types(
1531 potential_assoc_types,
1535 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1536 // `dyn Trait + Send`.
1537 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1538 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1539 debug!("regular_traits: {:?}", regular_traits);
1540 debug!("auto_traits: {:?}", auto_traits);
1542 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1543 // removing the dummy `Self` type (`trait_object_dummy_self`).
1544 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1545 if trait_ref.self_ty() != dummy_self {
1546 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1547 // which picks up non-supertraits where clauses - but also, the object safety
1548 // completely ignores trait aliases, which could be object safety hazards. We
1549 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1550 // disabled. (#66420)
1551 tcx.sess.delay_span_bug(
1554 "trait_ref_to_existential called on {:?} with non-dummy Self",
1559 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1562 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1563 let existential_trait_refs = regular_traits
1565 .map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
1566 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1567 bound.map_bound(|b| {
1568 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1569 ty::ExistentialProjection {
1571 item_def_id: b.projection_ty.item_def_id,
1572 substs: trait_ref.substs,
1577 // Calling `skip_binder` is okay because the predicates are re-bound.
1578 let regular_trait_predicates = existential_trait_refs
1579 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1580 let auto_trait_predicates = auto_traits
1582 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1583 let mut v = regular_trait_predicates
1584 .chain(auto_trait_predicates)
1586 existential_projections
1587 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1589 .collect::<SmallVec<[_; 8]>>();
1590 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1592 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1594 // Use explicitly-specified region bound.
1595 let region_bound = if !lifetime.is_elided() {
1596 self.ast_region_to_region(lifetime, None)
1598 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1599 if tcx.named_region(lifetime.hir_id).is_some() {
1600 self.ast_region_to_region(lifetime, None)
1602 self.re_infer(None, span).unwrap_or_else(|| {
1607 "the lifetime bound for this object type cannot be deduced \
1608 from context; please supply an explicit bound"
1610 tcx.lifetimes.re_static
1615 debug!("region_bound: {:?}", region_bound);
1617 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1618 debug!("trait_object_type: {:?}", ty);
1622 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1623 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1624 /// same trait bound have the same name (as they come from different super-traits), we instead
1625 /// emit a generic note suggesting using a `where` clause to constraint instead.
1626 fn complain_about_missing_associated_types(
1628 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1629 potential_assoc_types: Vec<Span>,
1630 trait_bounds: &[hir::PolyTraitRef<'_>],
1632 if !associated_types.values().any(|v| v.len() > 0) {
1635 let tcx = self.tcx();
1636 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1637 // appropriate one, but this should be handled earlier in the span assignment.
1638 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1640 .map(|(span, def_ids)| {
1641 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1644 let mut names = vec![];
1646 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1647 // `issue-22560.rs`.
1648 let mut trait_bound_spans: Vec<Span> = vec![];
1649 for (span, items) in &associated_types {
1650 if !items.is_empty() {
1651 trait_bound_spans.push(*span);
1653 for assoc_item in items {
1654 let trait_def_id = assoc_item.container.id();
1656 "`{}` (from trait `{}`)",
1658 tcx.def_path_str(trait_def_id),
1663 match (&potential_assoc_types[..], &trait_bounds) {
1664 ([], [bound]) => match &bound.trait_ref.path.segments[..] {
1665 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1666 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1667 // around that bug here, even though it should be fixed elsewhere.
1668 // This would otherwise cause an invalid suggestion. For an example, look at
1669 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1671 // error[E0191]: the value of the associated type `Output`
1672 // (from trait `std::ops::BitXor`) must be specified
1673 // --> $DIR/issue-28344.rs:4:17
1675 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1676 // | ^^^^^^ help: specify the associated type:
1677 // | `BitXor<Output = Type>`
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::bitor<Output = Type>`
1688 [segment] if segment.args.is_none() => {
1689 trait_bound_spans = vec![segment.ident.span];
1690 associated_types = associated_types
1692 .map(|(_, items)| (segment.ident.span, items))
1700 trait_bound_spans.sort();
1701 let mut err = struct_span_err!(
1705 "the value of the associated type{} {} must be specified",
1706 pluralize!(names.len()),
1709 let mut suggestions = vec![];
1710 let mut types_count = 0;
1711 let mut where_constraints = vec![];
1712 for (span, assoc_items) in &associated_types {
1713 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1714 for item in assoc_items {
1716 *names.entry(item.ident.name).or_insert(0) += 1;
1718 let mut dupes = false;
1719 for item in assoc_items {
1720 let prefix = if names[&item.ident.name] > 1 {
1721 let trait_def_id = item.container.id();
1723 format!("{}::", tcx.def_path_str(trait_def_id))
1727 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1728 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1731 if potential_assoc_types.len() == assoc_items.len() {
1732 // Only suggest when the amount of missing associated types equals the number of
1733 // extra type arguments present, as that gives us a relatively high confidence
1734 // that the user forgot to give the associtated type's name. The canonical
1735 // example would be trying to use `Iterator<isize>` instead of
1736 // `Iterator<Item = isize>`.
1737 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1738 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1739 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1742 } else if let (Ok(snippet), false) =
1743 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1746 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1747 let code = if snippet.ends_with(">") {
1748 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1749 // suggest, but at least we can clue them to the correct syntax
1750 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1752 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1754 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1755 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1756 format!("{}<{}>", snippet, types.join(", "))
1758 suggestions.push((*span, code));
1760 where_constraints.push(*span);
1763 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1764 using the fully-qualified path to the associated types";
1765 if !where_constraints.is_empty() && suggestions.is_empty() {
1766 // If there are duplicates associated type names and a single trait bound do not
1767 // use structured suggestion, it means that there are multiple super-traits with
1768 // the same associated type name.
1769 err.help(where_msg);
1771 if suggestions.len() != 1 {
1772 // We don't need this label if there's an inline suggestion, show otherwise.
1773 for (span, assoc_items) in &associated_types {
1774 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1775 for item in assoc_items {
1777 *names.entry(item.ident.name).or_insert(0) += 1;
1779 let mut label = vec![];
1780 for item in assoc_items {
1781 let postfix = if names[&item.ident.name] > 1 {
1782 let trait_def_id = item.container.id();
1783 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1787 label.push(format!("`{}`{}", item.ident, postfix));
1789 if !label.is_empty() {
1793 "associated type{} {} must be specified",
1794 pluralize!(label.len()),
1801 if !suggestions.is_empty() {
1802 err.multipart_suggestion(
1803 &format!("specify the associated type{}", pluralize!(types_count)),
1805 Applicability::HasPlaceholders,
1807 if !where_constraints.is_empty() {
1808 err.span_help(where_constraints, where_msg);
1814 fn report_ambiguous_associated_type(
1821 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1822 if let (Some(_), Ok(snippet)) = (
1823 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1824 self.tcx().sess.source_map().span_to_snippet(span),
1826 err.span_suggestion(
1828 "you are looking for the module in `std`, not the primitive type",
1829 format!("std::{}", snippet),
1830 Applicability::MachineApplicable,
1833 err.span_suggestion(
1835 "use fully-qualified syntax",
1836 format!("<{} as {}>::{}", type_str, trait_str, name),
1837 Applicability::HasPlaceholders,
1843 // Search for a bound on a type parameter which includes the associated item
1844 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1845 // This function will fail if there are no suitable bounds or there is
1847 fn find_bound_for_assoc_item(
1849 ty_param_def_id: DefId,
1850 assoc_name: ast::Ident,
1852 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1853 let tcx = self.tcx();
1856 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1857 ty_param_def_id, assoc_name, span,
1860 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1862 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1864 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1865 let param_name = tcx.hir().ty_param_name(param_hir_id);
1866 self.one_bound_for_assoc_type(
1868 traits::transitive_bounds(
1870 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1873 ¶m_name.as_str(),
1880 // Checks that `bounds` contains exactly one element and reports appropriate
1881 // errors otherwise.
1882 fn one_bound_for_assoc_type<I>(
1884 all_candidates: impl Fn() -> I,
1885 ty_param_name: &str,
1886 assoc_name: ast::Ident,
1888 is_equality: Option<String>,
1889 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1891 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1893 let mut matching_candidates = all_candidates()
1894 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1896 let bound = match matching_candidates.next() {
1897 Some(bound) => bound,
1899 self.complain_about_assoc_type_not_found(
1905 return Err(ErrorReported);
1909 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1911 if let Some(bound2) = matching_candidates.next() {
1912 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1914 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
1915 let mut err = if is_equality.is_some() {
1916 // More specific Error Index entry.
1921 "ambiguous associated type `{}` in bounds of `{}`",
1930 "ambiguous associated type `{}` in bounds of `{}`",
1935 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1937 let mut where_bounds = vec![];
1938 for bound in bounds {
1939 let bound_span = self
1941 .associated_items(bound.def_id())
1943 item.kind == ty::AssocKind::Type
1944 && self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1946 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1948 if let Some(bound_span) = bound_span {
1952 "ambiguous `{}` from `{}`",
1954 bound.print_only_trait_path(),
1957 if let Some(constraint) = &is_equality {
1958 where_bounds.push(format!(
1959 " T: {trait}::{assoc} = {constraint}",
1960 trait=bound.print_only_trait_path(),
1962 constraint=constraint,
1965 err.span_suggestion(
1967 "use fully qualified syntax to disambiguate",
1971 bound.print_only_trait_path(),
1974 Applicability::MaybeIncorrect,
1979 "associated type `{}` could derive from `{}`",
1981 bound.print_only_trait_path(),
1985 if !where_bounds.is_empty() {
1987 "consider introducing a new type parameter `T` and adding `where` constraints:\
1988 \n where\n T: {},\n{}",
1990 where_bounds.join(",\n"),
1994 if !where_bounds.is_empty() {
1995 return Err(ErrorReported);
2001 fn complain_about_assoc_type_not_found<I>(
2003 all_candidates: impl Fn() -> I,
2004 ty_param_name: &str,
2005 assoc_name: ast::Ident,
2008 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2010 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2011 // valid span, so we point at the whole path segment instead.
2012 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2013 let mut err = struct_span_err!(
2017 "associated type `{}` not found for `{}`",
2022 let all_candidate_names: Vec<_> = all_candidates()
2023 .map(|r| self.tcx().associated_items(r.def_id()))
2026 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2030 if let (Some(suggested_name), true) = (
2031 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2032 assoc_name.span != DUMMY_SP,
2034 err.span_suggestion(
2036 "there is an associated type with a similar name",
2037 suggested_name.to_string(),
2038 Applicability::MaybeIncorrect,
2041 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2047 // Create a type from a path to an associated type.
2048 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2049 // and item_segment is the path segment for `D`. We return a type and a def for
2051 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2052 // parameter or `Self`.
2053 pub fn associated_path_to_ty(
2055 hir_ref_id: hir::HirId,
2059 assoc_segment: &hir::PathSegment<'_>,
2060 permit_variants: bool,
2061 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2062 let tcx = self.tcx();
2063 let assoc_ident = assoc_segment.ident;
2065 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2067 // Check if we have an enum variant.
2068 let mut variant_resolution = None;
2069 if let ty::Adt(adt_def, _) = qself_ty.kind {
2070 if adt_def.is_enum() {
2071 let variant_def = adt_def
2074 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2075 if let Some(variant_def) = variant_def {
2076 if permit_variants {
2077 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2078 self.prohibit_generics(slice::from_ref(assoc_segment));
2079 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2081 variant_resolution = Some(variant_def.def_id);
2087 // Find the type of the associated item, and the trait where the associated
2088 // item is declared.
2089 let bound = match (&qself_ty.kind, qself_res) {
2090 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2091 // `Self` in an impl of a trait -- we have a concrete self type and a
2093 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2094 Some(trait_ref) => trait_ref,
2096 // A cycle error occurred, most likely.
2097 return Err(ErrorReported);
2101 self.one_bound_for_assoc_type(
2102 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2109 (&ty::Param(_), Res::SelfTy(Some(param_did), None))
2110 | (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
2111 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
2114 if variant_resolution.is_some() {
2115 // Variant in type position
2116 let msg = format!("expected type, found variant `{}`", assoc_ident);
2117 tcx.sess.span_err(span, &msg);
2118 } else if qself_ty.is_enum() {
2119 let mut err = tcx.sess.struct_span_err(
2121 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
2124 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2125 if let Some(suggested_name) = find_best_match_for_name(
2126 adt_def.variants.iter().map(|variant| &variant.ident.name),
2127 &assoc_ident.as_str(),
2130 err.span_suggestion(
2132 "there is a variant with a similar name",
2133 suggested_name.to_string(),
2134 Applicability::MaybeIncorrect,
2139 format!("variant not found in `{}`", qself_ty),
2143 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2144 let sp = tcx.sess.source_map().def_span(sp);
2145 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2149 } else if !qself_ty.references_error() {
2150 // Don't print `TyErr` to the user.
2151 self.report_ambiguous_associated_type(
2153 &qself_ty.to_string(),
2158 return Err(ErrorReported);
2162 let trait_did = bound.def_id();
2163 let (assoc_ident, def_scope) =
2164 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2166 .associated_items(trait_did)
2167 .find(|i| Namespace::from(i.kind) == Namespace::Type && i.ident.modern() == assoc_ident)
2168 .expect("missing associated type");
2170 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2171 let ty = self.normalize_ty(span, ty);
2173 let kind = DefKind::AssocTy;
2174 if !item.vis.is_accessible_from(def_scope, tcx) {
2175 let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
2176 tcx.sess.span_err(span, &msg);
2178 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2180 if let Some(variant_def_id) = variant_resolution {
2181 let mut err = tcx.struct_span_lint_hir(
2182 AMBIGUOUS_ASSOCIATED_ITEMS,
2185 "ambiguous associated item",
2188 let mut could_refer_to = |kind: DefKind, def_id, also| {
2189 let note_msg = format!(
2190 "`{}` could{} refer to {} defined here",
2195 err.span_note(tcx.def_span(def_id), ¬e_msg);
2197 could_refer_to(DefKind::Variant, variant_def_id, "");
2198 could_refer_to(kind, item.def_id, " also");
2200 err.span_suggestion(
2202 "use fully-qualified syntax",
2203 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2204 Applicability::MachineApplicable,
2209 Ok((ty, kind, item.def_id))
2215 opt_self_ty: Option<Ty<'tcx>>,
2217 trait_segment: &hir::PathSegment<'_>,
2218 item_segment: &hir::PathSegment<'_>,
2220 let tcx = self.tcx();
2222 let trait_def_id = tcx.parent(item_def_id).unwrap();
2224 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2226 let self_ty = if let Some(ty) = opt_self_ty {
2229 let path_str = tcx.def_path_str(trait_def_id);
2231 let def_id = self.item_def_id();
2233 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2235 let parent_def_id = def_id
2236 .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
2237 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
2239 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2241 // If the trait in segment is the same as the trait defining the item,
2242 // use the `<Self as ..>` syntax in the error.
2243 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2244 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2246 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2252 self.report_ambiguous_associated_type(
2256 item_segment.ident.name,
2258 return tcx.types.err;
2261 debug!("qpath_to_ty: self_type={:?}", self_ty);
2263 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2265 let item_substs = self.create_substs_for_associated_item(
2273 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2275 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2278 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2282 let mut has_err = false;
2283 for segment in segments {
2284 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2285 for arg in segment.generic_args().args {
2286 let (span, kind) = match arg {
2287 hir::GenericArg::Lifetime(lt) => {
2293 (lt.span, "lifetime")
2295 hir::GenericArg::Type(ty) => {
2303 hir::GenericArg::Const(ct) => {
2311 let mut err = struct_span_err!(
2315 "{} arguments are not allowed for this type",
2318 err.span_label(span, format!("{} argument not allowed", kind));
2320 if err_for_lt && err_for_ty && err_for_ct {
2324 for binding in segment.generic_args().bindings {
2326 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2333 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2334 let mut err = struct_span_err!(
2338 "associated type bindings are not allowed here"
2340 err.span_label(span, "associated type not allowed here").emit();
2343 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2344 pub fn def_ids_for_value_path_segments(
2346 segments: &[hir::PathSegment<'_>],
2347 self_ty: Option<Ty<'tcx>>,
2351 // We need to extract the type parameters supplied by the user in
2352 // the path `path`. Due to the current setup, this is a bit of a
2353 // tricky-process; the problem is that resolve only tells us the
2354 // end-point of the path resolution, and not the intermediate steps.
2355 // Luckily, we can (at least for now) deduce the intermediate steps
2356 // just from the end-point.
2358 // There are basically five cases to consider:
2360 // 1. Reference to a constructor of a struct:
2362 // struct Foo<T>(...)
2364 // In this case, the parameters are declared in the type space.
2366 // 2. Reference to a constructor of an enum variant:
2368 // enum E<T> { Foo(...) }
2370 // In this case, the parameters are defined in the type space,
2371 // but may be specified either on the type or the variant.
2373 // 3. Reference to a fn item or a free constant:
2377 // In this case, the path will again always have the form
2378 // `a::b::foo::<T>` where only the final segment should have
2379 // type parameters. However, in this case, those parameters are
2380 // declared on a value, and hence are in the `FnSpace`.
2382 // 4. Reference to a method or an associated constant:
2384 // impl<A> SomeStruct<A> {
2388 // Here we can have a path like
2389 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2390 // may appear in two places. The penultimate segment,
2391 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2392 // final segment, `foo::<B>` contains parameters in fn space.
2394 // The first step then is to categorize the segments appropriately.
2396 let tcx = self.tcx();
2398 assert!(!segments.is_empty());
2399 let last = segments.len() - 1;
2401 let mut path_segs = vec![];
2404 // Case 1. Reference to a struct constructor.
2405 DefKind::Ctor(CtorOf::Struct, ..) => {
2406 // Everything but the final segment should have no
2407 // parameters at all.
2408 let generics = tcx.generics_of(def_id);
2409 // Variant and struct constructors use the
2410 // generics of their parent type definition.
2411 let generics_def_id = generics.parent.unwrap_or(def_id);
2412 path_segs.push(PathSeg(generics_def_id, last));
2415 // Case 2. Reference to a variant constructor.
2416 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2417 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2418 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2419 debug_assert!(adt_def.is_enum());
2421 } else if last >= 1 && segments[last - 1].args.is_some() {
2422 // Everything but the penultimate segment should have no
2423 // parameters at all.
2424 let mut def_id = def_id;
2426 // `DefKind::Ctor` -> `DefKind::Variant`
2427 if let DefKind::Ctor(..) = kind {
2428 def_id = tcx.parent(def_id).unwrap()
2431 // `DefKind::Variant` -> `DefKind::Enum`
2432 let enum_def_id = tcx.parent(def_id).unwrap();
2433 (enum_def_id, last - 1)
2435 // FIXME: lint here recommending `Enum::<...>::Variant` form
2436 // instead of `Enum::Variant::<...>` form.
2438 // Everything but the final segment should have no
2439 // parameters at all.
2440 let generics = tcx.generics_of(def_id);
2441 // Variant and struct constructors use the
2442 // generics of their parent type definition.
2443 (generics.parent.unwrap_or(def_id), last)
2445 path_segs.push(PathSeg(generics_def_id, index));
2448 // Case 3. Reference to a top-level value.
2449 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2450 path_segs.push(PathSeg(def_id, last));
2453 // Case 4. Reference to a method or associated const.
2454 DefKind::Method | DefKind::AssocConst => {
2455 if segments.len() >= 2 {
2456 let generics = tcx.generics_of(def_id);
2457 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2459 path_segs.push(PathSeg(def_id, last));
2462 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2465 debug!("path_segs = {:?}", path_segs);
2470 // Check a type `Path` and convert it to a `Ty`.
2473 opt_self_ty: Option<Ty<'tcx>>,
2474 path: &hir::Path<'_>,
2475 permit_variants: bool,
2477 let tcx = self.tcx();
2480 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2481 path.res, opt_self_ty, path.segments
2484 let span = path.span;
2486 Res::Def(DefKind::OpaqueTy, did) => {
2487 // Check for desugared `impl Trait`.
2488 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2489 let item_segment = path.segments.split_last().unwrap();
2490 self.prohibit_generics(item_segment.1);
2491 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2492 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2494 Res::Def(DefKind::Enum, did)
2495 | Res::Def(DefKind::TyAlias, did)
2496 | Res::Def(DefKind::Struct, did)
2497 | Res::Def(DefKind::Union, did)
2498 | Res::Def(DefKind::ForeignTy, did) => {
2499 assert_eq!(opt_self_ty, None);
2500 self.prohibit_generics(path.segments.split_last().unwrap().1);
2501 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2503 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2504 // Convert "variant type" as if it were a real type.
2505 // The resulting `Ty` is type of the variant's enum for now.
2506 assert_eq!(opt_self_ty, None);
2509 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2510 let generic_segs: FxHashSet<_> =
2511 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2512 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2514 if !generic_segs.contains(&index) { Some(seg) } else { None }
2518 let PathSeg(def_id, index) = path_segs.last().unwrap();
2519 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2521 Res::Def(DefKind::TyParam, def_id) => {
2522 assert_eq!(opt_self_ty, None);
2523 self.prohibit_generics(path.segments);
2525 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2526 let item_id = tcx.hir().get_parent_node(hir_id);
2527 let item_def_id = tcx.hir().local_def_id(item_id);
2528 let generics = tcx.generics_of(item_def_id);
2529 let index = generics.param_def_id_to_index[&def_id];
2530 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2532 Res::SelfTy(Some(_), None) => {
2533 // `Self` in trait or type alias.
2534 assert_eq!(opt_self_ty, None);
2535 self.prohibit_generics(path.segments);
2536 tcx.types.self_param
2538 Res::SelfTy(_, Some(def_id)) => {
2539 // `Self` in impl (we know the concrete type).
2540 assert_eq!(opt_self_ty, None);
2541 self.prohibit_generics(path.segments);
2542 // Try to evaluate any array length constants.
2543 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2545 Res::Def(DefKind::AssocTy, def_id) => {
2546 debug_assert!(path.segments.len() >= 2);
2547 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2552 &path.segments[path.segments.len() - 2],
2553 path.segments.last().unwrap(),
2556 Res::PrimTy(prim_ty) => {
2557 assert_eq!(opt_self_ty, None);
2558 self.prohibit_generics(path.segments);
2560 hir::PrimTy::Bool => tcx.types.bool,
2561 hir::PrimTy::Char => tcx.types.char,
2562 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2563 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2564 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2565 hir::PrimTy::Str => tcx.mk_str(),
2569 self.set_tainted_by_errors();
2570 return self.tcx().types.err;
2572 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2576 /// Parses the programmer's textual representation of a type into our
2577 /// internal notion of a type.
2578 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2579 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2581 let tcx = self.tcx();
2583 let result_ty = match ast_ty.kind {
2584 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2585 hir::TyKind::Ptr(ref mt) => {
2586 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2588 hir::TyKind::Rptr(ref region, ref mt) => {
2589 let r = self.ast_region_to_region(region, None);
2590 debug!("ast_ty_to_ty: r={:?}", r);
2591 let t = self.ast_ty_to_ty(&mt.ty);
2592 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2594 hir::TyKind::Never => tcx.types.never,
2595 hir::TyKind::Tup(ref fields) => {
2596 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2598 hir::TyKind::BareFn(ref bf) => {
2599 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2600 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl, &[], None))
2602 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2603 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2605 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2606 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2607 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2608 self.res_to_ty(opt_self_ty, path, false)
2610 hir::TyKind::Def(item_id, ref lifetimes) => {
2611 let did = tcx.hir().local_def_id(item_id.id);
2612 self.impl_trait_ty_to_ty(did, lifetimes)
2614 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2615 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2616 let ty = self.ast_ty_to_ty(qself);
2618 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2623 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2624 .map(|(ty, _, _)| ty)
2625 .unwrap_or(tcx.types.err)
2627 hir::TyKind::Array(ref ty, ref length) => {
2628 let length = self.ast_const_to_const(length, tcx.types.usize);
2629 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2630 self.normalize_ty(ast_ty.span, array_ty)
2632 hir::TyKind::Typeof(ref _e) => {
2637 "`typeof` is a reserved keyword but unimplemented"
2639 .span_label(ast_ty.span, "reserved keyword")
2644 hir::TyKind::Infer => {
2645 // Infer also appears as the type of arguments or return
2646 // values in a ExprKind::Closure, or as
2647 // the type of local variables. Both of these cases are
2648 // handled specially and will not descend into this routine.
2649 self.ty_infer(None, ast_ty.span)
2651 hir::TyKind::Err => tcx.types.err,
2654 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2656 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2660 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2661 pub fn const_param_def_id(&self, expr: &hir::Expr<'_>) -> Option<DefId> {
2662 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2663 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2664 let expr = match &expr.kind {
2665 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2666 block.expr.as_ref().unwrap()
2672 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2673 Res::Def(DefKind::ConstParam, did) => Some(did),
2680 pub fn ast_const_to_const(
2682 ast_const: &hir::AnonConst,
2684 ) -> &'tcx ty::Const<'tcx> {
2685 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2687 let tcx = self.tcx();
2688 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2690 let mut const_ = ty::Const {
2691 val: ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id)),
2695 let expr = &tcx.hir().body(ast_const.body).value;
2696 if let Some(def_id) = self.const_param_def_id(expr) {
2697 // Find the name and index of the const parameter by indexing the generics of the
2698 // parent item and construct a `ParamConst`.
2699 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2700 let item_id = tcx.hir().get_parent_node(hir_id);
2701 let item_def_id = tcx.hir().local_def_id(item_id);
2702 let generics = tcx.generics_of(item_def_id);
2703 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2704 let name = tcx.hir().name(hir_id);
2705 const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2708 tcx.mk_const(const_)
2711 pub fn impl_trait_ty_to_ty(
2714 lifetimes: &[hir::GenericArg<'_>],
2716 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2717 let tcx = self.tcx();
2719 let generics = tcx.generics_of(def_id);
2721 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2722 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2723 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2724 // Our own parameters are the resolved lifetimes.
2726 GenericParamDefKind::Lifetime => {
2727 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2728 self.ast_region_to_region(lifetime, None).into()
2736 // Replace all parent lifetimes with `'static`.
2738 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2739 _ => tcx.mk_param_from_def(param),
2743 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2745 let ty = tcx.mk_opaque(def_id, substs);
2746 debug!("impl_trait_ty_to_ty: {}", ty);
2750 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2752 hir::TyKind::Infer if expected_ty.is_some() => {
2753 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2754 expected_ty.unwrap()
2756 _ => self.ast_ty_to_ty(ty),
2762 unsafety: hir::Unsafety,
2764 decl: &hir::FnDecl<'_>,
2765 generic_params: &[hir::GenericParam<'_>],
2766 ident_span: Option<Span>,
2767 ) -> ty::PolyFnSig<'tcx> {
2770 let tcx = self.tcx();
2772 // We proactively collect all the infered type params to emit a single error per fn def.
2773 let mut visitor = PlaceholderHirTyCollector::default();
2774 for ty in decl.inputs {
2775 visitor.visit_ty(ty);
2777 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2778 let output_ty = match decl.output {
2779 hir::FunctionRetTy::Return(ref output) => {
2780 visitor.visit_ty(output);
2781 self.ast_ty_to_ty(output)
2783 hir::FunctionRetTy::DefaultReturn(..) => tcx.mk_unit(),
2786 debug!("ty_of_fn: output_ty={:?}", output_ty);
2789 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2791 if !self.allow_ty_infer() {
2792 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2793 // only want to emit an error complaining about them if infer types (`_`) are not
2794 // allowed. `allow_ty_infer` gates this behavior.
2795 crate::collect::placeholder_type_error(
2797 ident_span.unwrap_or(DUMMY_SP),
2800 ident_span.is_some(),
2804 // Find any late-bound regions declared in return type that do
2805 // not appear in the arguments. These are not well-formed.
2808 // for<'a> fn() -> &'a str <-- 'a is bad
2809 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2810 let inputs = bare_fn_ty.inputs();
2811 let late_bound_in_args =
2812 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2813 let output = bare_fn_ty.output();
2814 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2815 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2816 let lifetime_name = match *br {
2817 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2818 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2820 let mut err = struct_span_err!(
2824 "return type references {} \
2825 which is not constrained by the fn input types",
2828 if let ty::BrAnon(_) = *br {
2829 // The only way for an anonymous lifetime to wind up
2830 // in the return type but **also** be unconstrained is
2831 // if it only appears in "associated types" in the
2832 // input. See #47511 for an example. In this case,
2833 // though we can easily give a hint that ought to be
2836 "lifetimes appearing in an associated type \
2837 are not considered constrained",
2846 /// Given the bounds on an object, determines what single region bound (if any) we can
2847 /// use to summarize this type. The basic idea is that we will use the bound the user
2848 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2849 /// for region bounds. It may be that we can derive no bound at all, in which case
2850 /// we return `None`.
2851 fn compute_object_lifetime_bound(
2854 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2855 ) -> Option<ty::Region<'tcx>> // if None, use the default
2857 let tcx = self.tcx();
2859 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2861 // No explicit region bound specified. Therefore, examine trait
2862 // bounds and see if we can derive region bounds from those.
2863 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2865 // If there are no derived region bounds, then report back that we
2866 // can find no region bound. The caller will use the default.
2867 if derived_region_bounds.is_empty() {
2871 // If any of the derived region bounds are 'static, that is always
2873 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2874 return Some(tcx.lifetimes.re_static);
2877 // Determine whether there is exactly one unique region in the set
2878 // of derived region bounds. If so, use that. Otherwise, report an
2880 let r = derived_region_bounds[0];
2881 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2886 "ambiguous lifetime bound, explicit lifetime bound required"
2893 /// Collects together a list of bounds that are applied to some type,
2894 /// after they've been converted into `ty` form (from the HIR
2895 /// representations). These lists of bounds occur in many places in
2899 /// trait Foo: Bar + Baz { }
2900 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2902 /// fn foo<T: Bar + Baz>() { }
2903 /// ^^^^^^^^^ bounding the type parameter `T`
2905 /// impl dyn Bar + Baz
2906 /// ^^^^^^^^^ bounding the forgotten dynamic type
2909 /// Our representation is a bit mixed here -- in some cases, we
2910 /// include the self type (e.g., `trait_bounds`) but in others we do
2911 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2912 pub struct Bounds<'tcx> {
2913 /// A list of region bounds on the (implicit) self type. So if you
2914 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2915 /// the `T` is not explicitly included).
2916 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2918 /// A list of trait bounds. So if you had `T: Debug` this would be
2919 /// `T: Debug`. Note that the self-type is explicit here.
2920 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2922 /// A list of projection equality bounds. So if you had `T:
2923 /// Iterator<Item = u32>` this would include `<T as
2924 /// Iterator>::Item => u32`. Note that the self-type is explicit
2926 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2928 /// `Some` if there is *no* `?Sized` predicate. The `span`
2929 /// is the location in the source of the `T` declaration which can
2930 /// be cited as the source of the `T: Sized` requirement.
2931 pub implicitly_sized: Option<Span>,
2934 impl<'tcx> Bounds<'tcx> {
2935 /// Converts a bounds list into a flat set of predicates (like
2936 /// where-clauses). Because some of our bounds listings (e.g.,
2937 /// regions) don't include the self-type, you must supply the
2938 /// self-type here (the `param_ty` parameter).
2943 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2944 // If it could be sized, and is, add the `Sized` predicate.
2945 let sized_predicate = self.implicitly_sized.and_then(|span| {
2946 tcx.lang_items().sized_trait().map(|sized| {
2947 let trait_ref = ty::Binder::bind(ty::TraitRef {
2949 substs: tcx.mk_substs_trait(param_ty, &[]),
2951 (trait_ref.to_predicate(), span)
2960 .map(|&(region_bound, span)| {
2961 // Account for the binder being introduced below; no need to shift `param_ty`
2962 // because, at present at least, it either only refers to early-bound regions,
2963 // or it's a generic associated type that deliberately has escaping bound vars.
2964 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2965 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2966 (ty::Binder::bind(outlives).to_predicate(), span)
2971 .map(|&(bound_trait_ref, span)| (bound_trait_ref.to_predicate(), span)),
2974 self.projection_bounds
2976 .map(|&(projection, span)| (projection.to_predicate(), span)),