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;
6 use crate::hir::def::{CtorOf, DefKind, Res};
7 use crate::hir::def_id::DefId;
8 use crate::hir::intravisit::Visitor;
10 use crate::hir::{self, ExprKind, GenericArg, GenericArgs};
12 use crate::middle::lang_items::SizedTraitLangItem;
13 use crate::middle::resolve_lifetime as rl;
14 use crate::namespace::Namespace;
15 use crate::require_c_abi_if_c_variadic;
16 use crate::util::common::ErrorReported;
17 use errors::{Applicability, DiagnosticId};
18 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
20 use rustc::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
21 use rustc::ty::wf::object_region_bounds;
22 use rustc::ty::{self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
23 use rustc::ty::{GenericParamDef, GenericParamDefKind};
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_span::symbol::sym;
26 use rustc_span::{MultiSpan, Span, DUMMY_SP};
27 use rustc_target::spec::abi;
28 use smallvec::SmallVec;
30 use syntax::errors::pluralize;
31 use syntax::feature_gate::feature_err;
32 use syntax::util::lev_distance::find_best_match_for_name;
34 use std::collections::BTreeSet;
38 use rustc_error_codes::*;
41 pub struct PathSeg(pub DefId, pub usize);
43 pub trait AstConv<'tcx> {
44 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
46 fn item_def_id(&self) -> Option<DefId>;
48 /// Returns predicates in scope of the form `X: Foo`, where `X` is
49 /// a type parameter `X` with the given id `def_id`. This is a
50 /// subset of the full set of predicates.
52 /// This is used for one specific purpose: resolving "short-hand"
53 /// associated type references like `T::Item`. In principle, we
54 /// would do that by first getting the full set of predicates in
55 /// scope and then filtering down to find those that apply to `T`,
56 /// but this can lead to cycle errors. The problem is that we have
57 /// to do this resolution *in order to create the predicates in
58 /// the first place*. Hence, we have this "special pass".
59 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
61 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
62 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
63 -> Option<ty::Region<'tcx>>;
65 /// Returns the type to use when a type is omitted.
66 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
68 /// Returns `true` if `_` is allowed in type signatures in the current context.
69 fn allow_ty_infer(&self) -> bool;
71 /// Returns the const to use when a const is omitted.
75 param: Option<&ty::GenericParamDef>,
77 ) -> &'tcx Const<'tcx>;
79 /// Projecting an associated type from a (potentially)
80 /// higher-ranked trait reference is more complicated, because of
81 /// the possibility of late-bound regions appearing in the
82 /// associated type binding. This is not legal in function
83 /// signatures for that reason. In a function body, we can always
84 /// handle it because we can use inference variables to remove the
85 /// late-bound regions.
86 fn projected_ty_from_poly_trait_ref(
90 item_segment: &hir::PathSegment<'_>,
91 poly_trait_ref: ty::PolyTraitRef<'tcx>,
94 /// Normalize an associated type coming from the user.
95 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
97 /// Invoked when we encounter an error from some prior pass
98 /// (e.g., resolve) that is translated into a ty-error. This is
99 /// used to help suppress derived errors typeck might otherwise
101 fn set_tainted_by_errors(&self);
103 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
106 pub enum SizedByDefault {
111 struct ConvertedBinding<'a, 'tcx> {
112 item_name: ast::Ident,
113 kind: ConvertedBindingKind<'a, 'tcx>,
117 enum ConvertedBindingKind<'a, 'tcx> {
119 Constraint(&'a [hir::GenericBound<'a>]),
123 enum GenericArgPosition {
125 Value, // e.g., functions
129 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
130 pub fn ast_region_to_region(
132 lifetime: &hir::Lifetime,
133 def: Option<&ty::GenericParamDef>,
134 ) -> ty::Region<'tcx> {
135 let tcx = self.tcx();
136 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id).unwrap());
138 let r = match tcx.named_region(lifetime.hir_id) {
139 Some(rl::Region::Static) => tcx.lifetimes.re_static,
141 Some(rl::Region::LateBound(debruijn, id, _)) => {
142 let name = lifetime_name(id);
143 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
146 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
147 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
150 Some(rl::Region::EarlyBound(index, id, _)) => {
151 let name = lifetime_name(id);
152 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
155 Some(rl::Region::Free(scope, id)) => {
156 let name = lifetime_name(id);
157 tcx.mk_region(ty::ReFree(ty::FreeRegion {
159 bound_region: ty::BrNamed(id, name),
162 // (*) -- not late-bound, won't change
166 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
167 // This indicates an illegal lifetime
168 // elision. `resolve_lifetime` should have
169 // reported an error in this case -- but if
170 // not, let's error out.
171 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
173 // Supply some dummy value. We don't have an
174 // `re_error`, annoyingly, so use `'static`.
175 tcx.lifetimes.re_static
180 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
185 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
186 /// returns an appropriate set of substitutions for this particular reference to `I`.
187 pub fn ast_path_substs_for_ty(
191 item_segment: &hir::PathSegment<'_>,
192 ) -> SubstsRef<'tcx> {
193 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
197 item_segment.generic_args(),
198 item_segment.infer_args,
202 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
207 /// Report error if there is an explicit type parameter when using `impl Trait`.
210 seg: &hir::PathSegment<'_>,
211 generics: &ty::Generics,
213 let explicit = !seg.infer_args;
214 let impl_trait = generics.params.iter().any(|param| match param.kind {
215 ty::GenericParamDefKind::Type {
216 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
222 if explicit && impl_trait {
227 .filter_map(|arg| match arg {
228 GenericArg::Type(_) => Some(arg.span()),
231 .collect::<Vec<_>>();
233 let mut err = struct_span_err! {
237 "cannot provide explicit generic arguments when `impl Trait` is \
238 used in argument position"
242 err.span_label(span, "explicit generic argument not allowed");
251 /// Checks that the correct number of generic arguments have been provided.
252 /// Used specifically for function calls.
253 pub fn check_generic_arg_count_for_call(
257 seg: &hir::PathSegment<'_>,
258 is_method_call: bool,
260 let empty_args = hir::GenericArgs::none();
261 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
262 Self::check_generic_arg_count(
266 if let Some(ref args) = seg.args { args } else { &empty_args },
267 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
268 def.parent.is_none() && def.has_self, // `has_self`
269 seg.infer_args || suppress_mismatch, // `infer_args`
274 /// Checks that the correct number of generic arguments have been provided.
275 /// This is used both for datatypes and function calls.
276 fn check_generic_arg_count(
280 args: &hir::GenericArgs<'_>,
281 position: GenericArgPosition,
284 ) -> (bool, Option<Vec<Span>>) {
285 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
286 // that lifetimes will proceed types. So it suffices to check the number of each generic
287 // arguments in order to validate them with respect to the generic parameters.
288 let param_counts = def.own_counts();
289 let arg_counts = args.own_counts();
290 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
292 let mut defaults: ty::GenericParamCount = Default::default();
293 for param in &def.params {
295 GenericParamDefKind::Lifetime => {}
296 GenericParamDefKind::Type { has_default, .. } => {
297 defaults.types += has_default as usize
299 GenericParamDefKind::Const => {
300 // FIXME(const_generics:defaults)
305 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
306 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
309 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
310 let mut reported_late_bound_region_err = None;
311 if !infer_lifetimes {
312 if let Some(span_late) = def.has_late_bound_regions {
313 let msg = "cannot specify lifetime arguments explicitly \
314 if late bound lifetime parameters are present";
315 let note = "the late bound lifetime parameter is introduced here";
316 let span = args.args[0].span();
317 if position == GenericArgPosition::Value
318 && arg_counts.lifetimes != param_counts.lifetimes
320 let mut err = tcx.sess.struct_span_err(span, msg);
321 err.span_note(span_late, note);
323 reported_late_bound_region_err = Some(true);
325 let mut multispan = MultiSpan::from_span(span);
326 multispan.push_span_label(span_late, note.to_string());
328 lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
333 reported_late_bound_region_err = Some(false);
338 let check_kind_count = |kind, required, permitted, provided, offset| {
340 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
341 kind, required, permitted, provided, offset
343 // We enforce the following: `required` <= `provided` <= `permitted`.
344 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
345 // For other kinds (i.e., types), `permitted` may be greater than `required`.
346 if required <= provided && provided <= permitted {
347 return (reported_late_bound_region_err.unwrap_or(false), None);
350 // Unfortunately lifetime and type parameter mismatches are typically styled
351 // differently in diagnostics, which means we have a few cases to consider here.
352 let (bound, quantifier) = if required != permitted {
353 if provided < required {
354 (required, "at least ")
356 // provided > permitted
357 (permitted, "at most ")
363 let mut potential_assoc_types: Option<Vec<Span>> = None;
364 let (spans, label) = if required == permitted && provided > permitted {
365 // In the case when the user has provided too many arguments,
366 // we want to point to the unexpected arguments.
367 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
369 .map(|arg| arg.span())
371 potential_assoc_types = Some(spans.clone());
372 (spans, format!("unexpected {} argument", kind))
377 "expected {}{} {} argument{}",
386 let mut err = tcx.sess.struct_span_err_with_code(
389 "wrong number of {} arguments: expected {}{}, found {}",
390 kind, quantifier, bound, provided,
392 DiagnosticId::Error("E0107".into()),
395 err.span_label(span, label.as_str());
400 provided > required, // `suppress_error`
401 potential_assoc_types,
405 if reported_late_bound_region_err.is_none()
406 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
410 param_counts.lifetimes,
411 param_counts.lifetimes,
412 arg_counts.lifetimes,
416 // FIXME(const_generics:defaults)
417 if !infer_args || arg_counts.consts > param_counts.consts {
423 arg_counts.lifetimes + arg_counts.types,
426 // Note that type errors are currently be emitted *after* const errors.
427 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
431 param_counts.types - defaults.types - has_self as usize,
432 param_counts.types - has_self as usize,
434 arg_counts.lifetimes,
437 (reported_late_bound_region_err.unwrap_or(false), None)
441 /// Creates the relevant generic argument substitutions
442 /// corresponding to a set of generic parameters. This is a
443 /// rather complex function. Let us try to explain the role
444 /// of each of its parameters:
446 /// To start, we are given the `def_id` of the thing we are
447 /// creating the substitutions for, and a partial set of
448 /// substitutions `parent_substs`. In general, the substitutions
449 /// for an item begin with substitutions for all the "parents" of
450 /// that item -- e.g., for a method it might include the
451 /// parameters from the impl.
453 /// Therefore, the method begins by walking down these parents,
454 /// starting with the outermost parent and proceed inwards until
455 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
456 /// first to see if the parent's substitutions are listed in there. If so,
457 /// we can append those and move on. Otherwise, it invokes the
458 /// three callback functions:
460 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
461 /// generic arguments that were given to that parent from within
462 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
463 /// might refer to the trait `Foo`, and the arguments might be
464 /// `[T]`. The boolean value indicates whether to infer values
465 /// for arguments whose values were not explicitly provided.
466 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
467 /// instantiate a `GenericArg`.
468 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
469 /// creates a suitable inference variable.
470 pub fn create_substs_for_generic_args<'b>(
473 parent_substs: &[subst::GenericArg<'tcx>],
475 self_ty: Option<Ty<'tcx>>,
476 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
477 provided_kind: impl Fn(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
478 mut inferred_kind: impl FnMut(
479 Option<&[subst::GenericArg<'tcx>]>,
482 ) -> subst::GenericArg<'tcx>,
483 ) -> SubstsRef<'tcx> {
484 // Collect the segments of the path; we need to substitute arguments
485 // for parameters throughout the entire path (wherever there are
486 // generic parameters).
487 let mut parent_defs = tcx.generics_of(def_id);
488 let count = parent_defs.count();
489 let mut stack = vec![(def_id, parent_defs)];
490 while let Some(def_id) = parent_defs.parent {
491 parent_defs = tcx.generics_of(def_id);
492 stack.push((def_id, parent_defs));
495 // We manually build up the substitution, rather than using convenience
496 // methods in `subst.rs`, so that we can iterate over the arguments and
497 // parameters in lock-step linearly, instead of trying to match each pair.
498 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
500 // Iterate over each segment of the path.
501 while let Some((def_id, defs)) = stack.pop() {
502 let mut params = defs.params.iter().peekable();
504 // If we have already computed substitutions for parents, we can use those directly.
505 while let Some(¶m) = params.peek() {
506 if let Some(&kind) = parent_substs.get(param.index as usize) {
514 // `Self` is handled first, unless it's been handled in `parent_substs`.
516 if let Some(¶m) = params.peek() {
517 if param.index == 0 {
518 if let GenericParamDefKind::Type { .. } = param.kind {
522 .unwrap_or_else(|| inferred_kind(None, param, true)),
530 // Check whether this segment takes generic arguments and the user has provided any.
531 let (generic_args, infer_args) = args_for_def_id(def_id);
534 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
537 // We're going to iterate through the generic arguments that the user
538 // provided, matching them with the generic parameters we expect.
539 // Mismatches can occur as a result of elided lifetimes, or for malformed
540 // input. We try to handle both sensibly.
541 match (args.peek(), params.peek()) {
542 (Some(&arg), Some(¶m)) => {
543 match (arg, ¶m.kind) {
544 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
545 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
546 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
547 substs.push(provided_kind(param, arg));
551 (GenericArg::Type(_), GenericParamDefKind::Lifetime)
552 | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
553 // We expected a lifetime argument, but got a type or const
554 // argument. That means we're inferring the lifetimes.
555 substs.push(inferred_kind(None, param, infer_args));
559 // We expected one kind of parameter, but the user provided
560 // another. This is an error, but we need to handle it
561 // gracefully so we can report sensible errors.
562 // In this case, we're simply going to infer this argument.
568 // We should never be able to reach this point with well-formed input.
569 // Getting to this point means the user supplied more arguments than
570 // there are parameters.
573 (None, Some(¶m)) => {
574 // If there are fewer arguments than parameters, it means
575 // we're inferring the remaining arguments.
576 substs.push(inferred_kind(Some(&substs), param, infer_args));
580 (None, None) => break,
585 tcx.intern_substs(&substs)
588 /// Given the type/lifetime/const arguments provided to some path (along with
589 /// an implicit `Self`, if this is a trait reference), returns the complete
590 /// set of substitutions. This may involve applying defaulted type parameters.
591 /// Also returns back constriants on associated types.
596 /// T: std::ops::Index<usize, Output = u32>
597 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
600 /// 1. The `self_ty` here would refer to the type `T`.
601 /// 2. The path in question is the path to the trait `std::ops::Index`,
602 /// which will have been resolved to a `def_id`
603 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
604 /// parameters are returned in the `SubstsRef`, the associated type bindings like
605 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
607 /// Note that the type listing given here is *exactly* what the user provided.
609 /// For (generic) associated types
612 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
615 /// We have the parent substs are the substs for the parent trait:
616 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
617 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
618 /// lists: `[Vec<u8>, u8, 'a]`.
619 fn create_substs_for_ast_path<'a>(
623 parent_substs: &[subst::GenericArg<'tcx>],
624 generic_args: &'a hir::GenericArgs<'_>,
626 self_ty: Option<Ty<'tcx>>,
627 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
628 // If the type is parameterized by this region, then replace this
629 // region with the current anon region binding (in other words,
630 // whatever & would get replaced with).
632 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
634 def_id, self_ty, generic_args
637 let tcx = self.tcx();
638 let generic_params = tcx.generics_of(def_id);
640 if generic_params.has_self {
641 if generic_params.parent.is_some() {
642 // The parent is a trait so it should have at least one subst
643 // for the `Self` type.
644 assert!(!parent_substs.is_empty())
646 // This item (presumably a trait) needs a self-type.
647 assert!(self_ty.is_some());
650 assert!(self_ty.is_none() && parent_substs.is_empty());
653 let (_, potential_assoc_types) = Self::check_generic_arg_count(
658 GenericArgPosition::Type,
663 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
664 let default_needs_object_self = |param: &ty::GenericParamDef| {
665 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
666 if is_object && has_default {
667 let self_param = tcx.types.self_param;
668 if tcx.at(span).type_of(param.def_id).walk().any(|ty| ty == self_param) {
669 // There is no suitable inference default for a type parameter
670 // that references self, in an object type.
679 let mut missing_type_params = vec![];
680 let substs = Self::create_substs_for_generic_args(
686 // Provide the generic args, and whether types should be inferred.
687 |_| (Some(generic_args), infer_args),
688 // Provide substitutions for parameters for which (valid) arguments have been provided.
689 |param, arg| match (¶m.kind, arg) {
690 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
691 self.ast_region_to_region(<, Some(param)).into()
693 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
694 self.ast_ty_to_ty(&ty).into()
696 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
697 self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
701 // Provide substitutions for parameters for which arguments are inferred.
702 |substs, param, infer_args| {
704 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
705 GenericParamDefKind::Type { has_default, .. } => {
706 if !infer_args && has_default {
707 // No type parameter provided, but a default exists.
709 // If we are converting an object type, then the
710 // `Self` parameter is unknown. However, some of the
711 // other type parameters may reference `Self` in their
712 // defaults. This will lead to an ICE if we are not
714 if default_needs_object_self(param) {
715 missing_type_params.push(param.name.to_string());
718 // This is a default type parameter.
721 tcx.at(span).type_of(param.def_id).subst_spanned(
729 } else if infer_args {
730 // No type parameters were provided, we can infer all.
732 if !default_needs_object_self(param) { Some(param) } else { None };
733 self.ty_infer(param, span).into()
735 // We've already errored above about the mismatch.
739 GenericParamDefKind::Const => {
740 // FIXME(const_generics:defaults)
742 // No const parameters were provided, we can infer all.
743 let ty = tcx.at(span).type_of(param.def_id);
744 self.ct_infer(ty, Some(param), span).into()
746 // We've already errored above about the mismatch.
747 tcx.consts.err.into()
754 self.complain_about_missing_type_params(
758 generic_args.args.is_empty(),
761 // Convert associated-type bindings or constraints into a separate vector.
762 // Example: Given this:
764 // T: Iterator<Item = u32>
766 // The `T` is passed in as a self-type; the `Item = u32` is
767 // not a "type parameter" of the `Iterator` trait, but rather
768 // a restriction on `<T as Iterator>::Item`, so it is passed
770 let assoc_bindings = generic_args
774 let kind = match binding.kind {
775 hir::TypeBindingKind::Equality { ref ty } => {
776 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
778 hir::TypeBindingKind::Constraint { ref bounds } => {
779 ConvertedBindingKind::Constraint(bounds)
782 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
787 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
788 generic_params, self_ty, substs
791 (substs, assoc_bindings, potential_assoc_types)
794 crate fn create_substs_for_associated_item(
799 item_segment: &hir::PathSegment<'_>,
800 parent_substs: SubstsRef<'tcx>,
801 ) -> SubstsRef<'tcx> {
802 if tcx.generics_of(item_def_id).params.is_empty() {
803 self.prohibit_generics(slice::from_ref(item_segment));
807 self.create_substs_for_ast_path(
811 item_segment.generic_args(),
812 item_segment.infer_args,
819 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
820 /// the type parameter's name as a placeholder.
821 fn complain_about_missing_type_params(
823 missing_type_params: Vec<String>,
826 empty_generic_args: bool,
828 if missing_type_params.is_empty() {
832 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
833 let mut err = struct_span_err!(
837 "the type parameter{} {} must be explicitly specified",
838 pluralize!(missing_type_params.len()),
842 self.tcx().def_span(def_id),
844 "type parameter{} {} must be specified for this",
845 pluralize!(missing_type_params.len()),
849 let mut suggested = false;
850 if let (Ok(snippet), true) = (
851 self.tcx().sess.source_map().span_to_snippet(span),
852 // Don't suggest setting the type params if there are some already: the order is
853 // tricky to get right and the user will already know what the syntax is.
856 if snippet.ends_with('>') {
857 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
858 // we would have to preserve the right order. For now, as clearly the user is
859 // aware of the syntax, we do nothing.
861 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
862 // least we can clue them to the correct syntax `Iterator<Type>`.
866 "set the type parameter{plural} to the desired type{plural}",
867 plural = pluralize!(missing_type_params.len()),
869 format!("{}<{}>", snippet, missing_type_params.join(", ")),
870 Applicability::HasPlaceholders,
879 "missing reference{} to {}",
880 pluralize!(missing_type_params.len()),
886 "because of the default `Self` reference, type parameters must be \
887 specified on object types"
892 /// Instantiates the path for the given trait reference, assuming that it's
893 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
894 /// The type _cannot_ be a type other than a trait type.
896 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
897 /// are disallowed. Otherwise, they are pushed onto the vector given.
898 pub fn instantiate_mono_trait_ref(
900 trait_ref: &hir::TraitRef<'_>,
902 ) -> ty::TraitRef<'tcx> {
903 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
905 self.ast_path_to_mono_trait_ref(
907 trait_ref.trait_def_id(),
909 trait_ref.path.segments.last().unwrap(),
913 /// The given trait-ref must actually be a trait.
914 pub(super) fn instantiate_poly_trait_ref_inner(
916 trait_ref: &hir::TraitRef<'_>,
919 bounds: &mut Bounds<'tcx>,
921 ) -> Option<Vec<Span>> {
922 let trait_def_id = trait_ref.trait_def_id();
924 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
926 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
928 let path_span = if let [segment] = &trait_ref.path.segments[..] {
929 // FIXME: `trait_ref.path.span` can point to a full path with multiple
930 // segments, even though `trait_ref.path.segments` is of length `1`. Work
931 // around that bug here, even though it should be fixed elsewhere.
932 // This would otherwise cause an invalid suggestion. For an example, look at
933 // `src/test/ui/issues/issue-28344.rs`.
938 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
942 trait_ref.path.segments.last().unwrap(),
944 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
946 bounds.trait_bounds.push((poly_trait_ref, span));
948 let mut dup_bindings = FxHashMap::default();
949 for binding in &assoc_bindings {
950 // Specify type to assert that error was already reported in `Err` case.
951 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
952 trait_ref.hir_ref_id,
960 // Okay to ignore `Err` because of `ErrorReported` (see above).
964 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
965 trait_ref, bounds, poly_trait_ref
967 potential_assoc_types
970 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
971 /// a full trait reference. The resulting trait reference is returned. This may also generate
972 /// auxiliary bounds, which are added to `bounds`.
977 /// poly_trait_ref = Iterator<Item = u32>
981 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
983 /// **A note on binders:** against our usual convention, there is an implied bounder around
984 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
985 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
986 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
987 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
989 pub fn instantiate_poly_trait_ref(
991 poly_trait_ref: &hir::PolyTraitRef<'_>,
993 bounds: &mut Bounds<'tcx>,
994 ) -> Option<Vec<Span>> {
995 self.instantiate_poly_trait_ref_inner(
996 &poly_trait_ref.trait_ref,
1004 fn ast_path_to_mono_trait_ref(
1007 trait_def_id: DefId,
1009 trait_segment: &hir::PathSegment<'_>,
1010 ) -> ty::TraitRef<'tcx> {
1011 let (substs, assoc_bindings, _) =
1012 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1013 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
1014 ty::TraitRef::new(trait_def_id, substs)
1017 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1018 /// an error and attempt to build a reasonable structured suggestion.
1019 fn complain_about_internal_fn_trait(
1022 trait_def_id: DefId,
1023 trait_segment: &'a hir::PathSegment<'a>,
1025 let trait_def = self.tcx().trait_def(trait_def_id);
1027 if !self.tcx().features().unboxed_closures
1028 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1030 // For now, require that parenthetical notation be used only with `Fn()` etc.
1031 let (msg, sugg) = if trait_def.paren_sugar {
1033 "the precise format of `Fn`-family traits' type parameters is subject to \
1037 trait_segment.ident,
1041 .and_then(|args| args.args.get(0))
1042 .and_then(|arg| match arg {
1043 hir::GenericArg::Type(ty) => {
1044 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1048 .unwrap_or_else(|| "()".to_string()),
1053 .filter_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1054 (true, hir::TypeBindingKind::Equality { ty }) => {
1055 Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1060 .unwrap_or_else(|| "()".to_string()),
1064 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1066 let sess = &self.tcx().sess.parse_sess;
1067 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1068 if let Some(sugg) = sugg {
1069 let msg = "use parenthetical notation instead";
1070 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1076 fn create_substs_for_ast_trait_ref<'a>(
1079 trait_def_id: DefId,
1081 trait_segment: &'a hir::PathSegment<'a>,
1082 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Option<Vec<Span>>) {
1083 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1085 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1087 self.create_substs_for_ast_path(
1091 trait_segment.generic_args(),
1092 trait_segment.infer_args,
1097 fn trait_defines_associated_type_named(
1099 trait_def_id: DefId,
1100 assoc_name: ast::Ident,
1102 self.tcx().associated_items(trait_def_id).any(|item| {
1103 item.kind == ty::AssocKind::Type
1104 && self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
1108 // Returns `true` if a bounds list includes `?Sized`.
1109 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1110 let tcx = self.tcx();
1112 // Try to find an unbound in bounds.
1113 let mut unbound = None;
1114 for ab in ast_bounds {
1115 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1116 if unbound.is_none() {
1117 unbound = Some(&ptr.trait_ref);
1123 "type parameter has more than one relaxed default \
1124 bound, only one is supported"
1130 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1133 // FIXME(#8559) currently requires the unbound to be built-in.
1134 if let Ok(kind_id) = kind_id {
1135 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1138 "default bound relaxed for a type parameter, but \
1139 this does nothing because the given bound is not \
1140 a default; only `?Sized` is supported",
1145 _ if kind_id.is_ok() => {
1148 // No lang item for `Sized`, so we can't add it as a bound.
1155 /// This helper takes a *converted* parameter type (`param_ty`)
1156 /// and an *unconverted* list of bounds:
1159 /// fn foo<T: Debug>
1160 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1162 /// `param_ty`, in ty form
1165 /// It adds these `ast_bounds` into the `bounds` structure.
1167 /// **A note on binders:** there is an implied binder around
1168 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1169 /// for more details.
1173 ast_bounds: &[hir::GenericBound<'_>],
1174 bounds: &mut Bounds<'tcx>,
1176 let mut trait_bounds = Vec::new();
1177 let mut region_bounds = Vec::new();
1179 for ast_bound in ast_bounds {
1181 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1182 trait_bounds.push(b)
1184 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1185 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1189 for bound in trait_bounds {
1190 let _ = self.instantiate_poly_trait_ref(bound, param_ty, bounds);
1193 bounds.region_bounds.extend(
1194 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1198 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1199 /// The self-type for the bounds is given by `param_ty`.
1204 /// fn foo<T: Bar + Baz>() { }
1205 /// ^ ^^^^^^^^^ ast_bounds
1209 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1210 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1211 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1213 /// `span` should be the declaration size of the parameter.
1214 pub fn compute_bounds(
1217 ast_bounds: &[hir::GenericBound<'_>],
1218 sized_by_default: SizedByDefault,
1221 let mut bounds = Bounds::default();
1223 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1224 bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1226 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1227 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1235 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1238 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1239 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1240 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1241 fn add_predicates_for_ast_type_binding(
1243 hir_ref_id: hir::HirId,
1244 trait_ref: ty::PolyTraitRef<'tcx>,
1245 binding: &ConvertedBinding<'_, 'tcx>,
1246 bounds: &mut Bounds<'tcx>,
1248 dup_bindings: &mut FxHashMap<DefId, Span>,
1250 ) -> Result<(), ErrorReported> {
1251 let tcx = self.tcx();
1254 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1255 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1256 // subtle in the event that `T` is defined in a supertrait of
1257 // `SomeTrait`, because in that case we need to upcast.
1259 // That is, consider this case:
1262 // trait SubTrait: SuperTrait<int> { }
1263 // trait SuperTrait<A> { type T; }
1265 // ... B: SubTrait<T = foo> ...
1268 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1270 // Find any late-bound regions declared in `ty` that are not
1271 // declared in the trait-ref. These are not well-formed.
1275 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1276 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1277 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1278 let late_bound_in_trait_ref =
1279 tcx.collect_constrained_late_bound_regions(&trait_ref);
1280 let late_bound_in_ty =
1281 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1282 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1283 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1284 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1285 let br_name = match *br {
1286 ty::BrNamed(_, name) => name,
1290 "anonymous bound region {:?} in binding but not trait ref",
1299 "binding for associated type `{}` references lifetime `{}`, \
1300 which does not appear in the trait input types",
1310 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1311 // Simple case: X is defined in the current trait.
1314 // Otherwise, we have to walk through the supertraits to find
1316 self.one_bound_for_assoc_type(
1317 || traits::supertraits(tcx, trait_ref),
1318 &trait_ref.print_only_trait_path().to_string(),
1321 match binding.kind {
1322 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1328 let (assoc_ident, def_scope) =
1329 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1331 .associated_items(candidate.def_id())
1332 .find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident)
1333 .expect("missing associated type");
1335 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1336 let msg = format!("associated type `{}` is private", binding.item_name);
1337 tcx.sess.span_err(binding.span, &msg);
1339 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1343 .entry(assoc_ty.def_id)
1344 .and_modify(|prev_span| {
1349 "the value of the associated type `{}` (from trait `{}`) \
1350 is already specified",
1352 tcx.def_path_str(assoc_ty.container.id())
1354 .span_label(binding.span, "re-bound here")
1355 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1358 .or_insert(binding.span);
1361 match binding.kind {
1362 ConvertedBindingKind::Equality(ref ty) => {
1363 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1364 // the "projection predicate" for:
1366 // `<T as Iterator>::Item = u32`
1367 bounds.projection_bounds.push((
1368 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1369 projection_ty: ty::ProjectionTy::from_ref_and_name(
1379 ConvertedBindingKind::Constraint(ast_bounds) => {
1380 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1382 // `<T as Iterator>::Item: Debug`
1384 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1385 // parameter to have a skipped binder.
1386 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1387 self.add_bounds(param_ty, ast_bounds, bounds);
1397 item_segment: &hir::PathSegment<'_>,
1399 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1400 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1403 fn conv_object_ty_poly_trait_ref(
1406 trait_bounds: &[hir::PolyTraitRef<'_>],
1407 lifetime: &hir::Lifetime,
1409 let tcx = self.tcx();
1411 let mut bounds = Bounds::default();
1412 let mut potential_assoc_types = Vec::new();
1413 let dummy_self = self.tcx().types.trait_object_dummy_self;
1414 for trait_bound in trait_bounds.iter().rev() {
1415 let cur_potential_assoc_types =
1416 self.instantiate_poly_trait_ref(trait_bound, dummy_self, &mut bounds);
1417 potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1420 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1421 // is used and no 'maybe' bounds are used.
1422 let expanded_traits =
1423 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1424 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1425 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1426 if regular_traits.len() > 1 {
1427 let first_trait = ®ular_traits[0];
1428 let additional_trait = ®ular_traits[1];
1429 let mut err = struct_span_err!(
1431 additional_trait.bottom().1,
1433 "only auto traits can be used as additional traits in a trait object"
1435 additional_trait.label_with_exp_info(
1437 "additional non-auto trait",
1440 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1444 if regular_traits.is_empty() && auto_traits.is_empty() {
1445 span_err!(tcx.sess, span, E0224, "at least one trait is required for an object type");
1446 return tcx.types.err;
1449 // Check that there are no gross object safety violations;
1450 // most importantly, that the supertraits don't contain `Self`,
1452 for item in ®ular_traits {
1453 let object_safety_violations =
1454 tcx.astconv_object_safety_violations(item.trait_ref().def_id());
1455 if !object_safety_violations.is_empty() {
1456 tcx.report_object_safety_error(
1458 item.trait_ref().def_id(),
1459 object_safety_violations,
1462 return tcx.types.err;
1466 // Use a `BTreeSet` to keep output in a more consistent order.
1467 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1469 let regular_traits_refs_spans = bounds
1472 .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1474 for (base_trait_ref, span) in regular_traits_refs_spans {
1475 for trait_ref in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1477 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1481 ty::Predicate::Trait(pred) => {
1482 associated_types.entry(span).or_default().extend(
1483 tcx.associated_items(pred.def_id())
1484 .filter(|item| item.kind == ty::AssocKind::Type)
1485 .map(|item| item.def_id),
1488 ty::Predicate::Projection(pred) => {
1489 // A `Self` within the original bound will be substituted with a
1490 // `trait_object_dummy_self`, so check for that.
1491 let references_self = pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1493 // If the projection output contains `Self`, force the user to
1494 // elaborate it explicitly to avoid a lot of complexity.
1496 // The "classicaly useful" case is the following:
1498 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1503 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1504 // but actually supporting that would "expand" to an infinitely-long type
1505 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1507 // Instead, we force the user to write
1508 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1509 // the discussion in #56288 for alternatives.
1510 if !references_self {
1511 // Include projections defined on supertraits.
1512 bounds.projection_bounds.push((pred, span));
1520 for (projection_bound, _) in &bounds.projection_bounds {
1521 for (_, def_ids) in &mut associated_types {
1522 def_ids.remove(&projection_bound.projection_def_id());
1526 self.complain_about_missing_associated_types(
1528 potential_assoc_types,
1532 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1533 // `dyn Trait + Send`.
1534 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1535 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1536 debug!("regular_traits: {:?}", regular_traits);
1537 debug!("auto_traits: {:?}", auto_traits);
1539 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1540 // removing the dummy `Self` type (`trait_object_dummy_self`).
1541 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1542 if trait_ref.self_ty() != dummy_self {
1543 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1544 // which picks up non-supertraits where clauses - but also, the object safety
1545 // completely ignores trait aliases, which could be object safety hazards. We
1546 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1547 // disabled. (#66420)
1548 tcx.sess.delay_span_bug(
1551 "trait_ref_to_existential called on {:?} with non-dummy Self",
1556 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1559 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1560 let existential_trait_refs = regular_traits
1562 .map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
1563 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1564 bound.map_bound(|b| {
1565 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1566 ty::ExistentialProjection {
1568 item_def_id: b.projection_ty.item_def_id,
1569 substs: trait_ref.substs,
1574 // Calling `skip_binder` is okay because the predicates are re-bound.
1575 let regular_trait_predicates = existential_trait_refs
1576 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1577 let auto_trait_predicates = auto_traits
1579 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1580 let mut v = regular_trait_predicates
1581 .chain(auto_trait_predicates)
1583 existential_projections
1584 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1586 .collect::<SmallVec<[_; 8]>>();
1587 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1589 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1591 // Use explicitly-specified region bound.
1592 let region_bound = if !lifetime.is_elided() {
1593 self.ast_region_to_region(lifetime, None)
1595 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1596 if tcx.named_region(lifetime.hir_id).is_some() {
1597 self.ast_region_to_region(lifetime, None)
1599 self.re_infer(None, span).unwrap_or_else(|| {
1604 "the lifetime bound for this object type cannot be deduced \
1605 from context; please supply an explicit bound"
1607 tcx.lifetimes.re_static
1612 debug!("region_bound: {:?}", region_bound);
1614 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1615 debug!("trait_object_type: {:?}", ty);
1619 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1620 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1621 /// same trait bound have the same name (as they come from different super-traits), we instead
1622 /// emit a generic note suggesting using a `where` clause to constraint instead.
1623 fn complain_about_missing_associated_types(
1625 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1626 potential_assoc_types: Vec<Span>,
1627 trait_bounds: &[hir::PolyTraitRef<'_>],
1629 if !associated_types.values().any(|v| v.len() > 0) {
1632 let tcx = self.tcx();
1633 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1634 // appropriate one, but this should be handled earlier in the span assignment.
1635 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1637 .map(|(span, def_ids)| {
1638 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1641 let mut names = vec![];
1643 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1644 // `issue-22560.rs`.
1645 let mut trait_bound_spans: Vec<Span> = vec![];
1646 for (span, items) in &associated_types {
1647 if !items.is_empty() {
1648 trait_bound_spans.push(*span);
1650 for assoc_item in items {
1651 let trait_def_id = assoc_item.container.id();
1653 "`{}` (from trait `{}`)",
1655 tcx.def_path_str(trait_def_id),
1660 match (&potential_assoc_types[..], &trait_bounds) {
1661 ([], [bound]) => match &bound.trait_ref.path.segments[..] {
1662 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1663 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1664 // around that bug here, even though it should be fixed elsewhere.
1665 // This would otherwise cause an invalid suggestion. For an example, look at
1666 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1668 // error[E0191]: the value of the associated type `Output`
1669 // (from trait `std::ops::BitXor`) must be specified
1670 // --> $DIR/issue-28344.rs:4:17
1672 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1673 // | ^^^^^^ help: specify the associated type:
1674 // | `BitXor<Output = Type>`
1678 // error[E0191]: the value of the associated type `Output`
1679 // (from trait `std::ops::BitXor`) must be specified
1680 // --> $DIR/issue-28344.rs:4:17
1682 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1683 // | ^^^^^^^^^^^^^ help: specify the associated type:
1684 // | `BitXor::bitor<Output = Type>`
1685 [segment] if segment.args.is_none() => {
1686 trait_bound_spans = vec![segment.ident.span];
1687 associated_types = associated_types
1689 .map(|(_, items)| (segment.ident.span, items))
1697 trait_bound_spans.sort();
1698 let mut err = struct_span_err!(
1702 "the value of the associated type{} {} must be specified",
1703 pluralize!(names.len()),
1706 let mut suggestions = vec![];
1707 let mut types_count = 0;
1708 let mut where_constraints = vec![];
1709 for (span, assoc_items) in &associated_types {
1710 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1711 for item in assoc_items {
1713 *names.entry(item.ident.name).or_insert(0) += 1;
1715 let mut dupes = false;
1716 for item in assoc_items {
1717 let prefix = if names[&item.ident.name] > 1 {
1718 let trait_def_id = item.container.id();
1720 format!("{}::", tcx.def_path_str(trait_def_id))
1724 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1725 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1728 if potential_assoc_types.len() == assoc_items.len() {
1729 // Only suggest when the amount of missing associated types equals the number of
1730 // extra type arguments present, as that gives us a relatively high confidence
1731 // that the user forgot to give the associtated type's name. The canonical
1732 // example would be trying to use `Iterator<isize>` instead of
1733 // `Iterator<Item = isize>`.
1734 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1735 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1736 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1739 } else if let (Ok(snippet), false) =
1740 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1743 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1744 let code = if snippet.ends_with(">") {
1745 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1746 // suggest, but at least we can clue them to the correct syntax
1747 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1749 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1751 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1752 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1753 format!("{}<{}>", snippet, types.join(", "))
1755 suggestions.push((*span, code));
1757 where_constraints.push(*span);
1760 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1761 using the fully-qualified path to the associated types";
1762 if !where_constraints.is_empty() && suggestions.is_empty() {
1763 // If there are duplicates associated type names and a single trait bound do not
1764 // use structured suggestion, it means that there are multiple super-traits with
1765 // the same associated type name.
1766 err.help(where_msg);
1768 if suggestions.len() != 1 {
1769 // We don't need this label if there's an inline suggestion, show otherwise.
1770 for (span, assoc_items) in &associated_types {
1771 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1772 for item in assoc_items {
1774 *names.entry(item.ident.name).or_insert(0) += 1;
1776 let mut label = vec![];
1777 for item in assoc_items {
1778 let postfix = if names[&item.ident.name] > 1 {
1779 let trait_def_id = item.container.id();
1780 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1784 label.push(format!("`{}`{}", item.ident, postfix));
1786 if !label.is_empty() {
1790 "associated type{} {} must be specified",
1791 pluralize!(label.len()),
1798 if !suggestions.is_empty() {
1799 err.multipart_suggestion(
1800 &format!("specify the associated type{}", pluralize!(types_count)),
1802 Applicability::HasPlaceholders,
1804 if !where_constraints.is_empty() {
1805 err.span_help(where_constraints, where_msg);
1811 fn report_ambiguous_associated_type(
1818 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1819 if let (Some(_), Ok(snippet)) = (
1820 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1821 self.tcx().sess.source_map().span_to_snippet(span),
1823 err.span_suggestion(
1825 "you are looking for the module in `std`, not the primitive type",
1826 format!("std::{}", snippet),
1827 Applicability::MachineApplicable,
1830 err.span_suggestion(
1832 "use fully-qualified syntax",
1833 format!("<{} as {}>::{}", type_str, trait_str, name),
1834 Applicability::HasPlaceholders,
1840 // Search for a bound on a type parameter which includes the associated item
1841 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1842 // This function will fail if there are no suitable bounds or there is
1844 fn find_bound_for_assoc_item(
1846 ty_param_def_id: DefId,
1847 assoc_name: ast::Ident,
1849 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1850 let tcx = self.tcx();
1853 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1854 ty_param_def_id, assoc_name, span,
1857 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1859 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1861 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1862 let param_name = tcx.hir().ty_param_name(param_hir_id);
1863 self.one_bound_for_assoc_type(
1865 traits::transitive_bounds(
1867 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1870 ¶m_name.as_str(),
1877 // Checks that `bounds` contains exactly one element and reports appropriate
1878 // errors otherwise.
1879 fn one_bound_for_assoc_type<I>(
1881 all_candidates: impl Fn() -> I,
1882 ty_param_name: &str,
1883 assoc_name: ast::Ident,
1885 is_equality: Option<String>,
1886 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1888 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1890 let mut matching_candidates = all_candidates()
1891 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1893 let bound = match matching_candidates.next() {
1894 Some(bound) => bound,
1896 self.complain_about_assoc_type_not_found(
1902 return Err(ErrorReported);
1906 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1908 if let Some(bound2) = matching_candidates.next() {
1909 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1911 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
1912 let mut err = if is_equality.is_some() {
1913 // More specific Error Index entry.
1918 "ambiguous associated type `{}` in bounds of `{}`",
1927 "ambiguous associated type `{}` in bounds of `{}`",
1932 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1934 let mut where_bounds = vec![];
1935 for bound in bounds {
1936 let bound_span = self
1938 .associated_items(bound.def_id())
1940 item.kind == ty::AssocKind::Type
1941 && self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1943 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1945 if let Some(bound_span) = bound_span {
1949 "ambiguous `{}` from `{}`",
1951 bound.print_only_trait_path(),
1954 if let Some(constraint) = &is_equality {
1955 where_bounds.push(format!(
1956 " T: {trait}::{assoc} = {constraint}",
1957 trait=bound.print_only_trait_path(),
1959 constraint=constraint,
1962 err.span_suggestion(
1964 "use fully qualified syntax to disambiguate",
1968 bound.print_only_trait_path(),
1971 Applicability::MaybeIncorrect,
1976 "associated type `{}` could derive from `{}`",
1978 bound.print_only_trait_path(),
1982 if !where_bounds.is_empty() {
1984 "consider introducing a new type parameter `T` and adding `where` constraints:\
1985 \n where\n T: {},\n{}",
1987 where_bounds.join(",\n"),
1991 if !where_bounds.is_empty() {
1992 return Err(ErrorReported);
1998 fn complain_about_assoc_type_not_found<I>(
2000 all_candidates: impl Fn() -> I,
2001 ty_param_name: &str,
2002 assoc_name: ast::Ident,
2005 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2007 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2008 // valid span, so we point at the whole path segment instead.
2009 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2010 let mut err = struct_span_err!(
2014 "associated type `{}` not found for `{}`",
2019 let all_candidate_names: Vec<_> = all_candidates()
2020 .map(|r| self.tcx().associated_items(r.def_id()))
2023 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2027 if let (Some(suggested_name), true) = (
2028 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2029 assoc_name.span != DUMMY_SP,
2031 err.span_suggestion(
2033 "there is an associated type with a similar name",
2034 suggested_name.to_string(),
2035 Applicability::MaybeIncorrect,
2038 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2044 // Create a type from a path to an associated type.
2045 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2046 // and item_segment is the path segment for `D`. We return a type and a def for
2048 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2049 // parameter or `Self`.
2050 pub fn associated_path_to_ty(
2052 hir_ref_id: hir::HirId,
2056 assoc_segment: &hir::PathSegment<'_>,
2057 permit_variants: bool,
2058 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2059 let tcx = self.tcx();
2060 let assoc_ident = assoc_segment.ident;
2062 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2064 // Check if we have an enum variant.
2065 let mut variant_resolution = None;
2066 if let ty::Adt(adt_def, _) = qself_ty.kind {
2067 if adt_def.is_enum() {
2068 let variant_def = adt_def
2071 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2072 if let Some(variant_def) = variant_def {
2073 if permit_variants {
2074 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2075 self.prohibit_generics(slice::from_ref(assoc_segment));
2076 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2078 variant_resolution = Some(variant_def.def_id);
2084 // Find the type of the associated item, and the trait where the associated
2085 // item is declared.
2086 let bound = match (&qself_ty.kind, qself_res) {
2087 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2088 // `Self` in an impl of a trait -- we have a concrete self type and a
2090 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2091 Some(trait_ref) => trait_ref,
2093 // A cycle error occurred, most likely.
2094 return Err(ErrorReported);
2098 self.one_bound_for_assoc_type(
2099 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2106 (&ty::Param(_), Res::SelfTy(Some(param_did), None))
2107 | (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
2108 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
2111 if variant_resolution.is_some() {
2112 // Variant in type position
2113 let msg = format!("expected type, found variant `{}`", assoc_ident);
2114 tcx.sess.span_err(span, &msg);
2115 } else if qself_ty.is_enum() {
2116 let mut err = tcx.sess.struct_span_err(
2118 &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
2121 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2122 if let Some(suggested_name) = find_best_match_for_name(
2123 adt_def.variants.iter().map(|variant| &variant.ident.name),
2124 &assoc_ident.as_str(),
2127 err.span_suggestion(
2129 "there is a variant with a similar name",
2130 suggested_name.to_string(),
2131 Applicability::MaybeIncorrect,
2136 format!("variant not found in `{}`", qself_ty),
2140 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2141 let sp = tcx.sess.source_map().def_span(sp);
2142 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2146 } else if !qself_ty.references_error() {
2147 // Don't print `TyErr` to the user.
2148 self.report_ambiguous_associated_type(
2150 &qself_ty.to_string(),
2155 return Err(ErrorReported);
2159 let trait_did = bound.def_id();
2160 let (assoc_ident, def_scope) =
2161 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2163 .associated_items(trait_did)
2164 .find(|i| Namespace::from(i.kind) == Namespace::Type && i.ident.modern() == assoc_ident)
2165 .expect("missing associated type");
2167 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2168 let ty = self.normalize_ty(span, ty);
2170 let kind = DefKind::AssocTy;
2171 if !item.vis.is_accessible_from(def_scope, tcx) {
2172 let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
2173 tcx.sess.span_err(span, &msg);
2175 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2177 if let Some(variant_def_id) = variant_resolution {
2178 let mut err = tcx.struct_span_lint_hir(
2179 AMBIGUOUS_ASSOCIATED_ITEMS,
2182 "ambiguous associated item",
2185 let mut could_refer_to = |kind: DefKind, def_id, also| {
2186 let note_msg = format!(
2187 "`{}` could{} refer to {} defined here",
2192 err.span_note(tcx.def_span(def_id), ¬e_msg);
2194 could_refer_to(DefKind::Variant, variant_def_id, "");
2195 could_refer_to(kind, item.def_id, " also");
2197 err.span_suggestion(
2199 "use fully-qualified syntax",
2200 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2201 Applicability::MachineApplicable,
2206 Ok((ty, kind, item.def_id))
2212 opt_self_ty: Option<Ty<'tcx>>,
2214 trait_segment: &hir::PathSegment<'_>,
2215 item_segment: &hir::PathSegment<'_>,
2217 let tcx = self.tcx();
2219 let trait_def_id = tcx.parent(item_def_id).unwrap();
2221 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2223 let self_ty = if let Some(ty) = opt_self_ty {
2226 let path_str = tcx.def_path_str(trait_def_id);
2228 let def_id = self.item_def_id();
2230 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2232 let parent_def_id = def_id
2233 .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
2234 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
2236 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2238 // If the trait in segment is the same as the trait defining the item,
2239 // use the `<Self as ..>` syntax in the error.
2240 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2241 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2243 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2249 self.report_ambiguous_associated_type(
2253 item_segment.ident.name,
2255 return tcx.types.err;
2258 debug!("qpath_to_ty: self_type={:?}", self_ty);
2260 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2262 let item_substs = self.create_substs_for_associated_item(
2270 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2272 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2275 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2279 let mut has_err = false;
2280 for segment in segments {
2281 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2282 for arg in segment.generic_args().args {
2283 let (span, kind) = match arg {
2284 hir::GenericArg::Lifetime(lt) => {
2290 (lt.span, "lifetime")
2292 hir::GenericArg::Type(ty) => {
2300 hir::GenericArg::Const(ct) => {
2308 let mut err = struct_span_err!(
2312 "{} arguments are not allowed for this type",
2315 err.span_label(span, format!("{} argument not allowed", kind));
2317 if err_for_lt && err_for_ty && err_for_ct {
2321 for binding in segment.generic_args().bindings {
2323 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2330 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2331 let mut err = struct_span_err!(
2335 "associated type bindings are not allowed here"
2337 err.span_label(span, "associated type not allowed here").emit();
2340 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2341 pub fn def_ids_for_value_path_segments(
2343 segments: &[hir::PathSegment<'_>],
2344 self_ty: Option<Ty<'tcx>>,
2348 // We need to extract the type parameters supplied by the user in
2349 // the path `path`. Due to the current setup, this is a bit of a
2350 // tricky-process; the problem is that resolve only tells us the
2351 // end-point of the path resolution, and not the intermediate steps.
2352 // Luckily, we can (at least for now) deduce the intermediate steps
2353 // just from the end-point.
2355 // There are basically five cases to consider:
2357 // 1. Reference to a constructor of a struct:
2359 // struct Foo<T>(...)
2361 // In this case, the parameters are declared in the type space.
2363 // 2. Reference to a constructor of an enum variant:
2365 // enum E<T> { Foo(...) }
2367 // In this case, the parameters are defined in the type space,
2368 // but may be specified either on the type or the variant.
2370 // 3. Reference to a fn item or a free constant:
2374 // In this case, the path will again always have the form
2375 // `a::b::foo::<T>` where only the final segment should have
2376 // type parameters. However, in this case, those parameters are
2377 // declared on a value, and hence are in the `FnSpace`.
2379 // 4. Reference to a method or an associated constant:
2381 // impl<A> SomeStruct<A> {
2385 // Here we can have a path like
2386 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2387 // may appear in two places. The penultimate segment,
2388 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2389 // final segment, `foo::<B>` contains parameters in fn space.
2391 // The first step then is to categorize the segments appropriately.
2393 let tcx = self.tcx();
2395 assert!(!segments.is_empty());
2396 let last = segments.len() - 1;
2398 let mut path_segs = vec![];
2401 // Case 1. Reference to a struct constructor.
2402 DefKind::Ctor(CtorOf::Struct, ..) => {
2403 // Everything but the final segment should have no
2404 // parameters at all.
2405 let generics = tcx.generics_of(def_id);
2406 // Variant and struct constructors use the
2407 // generics of their parent type definition.
2408 let generics_def_id = generics.parent.unwrap_or(def_id);
2409 path_segs.push(PathSeg(generics_def_id, last));
2412 // Case 2. Reference to a variant constructor.
2413 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2414 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2415 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2416 debug_assert!(adt_def.is_enum());
2418 } else if last >= 1 && segments[last - 1].args.is_some() {
2419 // Everything but the penultimate segment should have no
2420 // parameters at all.
2421 let mut def_id = def_id;
2423 // `DefKind::Ctor` -> `DefKind::Variant`
2424 if let DefKind::Ctor(..) = kind {
2425 def_id = tcx.parent(def_id).unwrap()
2428 // `DefKind::Variant` -> `DefKind::Enum`
2429 let enum_def_id = tcx.parent(def_id).unwrap();
2430 (enum_def_id, last - 1)
2432 // FIXME: lint here recommending `Enum::<...>::Variant` form
2433 // instead of `Enum::Variant::<...>` form.
2435 // Everything but the final segment should have no
2436 // parameters at all.
2437 let generics = tcx.generics_of(def_id);
2438 // Variant and struct constructors use the
2439 // generics of their parent type definition.
2440 (generics.parent.unwrap_or(def_id), last)
2442 path_segs.push(PathSeg(generics_def_id, index));
2445 // Case 3. Reference to a top-level value.
2446 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2447 path_segs.push(PathSeg(def_id, last));
2450 // Case 4. Reference to a method or associated const.
2451 DefKind::Method | DefKind::AssocConst => {
2452 if segments.len() >= 2 {
2453 let generics = tcx.generics_of(def_id);
2454 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2456 path_segs.push(PathSeg(def_id, last));
2459 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2462 debug!("path_segs = {:?}", path_segs);
2467 // Check a type `Path` and convert it to a `Ty`.
2470 opt_self_ty: Option<Ty<'tcx>>,
2471 path: &hir::Path<'_>,
2472 permit_variants: bool,
2474 let tcx = self.tcx();
2477 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2478 path.res, opt_self_ty, path.segments
2481 let span = path.span;
2483 Res::Def(DefKind::OpaqueTy, did) => {
2484 // Check for desugared `impl Trait`.
2485 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2486 let item_segment = path.segments.split_last().unwrap();
2487 self.prohibit_generics(item_segment.1);
2488 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2489 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2491 Res::Def(DefKind::Enum, did)
2492 | Res::Def(DefKind::TyAlias, did)
2493 | Res::Def(DefKind::Struct, did)
2494 | Res::Def(DefKind::Union, did)
2495 | Res::Def(DefKind::ForeignTy, did) => {
2496 assert_eq!(opt_self_ty, None);
2497 self.prohibit_generics(path.segments.split_last().unwrap().1);
2498 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2500 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2501 // Convert "variant type" as if it were a real type.
2502 // The resulting `Ty` is type of the variant's enum for now.
2503 assert_eq!(opt_self_ty, None);
2506 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2507 let generic_segs: FxHashSet<_> =
2508 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2509 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2511 if !generic_segs.contains(&index) { Some(seg) } else { None }
2515 let PathSeg(def_id, index) = path_segs.last().unwrap();
2516 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2518 Res::Def(DefKind::TyParam, def_id) => {
2519 assert_eq!(opt_self_ty, None);
2520 self.prohibit_generics(path.segments);
2522 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2523 let item_id = tcx.hir().get_parent_node(hir_id);
2524 let item_def_id = tcx.hir().local_def_id(item_id);
2525 let generics = tcx.generics_of(item_def_id);
2526 let index = generics.param_def_id_to_index[&def_id];
2527 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2529 Res::SelfTy(Some(_), None) => {
2530 // `Self` in trait or type alias.
2531 assert_eq!(opt_self_ty, None);
2532 self.prohibit_generics(path.segments);
2533 tcx.types.self_param
2535 Res::SelfTy(_, Some(def_id)) => {
2536 // `Self` in impl (we know the concrete type).
2537 assert_eq!(opt_self_ty, None);
2538 self.prohibit_generics(path.segments);
2539 // Try to evaluate any array length constants.
2540 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2542 Res::Def(DefKind::AssocTy, def_id) => {
2543 debug_assert!(path.segments.len() >= 2);
2544 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2549 &path.segments[path.segments.len() - 2],
2550 path.segments.last().unwrap(),
2553 Res::PrimTy(prim_ty) => {
2554 assert_eq!(opt_self_ty, None);
2555 self.prohibit_generics(path.segments);
2557 hir::Bool => tcx.types.bool,
2558 hir::Char => tcx.types.char,
2559 hir::Int(it) => tcx.mk_mach_int(it),
2560 hir::Uint(uit) => tcx.mk_mach_uint(uit),
2561 hir::Float(ft) => tcx.mk_mach_float(ft),
2562 hir::Str => tcx.mk_str(),
2566 self.set_tainted_by_errors();
2567 return self.tcx().types.err;
2569 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2573 /// Parses the programmer's textual representation of a type into our
2574 /// internal notion of a type.
2575 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2576 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2578 let tcx = self.tcx();
2580 let result_ty = match ast_ty.kind {
2581 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2582 hir::TyKind::Ptr(ref mt) => {
2583 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2585 hir::TyKind::Rptr(ref region, ref mt) => {
2586 let r = self.ast_region_to_region(region, None);
2587 debug!("ast_ty_to_ty: r={:?}", r);
2588 let t = self.ast_ty_to_ty(&mt.ty);
2589 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2591 hir::TyKind::Never => tcx.types.never,
2592 hir::TyKind::Tup(ref fields) => {
2593 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2595 hir::TyKind::BareFn(ref bf) => {
2596 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2597 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl, &[], None))
2599 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2600 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2602 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2603 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2604 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2605 self.res_to_ty(opt_self_ty, path, false)
2607 hir::TyKind::Def(item_id, ref lifetimes) => {
2608 let did = tcx.hir().local_def_id(item_id.id);
2609 self.impl_trait_ty_to_ty(did, lifetimes)
2611 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2612 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2613 let ty = self.ast_ty_to_ty(qself);
2615 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2620 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2621 .map(|(ty, _, _)| ty)
2622 .unwrap_or(tcx.types.err)
2624 hir::TyKind::Array(ref ty, ref length) => {
2625 let length = self.ast_const_to_const(length, tcx.types.usize);
2626 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2627 self.normalize_ty(ast_ty.span, array_ty)
2629 hir::TyKind::Typeof(ref _e) => {
2634 "`typeof` is a reserved keyword but unimplemented"
2636 .span_label(ast_ty.span, "reserved keyword")
2641 hir::TyKind::Infer => {
2642 // Infer also appears as the type of arguments or return
2643 // values in a ExprKind::Closure, or as
2644 // the type of local variables. Both of these cases are
2645 // handled specially and will not descend into this routine.
2646 self.ty_infer(None, ast_ty.span)
2648 hir::TyKind::Err => tcx.types.err,
2651 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2653 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2657 /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2658 pub fn const_param_def_id(&self, expr: &hir::Expr<'_>) -> Option<DefId> {
2659 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2660 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2661 let expr = match &expr.kind {
2662 ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2663 block.expr.as_ref().unwrap()
2669 ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2670 Res::Def(DefKind::ConstParam, did) => Some(did),
2677 pub fn ast_const_to_const(
2679 ast_const: &hir::AnonConst,
2681 ) -> &'tcx ty::Const<'tcx> {
2682 debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2684 let tcx = self.tcx();
2685 let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2687 let mut const_ = ty::Const {
2688 val: ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id)),
2692 let expr = &tcx.hir().body(ast_const.body).value;
2693 if let Some(def_id) = self.const_param_def_id(expr) {
2694 // Find the name and index of the const parameter by indexing the generics of the
2695 // parent item and construct a `ParamConst`.
2696 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2697 let item_id = tcx.hir().get_parent_node(hir_id);
2698 let item_def_id = tcx.hir().local_def_id(item_id);
2699 let generics = tcx.generics_of(item_def_id);
2700 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2701 let name = tcx.hir().name(hir_id);
2702 const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2705 tcx.mk_const(const_)
2708 pub fn impl_trait_ty_to_ty(
2711 lifetimes: &[hir::GenericArg<'_>],
2713 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2714 let tcx = self.tcx();
2716 let generics = tcx.generics_of(def_id);
2718 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2719 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2720 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2721 // Our own parameters are the resolved lifetimes.
2723 GenericParamDefKind::Lifetime => {
2724 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2725 self.ast_region_to_region(lifetime, None).into()
2733 // Replace all parent lifetimes with `'static`.
2735 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2736 _ => tcx.mk_param_from_def(param),
2740 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2742 let ty = tcx.mk_opaque(def_id, substs);
2743 debug!("impl_trait_ty_to_ty: {}", ty);
2747 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2749 hir::TyKind::Infer if expected_ty.is_some() => {
2750 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2751 expected_ty.unwrap()
2753 _ => self.ast_ty_to_ty(ty),
2759 unsafety: hir::Unsafety,
2761 decl: &hir::FnDecl<'_>,
2762 generic_params: &[hir::GenericParam<'_>],
2763 ident_span: Option<Span>,
2764 ) -> ty::PolyFnSig<'tcx> {
2767 let tcx = self.tcx();
2769 // We proactively collect all the infered type params to emit a single error per fn def.
2770 let mut visitor = PlaceholderHirTyCollector::default();
2771 for ty in decl.inputs {
2772 visitor.visit_ty(ty);
2774 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2775 let output_ty = match decl.output {
2776 hir::Return(ref output) => {
2777 visitor.visit_ty(output);
2778 self.ast_ty_to_ty(output)
2780 hir::DefaultReturn(..) => tcx.mk_unit(),
2783 debug!("ty_of_fn: output_ty={:?}", output_ty);
2786 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2788 if !self.allow_ty_infer() {
2789 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2790 // only want to emit an error complaining about them if infer types (`_`) are not
2791 // allowed. `allow_ty_infer` gates this behavior.
2792 crate::collect::placeholder_type_error(
2794 ident_span.unwrap_or(DUMMY_SP),
2797 ident_span.is_some(),
2801 // Find any late-bound regions declared in return type that do
2802 // not appear in the arguments. These are not well-formed.
2805 // for<'a> fn() -> &'a str <-- 'a is bad
2806 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2807 let inputs = bare_fn_ty.inputs();
2808 let late_bound_in_args =
2809 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2810 let output = bare_fn_ty.output();
2811 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2812 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2813 let lifetime_name = match *br {
2814 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2815 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2817 let mut err = struct_span_err!(
2821 "return type references {} \
2822 which is not constrained by the fn input types",
2825 if let ty::BrAnon(_) = *br {
2826 // The only way for an anonymous lifetime to wind up
2827 // in the return type but **also** be unconstrained is
2828 // if it only appears in "associated types" in the
2829 // input. See #47511 for an example. In this case,
2830 // though we can easily give a hint that ought to be
2833 "lifetimes appearing in an associated type \
2834 are not considered constrained",
2843 /// Given the bounds on an object, determines what single region bound (if any) we can
2844 /// use to summarize this type. The basic idea is that we will use the bound the user
2845 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2846 /// for region bounds. It may be that we can derive no bound at all, in which case
2847 /// we return `None`.
2848 fn compute_object_lifetime_bound(
2851 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2852 ) -> Option<ty::Region<'tcx>> // if None, use the default
2854 let tcx = self.tcx();
2856 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2858 // No explicit region bound specified. Therefore, examine trait
2859 // bounds and see if we can derive region bounds from those.
2860 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2862 // If there are no derived region bounds, then report back that we
2863 // can find no region bound. The caller will use the default.
2864 if derived_region_bounds.is_empty() {
2868 // If any of the derived region bounds are 'static, that is always
2870 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2871 return Some(tcx.lifetimes.re_static);
2874 // Determine whether there is exactly one unique region in the set
2875 // of derived region bounds. If so, use that. Otherwise, report an
2877 let r = derived_region_bounds[0];
2878 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2883 "ambiguous lifetime bound, explicit lifetime bound required"
2890 /// Collects together a list of bounds that are applied to some type,
2891 /// after they've been converted into `ty` form (from the HIR
2892 /// representations). These lists of bounds occur in many places in
2896 /// trait Foo: Bar + Baz { }
2897 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2899 /// fn foo<T: Bar + Baz>() { }
2900 /// ^^^^^^^^^ bounding the type parameter `T`
2902 /// impl dyn Bar + Baz
2903 /// ^^^^^^^^^ bounding the forgotten dynamic type
2906 /// Our representation is a bit mixed here -- in some cases, we
2907 /// include the self type (e.g., `trait_bounds`) but in others we do
2908 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2909 pub struct Bounds<'tcx> {
2910 /// A list of region bounds on the (implicit) self type. So if you
2911 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2912 /// the `T` is not explicitly included).
2913 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2915 /// A list of trait bounds. So if you had `T: Debug` this would be
2916 /// `T: Debug`. Note that the self-type is explicit here.
2917 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2919 /// A list of projection equality bounds. So if you had `T:
2920 /// Iterator<Item = u32>` this would include `<T as
2921 /// Iterator>::Item => u32`. Note that the self-type is explicit
2923 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2925 /// `Some` if there is *no* `?Sized` predicate. The `span`
2926 /// is the location in the source of the `T` declaration which can
2927 /// be cited as the source of the `T: Sized` requirement.
2928 pub implicitly_sized: Option<Span>,
2931 impl<'tcx> Bounds<'tcx> {
2932 /// Converts a bounds list into a flat set of predicates (like
2933 /// where-clauses). Because some of our bounds listings (e.g.,
2934 /// regions) don't include the self-type, you must supply the
2935 /// self-type here (the `param_ty` parameter).
2940 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2941 // If it could be sized, and is, add the `Sized` predicate.
2942 let sized_predicate = self.implicitly_sized.and_then(|span| {
2943 tcx.lang_items().sized_trait().map(|sized| {
2944 let trait_ref = ty::Binder::bind(ty::TraitRef {
2946 substs: tcx.mk_substs_trait(param_ty, &[]),
2948 (trait_ref.to_predicate(), span)
2957 .map(|&(region_bound, span)| {
2958 // Account for the binder being introduced below; no need to shift `param_ty`
2959 // because, at present at least, it either only refers to early-bound regions,
2960 // or it's a generic associated type that deliberately has escaping bound vars.
2961 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2962 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2963 (ty::Binder::bind(outlives).to_predicate(), span)
2968 .map(|&(bound_trait_ref, span)| (bound_trait_ref.to_predicate(), span)),
2971 self.projection_bounds
2973 .map(|&(projection, span)| (projection.to_predicate(), span)),