1 // ignore-tidy-filelength FIXME(#67418) Split up this file.
2 //! Conversion from AST representation of types to the `ty.rs` representation.
3 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
4 //! instance of `AstConv`.
6 // ignore-tidy-filelength
8 use crate::collect::PlaceholderHirTyCollector;
9 use crate::middle::resolve_lifetime as rl;
10 use crate::require_c_abi_if_c_variadic;
11 use rustc_ast::util::lev_distance::find_best_match_for_name;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_errors::ErrorReported;
14 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError};
16 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_hir::intravisit::{walk_generics, Visitor as _};
19 use rustc_hir::lang_items::SizedTraitLangItem;
20 use rustc_hir::{Constness, GenericArg, GenericArgs};
21 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
22 use rustc_middle::ty::{
23 self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
25 use rustc_middle::ty::{GenericParamDef, GenericParamDefKind};
26 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS};
27 use rustc_session::parse::feature_err;
28 use rustc_session::Session;
29 use rustc_span::symbol::{sym, Ident, Symbol};
30 use rustc_span::{MultiSpan, Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use rustc_trait_selection::traits;
33 use rustc_trait_selection::traits::astconv_object_safety_violations;
34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
35 use rustc_trait_selection::traits::wf::object_region_bounds;
37 use smallvec::SmallVec;
38 use std::collections::BTreeSet;
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 fn default_constness_for_trait_bounds(&self) -> Constness;
52 /// Returns predicates in scope of the form `X: Foo`, where `X` is
53 /// a type parameter `X` with the given id `def_id`. This is a
54 /// subset of the full set of predicates.
56 /// This is used for one specific purpose: resolving "short-hand"
57 /// associated type references like `T::Item`. In principle, we
58 /// would do that by first getting the full set of predicates in
59 /// scope and then filtering down to find those that apply to `T`,
60 /// but this can lead to cycle errors. The problem is that we have
61 /// to do this resolution *in order to create the predicates in
62 /// the first place*. Hence, we have this "special pass".
63 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
65 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
66 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
67 -> Option<ty::Region<'tcx>>;
69 /// Returns the type to use when a type is omitted.
70 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
72 /// Returns `true` if `_` is allowed in type signatures in the current context.
73 fn allow_ty_infer(&self) -> bool;
75 /// Returns the const to use when a const is omitted.
79 param: Option<&ty::GenericParamDef>,
81 ) -> &'tcx Const<'tcx>;
83 /// Projecting an associated type from a (potentially)
84 /// higher-ranked trait reference is more complicated, because of
85 /// the possibility of late-bound regions appearing in the
86 /// associated type binding. This is not legal in function
87 /// signatures for that reason. In a function body, we can always
88 /// handle it because we can use inference variables to remove the
89 /// late-bound regions.
90 fn projected_ty_from_poly_trait_ref(
94 item_segment: &hir::PathSegment<'_>,
95 poly_trait_ref: ty::PolyTraitRef<'tcx>,
98 /// Normalize an associated type coming from the user.
99 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
101 /// Invoked when we encounter an error from some prior pass
102 /// (e.g., resolve) that is translated into a ty-error. This is
103 /// used to help suppress derived errors typeck might otherwise
105 fn set_tainted_by_errors(&self);
107 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
110 pub enum SizedByDefault {
115 struct ConvertedBinding<'a, 'tcx> {
117 kind: ConvertedBindingKind<'a, 'tcx>,
121 enum ConvertedBindingKind<'a, 'tcx> {
123 Constraint(&'a [hir::GenericBound<'a>]),
127 enum GenericArgPosition {
129 Value, // e.g., functions
133 /// A marker denoting that the generic arguments that were
134 /// provided did not match the respective generic parameters.
135 pub struct GenericArgCountMismatch {
136 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
137 pub reported: Option<ErrorReported>,
138 /// A list of spans of arguments provided that were not valid.
139 pub invalid_args: Vec<Span>,
142 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
143 pub fn ast_region_to_region(
145 lifetime: &hir::Lifetime,
146 def: Option<&ty::GenericParamDef>,
147 ) -> ty::Region<'tcx> {
148 let tcx = self.tcx();
149 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id));
151 let r = match tcx.named_region(lifetime.hir_id) {
152 Some(rl::Region::Static) => tcx.lifetimes.re_static,
154 Some(rl::Region::LateBound(debruijn, id, _)) => {
155 let name = lifetime_name(id.expect_local());
156 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
159 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
160 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
163 Some(rl::Region::EarlyBound(index, id, _)) => {
164 let name = lifetime_name(id.expect_local());
165 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
168 Some(rl::Region::Free(scope, id)) => {
169 let name = lifetime_name(id.expect_local());
170 tcx.mk_region(ty::ReFree(ty::FreeRegion {
172 bound_region: ty::BrNamed(id, name),
175 // (*) -- not late-bound, won't change
179 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
180 // This indicates an illegal lifetime
181 // elision. `resolve_lifetime` should have
182 // reported an error in this case -- but if
183 // not, let's error out.
184 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
186 // Supply some dummy value. We don't have an
187 // `re_error`, annoyingly, so use `'static`.
188 tcx.lifetimes.re_static
193 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
198 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
199 /// returns an appropriate set of substitutions for this particular reference to `I`.
200 pub fn ast_path_substs_for_ty(
204 item_segment: &hir::PathSegment<'_>,
205 ) -> SubstsRef<'tcx> {
206 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
210 item_segment.generic_args(),
211 item_segment.infer_args,
215 if let Some(b) = assoc_bindings.first() {
216 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
222 /// Report error if there is an explicit type parameter when using `impl Trait`.
225 seg: &hir::PathSegment<'_>,
226 generics: &ty::Generics,
228 let explicit = !seg.infer_args;
229 let impl_trait = generics.params.iter().any(|param| match param.kind {
230 ty::GenericParamDefKind::Type {
231 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
237 if explicit && impl_trait {
242 .filter_map(|arg| match arg {
243 GenericArg::Type(_) => Some(arg.span()),
246 .collect::<Vec<_>>();
248 let mut err = struct_span_err! {
252 "cannot provide explicit generic arguments when `impl Trait` is \
253 used in argument position"
257 err.span_label(span, "explicit generic argument not allowed");
266 /// Checks that the correct number of generic arguments have been provided.
267 /// Used specifically for function calls.
268 pub fn check_generic_arg_count_for_call(
272 seg: &hir::PathSegment<'_>,
273 is_method_call: bool,
274 ) -> Result<(), GenericArgCountMismatch> {
275 let empty_args = hir::GenericArgs::none();
276 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
277 Self::check_generic_arg_count(
281 if let Some(ref args) = seg.args { args } else { &empty_args },
282 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
283 def.parent.is_none() && def.has_self, // `has_self`
284 seg.infer_args || suppress_mismatch, // `infer_args`
288 /// Checks that the correct number of generic arguments have been provided.
289 /// This is used both for datatypes and function calls.
290 fn check_generic_arg_count(
294 args: &hir::GenericArgs<'_>,
295 position: GenericArgPosition,
298 ) -> Result<(), GenericArgCountMismatch> {
299 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
300 // that lifetimes will proceed types. So it suffices to check the number of each generic
301 // arguments in order to validate them with respect to the generic parameters.
302 let param_counts = def.own_counts();
303 let arg_counts = args.own_counts();
304 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
306 let mut defaults: ty::GenericParamCount = Default::default();
307 for param in &def.params {
309 GenericParamDefKind::Lifetime => {}
310 GenericParamDefKind::Type { has_default, .. } => {
311 defaults.types += has_default as usize
313 GenericParamDefKind::Const => {
314 // FIXME(const_generics:defaults)
319 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
320 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
323 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
324 let mut explicit_lifetimes = Ok(());
325 if !infer_lifetimes {
326 if let Some(span_late) = def.has_late_bound_regions {
327 let msg = "cannot specify lifetime arguments explicitly \
328 if late bound lifetime parameters are present";
329 let note = "the late bound lifetime parameter is introduced here";
330 let span = args.args[0].span();
331 if position == GenericArgPosition::Value
332 && arg_counts.lifetimes != param_counts.lifetimes
334 explicit_lifetimes = Err(true);
335 let mut err = tcx.sess.struct_span_err(span, msg);
336 err.span_note(span_late, note);
339 explicit_lifetimes = Err(false);
340 let mut multispan = MultiSpan::from_span(span);
341 multispan.push_span_label(span_late, note.to_string());
342 tcx.struct_span_lint_hir(
343 LATE_BOUND_LIFETIME_ARGUMENTS,
346 |lint| lint.build(msg).emit(),
352 let check_kind_count =
353 |kind, required, permitted, provided, offset, unexpected_spans: &mut Vec<Span>| {
355 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
356 kind, required, permitted, provided, offset
358 // We enforce the following: `required` <= `provided` <= `permitted`.
359 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
360 // For other kinds (i.e., types), `permitted` may be greater than `required`.
361 if required <= provided && provided <= permitted {
365 // Unfortunately lifetime and type parameter mismatches are typically styled
366 // differently in diagnostics, which means we have a few cases to consider here.
367 let (bound, quantifier) = if required != permitted {
368 if provided < required {
369 (required, "at least ")
371 // provided > permitted
372 (permitted, "at most ")
378 let (spans, label) = if required == permitted && provided > permitted {
379 // In the case when the user has provided too many arguments,
380 // we want to point to the unexpected arguments.
381 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
383 .map(|arg| arg.span())
385 unexpected_spans.extend(spans.clone());
386 (spans, format!("unexpected {} argument", kind))
391 "expected {}{} {} argument{}",
400 let mut err = tcx.sess.struct_span_err_with_code(
403 "wrong number of {} arguments: expected {}{}, found {}",
404 kind, quantifier, bound, provided,
406 DiagnosticId::Error("E0107".into()),
409 err.span_label(span, label.as_str());
416 let mut arg_count_correct = explicit_lifetimes;
417 let mut unexpected_spans = vec![];
419 if arg_count_correct.is_ok()
420 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
422 arg_count_correct = check_kind_count(
424 param_counts.lifetimes,
425 param_counts.lifetimes,
426 arg_counts.lifetimes,
428 &mut unexpected_spans,
430 .and(arg_count_correct);
432 // FIXME(const_generics:defaults)
433 if !infer_args || arg_counts.consts > param_counts.consts {
434 arg_count_correct = check_kind_count(
439 arg_counts.lifetimes + arg_counts.types,
440 &mut unexpected_spans,
442 .and(arg_count_correct);
444 // Note that type errors are currently be emitted *after* const errors.
445 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
447 arg_count_correct = check_kind_count(
449 param_counts.types - defaults.types - has_self as usize,
450 param_counts.types - has_self as usize,
452 arg_counts.lifetimes,
453 &mut unexpected_spans,
455 .and(arg_count_correct);
458 arg_count_correct.map_err(|reported_err| GenericArgCountMismatch {
459 reported: if reported_err { Some(ErrorReported) } else { None },
460 invalid_args: unexpected_spans,
464 /// Report an error that a generic argument did not match the generic parameter that was
466 fn generic_arg_mismatch_err(sess: &Session, arg: &GenericArg<'_>, kind: &'static str) {
467 let mut err = struct_span_err!(
471 "{} provided when a {} was expected",
475 // This note will be true as long as generic parameters are strictly ordered by their kind.
476 err.note(&format!("{} arguments must be provided before {} arguments", kind, arg.descr()));
480 /// Creates the relevant generic argument substitutions
481 /// corresponding to a set of generic parameters. This is a
482 /// rather complex function. Let us try to explain the role
483 /// of each of its parameters:
485 /// To start, we are given the `def_id` of the thing we are
486 /// creating the substitutions for, and a partial set of
487 /// substitutions `parent_substs`. In general, the substitutions
488 /// for an item begin with substitutions for all the "parents" of
489 /// that item -- e.g., for a method it might include the
490 /// parameters from the impl.
492 /// Therefore, the method begins by walking down these parents,
493 /// starting with the outermost parent and proceed inwards until
494 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
495 /// first to see if the parent's substitutions are listed in there. If so,
496 /// we can append those and move on. Otherwise, it invokes the
497 /// three callback functions:
499 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
500 /// generic arguments that were given to that parent from within
501 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
502 /// might refer to the trait `Foo`, and the arguments might be
503 /// `[T]`. The boolean value indicates whether to infer values
504 /// for arguments whose values were not explicitly provided.
505 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
506 /// instantiate a `GenericArg`.
507 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
508 /// creates a suitable inference variable.
509 pub fn create_substs_for_generic_args<'b>(
512 parent_substs: &[subst::GenericArg<'tcx>],
514 self_ty: Option<Ty<'tcx>>,
515 arg_count_correct: bool,
516 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
517 mut provided_kind: impl FnMut(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
518 mut inferred_kind: impl FnMut(
519 Option<&[subst::GenericArg<'tcx>]>,
522 ) -> subst::GenericArg<'tcx>,
523 ) -> SubstsRef<'tcx> {
524 // Collect the segments of the path; we need to substitute arguments
525 // for parameters throughout the entire path (wherever there are
526 // generic parameters).
527 let mut parent_defs = tcx.generics_of(def_id);
528 let count = parent_defs.count();
529 let mut stack = vec![(def_id, parent_defs)];
530 while let Some(def_id) = parent_defs.parent {
531 parent_defs = tcx.generics_of(def_id);
532 stack.push((def_id, parent_defs));
535 // We manually build up the substitution, rather than using convenience
536 // methods in `subst.rs`, so that we can iterate over the arguments and
537 // parameters in lock-step linearly, instead of trying to match each pair.
538 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
539 // Iterate over each segment of the path.
540 while let Some((def_id, defs)) = stack.pop() {
541 let mut params = defs.params.iter().peekable();
543 // If we have already computed substitutions for parents, we can use those directly.
544 while let Some(¶m) = params.peek() {
545 if let Some(&kind) = parent_substs.get(param.index as usize) {
553 // `Self` is handled first, unless it's been handled in `parent_substs`.
555 if let Some(¶m) = params.peek() {
556 if param.index == 0 {
557 if let GenericParamDefKind::Type { .. } = param.kind {
561 .unwrap_or_else(|| inferred_kind(None, param, true)),
569 // Check whether this segment takes generic arguments and the user has provided any.
570 let (generic_args, infer_args) = args_for_def_id(def_id);
573 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
575 // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
576 // If we later encounter a lifetime, we know that the arguments were provided in the
577 // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
578 // inferred, so we can use it for diagnostics later.
579 let mut force_infer_lt = None;
582 // We're going to iterate through the generic arguments that the user
583 // provided, matching them with the generic parameters we expect.
584 // Mismatches can occur as a result of elided lifetimes, or for malformed
585 // input. We try to handle both sensibly.
586 match (args.peek(), params.peek()) {
587 (Some(&arg), Some(¶m)) => {
588 match (arg, ¶m.kind) {
589 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
590 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
591 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
592 substs.push(provided_kind(param, arg));
597 GenericArg::Type(_) | GenericArg::Const(_),
598 GenericParamDefKind::Lifetime,
600 // We expected a lifetime argument, but got a type or const
601 // argument. That means we're inferring the lifetimes.
602 substs.push(inferred_kind(None, param, infer_args));
603 force_infer_lt = Some(arg);
607 // We expected one kind of parameter, but the user provided
608 // another. This is an error. However, if we already know that
609 // the arguments don't match up with the parameters, we won't issue
610 // an additional error, as the user already knows what's wrong.
611 if arg_count_correct {
612 Self::generic_arg_mismatch_err(tcx.sess, arg, kind.descr());
615 // We've reported the error, but we want to make sure that this
616 // problem doesn't bubble down and create additional, irrelevant
617 // errors. In this case, we're simply going to ignore the argument
618 // and any following arguments. The rest of the parameters will be
620 while args.next().is_some() {}
625 (Some(&arg), None) => {
626 // We should never be able to reach this point with well-formed input.
627 // There are two situations in which we can encounter this issue.
629 // 1. The number of arguments is incorrect. In this case, an error
630 // will already have been emitted, and we can ignore it. This case
631 // also occurs when late-bound lifetime parameters are present, yet
632 // the lifetime arguments have also been explicitly specified by the
634 // 2. We've inferred some lifetimes, which have been provided later (i.e.
635 // after a type or const). We want to throw an error in this case.
637 if arg_count_correct {
638 let kind = arg.descr();
639 assert_eq!(kind, "lifetime");
641 force_infer_lt.expect("lifetimes ought to have been inferred");
642 Self::generic_arg_mismatch_err(tcx.sess, provided, kind);
648 (None, Some(¶m)) => {
649 // If there are fewer arguments than parameters, it means
650 // we're inferring the remaining arguments.
651 substs.push(inferred_kind(Some(&substs), param, infer_args));
655 (None, None) => break,
660 tcx.intern_substs(&substs)
663 /// Given the type/lifetime/const arguments provided to some path (along with
664 /// an implicit `Self`, if this is a trait reference), returns the complete
665 /// set of substitutions. This may involve applying defaulted type parameters.
666 /// Also returns back constraints on associated types.
671 /// T: std::ops::Index<usize, Output = u32>
672 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
675 /// 1. The `self_ty` here would refer to the type `T`.
676 /// 2. The path in question is the path to the trait `std::ops::Index`,
677 /// which will have been resolved to a `def_id`
678 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
679 /// parameters are returned in the `SubstsRef`, the associated type bindings like
680 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
682 /// Note that the type listing given here is *exactly* what the user provided.
684 /// For (generic) associated types
687 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
690 /// We have the parent substs are the substs for the parent trait:
691 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
692 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
693 /// lists: `[Vec<u8>, u8, 'a]`.
694 fn create_substs_for_ast_path<'a>(
698 parent_substs: &[subst::GenericArg<'tcx>],
699 generic_args: &'a hir::GenericArgs<'_>,
701 self_ty: Option<Ty<'tcx>>,
702 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Result<(), GenericArgCountMismatch>)
704 // If the type is parameterized by this region, then replace this
705 // region with the current anon region binding (in other words,
706 // whatever & would get replaced with).
708 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
710 def_id, self_ty, generic_args
713 let tcx = self.tcx();
714 let generic_params = tcx.generics_of(def_id);
716 if generic_params.has_self {
717 if generic_params.parent.is_some() {
718 // The parent is a trait so it should have at least one subst
719 // for the `Self` type.
720 assert!(!parent_substs.is_empty())
722 // This item (presumably a trait) needs a self-type.
723 assert!(self_ty.is_some());
726 assert!(self_ty.is_none() && parent_substs.is_empty());
729 let arg_count_correct = Self::check_generic_arg_count(
734 GenericArgPosition::Type,
739 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
740 let default_needs_object_self = |param: &ty::GenericParamDef| {
741 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
742 if is_object && has_default {
743 let default_ty = tcx.at(span).type_of(param.def_id);
744 let self_param = tcx.types.self_param;
745 if default_ty.walk().any(|arg| arg == self_param.into()) {
746 // There is no suitable inference default for a type parameter
747 // that references self, in an object type.
756 let mut missing_type_params = vec![];
757 let mut inferred_params = vec![];
758 let substs = Self::create_substs_for_generic_args(
764 arg_count_correct.is_ok(),
765 // Provide the generic args, and whether types should be inferred.
768 (Some(generic_args), infer_args)
770 // The last component of this tuple is unimportant.
774 // Provide substitutions for parameters for which (valid) arguments have been provided.
775 |param, arg| match (¶m.kind, arg) {
776 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
777 self.ast_region_to_region(<, Some(param)).into()
779 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
780 if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
781 inferred_params.push(ty.span);
784 self.ast_ty_to_ty(&ty).into()
787 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
788 let ct_def_id = tcx.hir().local_def_id(ct.value.hir_id);
789 ty::Const::from_anon_const(tcx, ct_def_id).into()
793 // Provide substitutions for parameters for which arguments are inferred.
794 |substs, param, infer_args| {
796 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
797 GenericParamDefKind::Type { has_default, .. } => {
798 if !infer_args && has_default {
799 // No type parameter provided, but a default exists.
801 // If we are converting an object type, then the
802 // `Self` parameter is unknown. However, some of the
803 // other type parameters may reference `Self` in their
804 // defaults. This will lead to an ICE if we are not
806 if default_needs_object_self(param) {
807 missing_type_params.push(param.name.to_string());
810 // This is a default type parameter.
813 tcx.at(span).type_of(param.def_id).subst_spanned(
821 } else if infer_args {
822 // No type parameters were provided, we can infer all.
824 if !default_needs_object_self(param) { Some(param) } else { None };
825 self.ty_infer(param, span).into()
827 // We've already errored above about the mismatch.
831 GenericParamDefKind::Const => {
832 let ty = tcx.at(span).type_of(param.def_id);
833 // FIXME(const_generics:defaults)
835 // No const parameters were provided, we can infer all.
836 self.ct_infer(ty, Some(param), span).into()
838 // We've already errored above about the mismatch.
839 tcx.mk_const(ty::Const { val: ty::ConstKind::Error, ty }).into()
846 self.complain_about_missing_type_params(
850 generic_args.args.is_empty(),
853 // Convert associated-type bindings or constraints into a separate vector.
854 // Example: Given this:
856 // T: Iterator<Item = u32>
858 // The `T` is passed in as a self-type; the `Item = u32` is
859 // not a "type parameter" of the `Iterator` trait, but rather
860 // a restriction on `<T as Iterator>::Item`, so it is passed
862 let assoc_bindings = generic_args
866 let kind = match binding.kind {
867 hir::TypeBindingKind::Equality { ref ty } => {
868 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
870 hir::TypeBindingKind::Constraint { ref bounds } => {
871 ConvertedBindingKind::Constraint(bounds)
874 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
879 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
880 generic_params, self_ty, substs
883 (substs, assoc_bindings, arg_count_correct)
886 crate fn create_substs_for_associated_item(
891 item_segment: &hir::PathSegment<'_>,
892 parent_substs: SubstsRef<'tcx>,
893 ) -> SubstsRef<'tcx> {
894 if tcx.generics_of(item_def_id).params.is_empty() {
895 self.prohibit_generics(slice::from_ref(item_segment));
899 self.create_substs_for_ast_path(
903 item_segment.generic_args(),
904 item_segment.infer_args,
911 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
912 /// the type parameter's name as a placeholder.
913 fn complain_about_missing_type_params(
915 missing_type_params: Vec<String>,
918 empty_generic_args: bool,
920 if missing_type_params.is_empty() {
924 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
925 let mut err = struct_span_err!(
929 "the type parameter{} {} must be explicitly specified",
930 pluralize!(missing_type_params.len()),
934 self.tcx().def_span(def_id),
936 "type parameter{} {} must be specified for this",
937 pluralize!(missing_type_params.len()),
941 let mut suggested = false;
942 if let (Ok(snippet), true) = (
943 self.tcx().sess.source_map().span_to_snippet(span),
944 // Don't suggest setting the type params if there are some already: the order is
945 // tricky to get right and the user will already know what the syntax is.
948 if snippet.ends_with('>') {
949 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
950 // we would have to preserve the right order. For now, as clearly the user is
951 // aware of the syntax, we do nothing.
953 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
954 // least we can clue them to the correct syntax `Iterator<Type>`.
958 "set the type parameter{plural} to the desired type{plural}",
959 plural = pluralize!(missing_type_params.len()),
961 format!("{}<{}>", snippet, missing_type_params.join(", ")),
962 Applicability::HasPlaceholders,
971 "missing reference{} to {}",
972 pluralize!(missing_type_params.len()),
978 "because of the default `Self` reference, type parameters must be \
979 specified on object types",
984 /// Instantiates the path for the given trait reference, assuming that it's
985 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
986 /// The type _cannot_ be a type other than a trait type.
988 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
989 /// are disallowed. Otherwise, they are pushed onto the vector given.
990 pub fn instantiate_mono_trait_ref(
992 trait_ref: &hir::TraitRef<'_>,
994 ) -> ty::TraitRef<'tcx> {
995 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
997 self.ast_path_to_mono_trait_ref(
999 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
1001 trait_ref.path.segments.last().unwrap(),
1005 /// The given trait-ref must actually be a trait.
1006 pub(super) fn instantiate_poly_trait_ref_inner(
1008 trait_ref: &hir::TraitRef<'_>,
1010 constness: Constness,
1012 bounds: &mut Bounds<'tcx>,
1014 ) -> Result<(), GenericArgCountMismatch> {
1015 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
1017 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
1019 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1021 let (substs, assoc_bindings, arg_count_correct) = self.create_substs_for_ast_trait_ref(
1022 trait_ref.path.span,
1025 trait_ref.path.segments.last().unwrap(),
1027 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
1029 bounds.trait_bounds.push((poly_trait_ref, span, constness));
1031 let mut dup_bindings = FxHashMap::default();
1032 for binding in &assoc_bindings {
1033 // Specify type to assert that error was already reported in `Err` case.
1034 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
1035 trait_ref.hir_ref_id,
1043 // Okay to ignore `Err` because of `ErrorReported` (see above).
1047 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
1048 trait_ref, bounds, poly_trait_ref
1054 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
1055 /// a full trait reference. The resulting trait reference is returned. This may also generate
1056 /// auxiliary bounds, which are added to `bounds`.
1061 /// poly_trait_ref = Iterator<Item = u32>
1065 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
1067 /// **A note on binders:** against our usual convention, there is an implied bounder around
1068 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
1069 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
1070 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
1071 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
1073 pub fn instantiate_poly_trait_ref(
1075 poly_trait_ref: &hir::PolyTraitRef<'_>,
1076 constness: Constness,
1078 bounds: &mut Bounds<'tcx>,
1079 ) -> Result<(), GenericArgCountMismatch> {
1080 self.instantiate_poly_trait_ref_inner(
1081 &poly_trait_ref.trait_ref,
1082 poly_trait_ref.span,
1090 fn ast_path_to_mono_trait_ref(
1093 trait_def_id: DefId,
1095 trait_segment: &hir::PathSegment<'_>,
1096 ) -> ty::TraitRef<'tcx> {
1097 let (substs, assoc_bindings, _) =
1098 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1099 if let Some(b) = assoc_bindings.first() {
1100 AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span);
1102 ty::TraitRef::new(trait_def_id, substs)
1105 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1106 /// an error and attempt to build a reasonable structured suggestion.
1107 fn complain_about_internal_fn_trait(
1110 trait_def_id: DefId,
1111 trait_segment: &'a hir::PathSegment<'a>,
1113 let trait_def = self.tcx().trait_def(trait_def_id);
1115 if !self.tcx().features().unboxed_closures
1116 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1118 let sess = &self.tcx().sess.parse_sess;
1119 // For now, require that parenthetical notation be used only with `Fn()` etc.
1120 let (msg, sugg) = if trait_def.paren_sugar {
1122 "the precise format of `Fn`-family traits' type parameters is subject to \
1126 trait_segment.ident,
1130 .and_then(|args| args.args.get(0))
1131 .and_then(|arg| match arg {
1132 hir::GenericArg::Type(ty) => {
1133 sess.source_map().span_to_snippet(ty.span).ok()
1137 .unwrap_or_else(|| "()".to_string()),
1142 .find_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1143 (true, hir::TypeBindingKind::Equality { ty }) => {
1144 sess.source_map().span_to_snippet(ty.span).ok()
1148 .unwrap_or_else(|| "()".to_string()),
1152 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1154 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1155 if let Some(sugg) = sugg {
1156 let msg = "use parenthetical notation instead";
1157 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1163 fn create_substs_for_ast_trait_ref<'a>(
1166 trait_def_id: DefId,
1168 trait_segment: &'a hir::PathSegment<'a>,
1169 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Result<(), GenericArgCountMismatch>)
1171 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1173 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1175 self.create_substs_for_ast_path(
1179 trait_segment.generic_args(),
1180 trait_segment.infer_args,
1185 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
1187 .associated_items(trait_def_id)
1188 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
1192 // Returns `true` if a bounds list includes `?Sized`.
1193 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1194 let tcx = self.tcx();
1196 // Try to find an unbound in bounds.
1197 let mut unbound = None;
1198 for ab in ast_bounds {
1199 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1200 if unbound.is_none() {
1201 unbound = Some(&ptr.trait_ref);
1207 "type parameter has more than one relaxed default \
1208 bound, only one is supported"
1215 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1218 // FIXME(#8559) currently requires the unbound to be built-in.
1219 if let Ok(kind_id) = kind_id {
1220 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1223 "default bound relaxed for a type parameter, but \
1224 this does nothing because the given bound is not \
1225 a default; only `?Sized` is supported",
1230 _ if kind_id.is_ok() => {
1233 // No lang item for `Sized`, so we can't add it as a bound.
1240 /// This helper takes a *converted* parameter type (`param_ty`)
1241 /// and an *unconverted* list of bounds:
1244 /// fn foo<T: Debug>
1245 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1247 /// `param_ty`, in ty form
1250 /// It adds these `ast_bounds` into the `bounds` structure.
1252 /// **A note on binders:** there is an implied binder around
1253 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1254 /// for more details.
1258 ast_bounds: &[hir::GenericBound<'_>],
1259 bounds: &mut Bounds<'tcx>,
1261 let mut trait_bounds = Vec::new();
1262 let mut region_bounds = Vec::new();
1264 let constness = self.default_constness_for_trait_bounds();
1265 for ast_bound in ast_bounds {
1267 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1268 trait_bounds.push((b, constness))
1270 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
1271 trait_bounds.push((b, Constness::NotConst))
1273 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1274 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1278 for (bound, constness) in trait_bounds {
1279 let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
1282 bounds.region_bounds.extend(
1283 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1287 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1288 /// The self-type for the bounds is given by `param_ty`.
1293 /// fn foo<T: Bar + Baz>() { }
1294 /// ^ ^^^^^^^^^ ast_bounds
1298 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1299 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1300 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1302 /// `span` should be the declaration size of the parameter.
1303 pub fn compute_bounds(
1306 ast_bounds: &[hir::GenericBound<'_>],
1307 sized_by_default: SizedByDefault,
1310 let mut bounds = Bounds::default();
1312 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1313 bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
1315 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1316 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1324 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1327 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1328 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1329 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1330 fn add_predicates_for_ast_type_binding(
1332 hir_ref_id: hir::HirId,
1333 trait_ref: ty::PolyTraitRef<'tcx>,
1334 binding: &ConvertedBinding<'_, 'tcx>,
1335 bounds: &mut Bounds<'tcx>,
1337 dup_bindings: &mut FxHashMap<DefId, Span>,
1339 ) -> Result<(), ErrorReported> {
1340 let tcx = self.tcx();
1343 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1344 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1345 // subtle in the event that `T` is defined in a supertrait of
1346 // `SomeTrait`, because in that case we need to upcast.
1348 // That is, consider this case:
1351 // trait SubTrait: SuperTrait<int> { }
1352 // trait SuperTrait<A> { type T; }
1354 // ... B: SubTrait<T = foo> ...
1357 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1359 // Find any late-bound regions declared in `ty` that are not
1360 // declared in the trait-ref. These are not well-formed.
1364 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1365 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1366 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1367 let late_bound_in_trait_ref =
1368 tcx.collect_constrained_late_bound_regions(&trait_ref);
1369 let late_bound_in_ty =
1370 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1371 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1372 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1373 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1374 let br_name = match *br {
1375 ty::BrNamed(_, name) => name,
1379 "anonymous bound region {:?} in binding but not trait ref",
1384 // FIXME: point at the type params that don't have appropriate lifetimes:
1385 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1386 // ---- ---- ^^^^^^^
1391 "binding for associated type `{}` references lifetime `{}`, \
1392 which does not appear in the trait input types",
1402 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1403 // Simple case: X is defined in the current trait.
1406 // Otherwise, we have to walk through the supertraits to find
1408 self.one_bound_for_assoc_type(
1409 || traits::supertraits(tcx, trait_ref),
1410 || trait_ref.print_only_trait_path().to_string(),
1413 || match binding.kind {
1414 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1420 let (assoc_ident, def_scope) =
1421 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1423 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1424 // of calling `filter_by_name_and_kind`.
1426 .associated_items(candidate.def_id())
1427 .filter_by_name_unhygienic(assoc_ident.name)
1429 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1431 .expect("missing associated type");
1433 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1437 &format!("associated type `{}` is private", binding.item_name),
1439 .span_label(binding.span, "private associated type")
1442 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1446 .entry(assoc_ty.def_id)
1447 .and_modify(|prev_span| {
1452 "the value of the associated type `{}` (from trait `{}`) \
1453 is already specified",
1455 tcx.def_path_str(assoc_ty.container.id())
1457 .span_label(binding.span, "re-bound here")
1458 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1461 .or_insert(binding.span);
1464 match binding.kind {
1465 ConvertedBindingKind::Equality(ref ty) => {
1466 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1467 // the "projection predicate" for:
1469 // `<T as Iterator>::Item = u32`
1470 bounds.projection_bounds.push((
1471 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1472 projection_ty: ty::ProjectionTy::from_ref_and_name(
1482 ConvertedBindingKind::Constraint(ast_bounds) => {
1483 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1485 // `<T as Iterator>::Item: Debug`
1487 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1488 // parameter to have a skipped binder.
1489 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1490 self.add_bounds(param_ty, ast_bounds, bounds);
1500 item_segment: &hir::PathSegment<'_>,
1502 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1503 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1506 fn conv_object_ty_poly_trait_ref(
1509 trait_bounds: &[hir::PolyTraitRef<'_>],
1510 lifetime: &hir::Lifetime,
1512 let tcx = self.tcx();
1514 let mut bounds = Bounds::default();
1515 let mut potential_assoc_types = Vec::new();
1516 let dummy_self = self.tcx().types.trait_object_dummy_self;
1517 for trait_bound in trait_bounds.iter().rev() {
1518 if let Err(GenericArgCountMismatch {
1519 invalid_args: cur_potential_assoc_types, ..
1520 }) = self.instantiate_poly_trait_ref(
1522 Constness::NotConst,
1526 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1530 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1531 // is used and no 'maybe' bounds are used.
1532 let expanded_traits =
1533 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1534 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1535 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1536 if regular_traits.len() > 1 {
1537 let first_trait = ®ular_traits[0];
1538 let additional_trait = ®ular_traits[1];
1539 let mut err = struct_span_err!(
1541 additional_trait.bottom().1,
1543 "only auto traits can be used as additional traits in a trait object"
1545 additional_trait.label_with_exp_info(
1547 "additional non-auto trait",
1550 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1554 if regular_traits.is_empty() && auto_traits.is_empty() {
1559 "at least one trait is required for an object type"
1562 return tcx.types.err;
1565 // Check that there are no gross object safety violations;
1566 // most importantly, that the supertraits don't contain `Self`,
1568 for item in ®ular_traits {
1569 let object_safety_violations =
1570 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1571 if !object_safety_violations.is_empty() {
1572 report_object_safety_error(
1575 item.trait_ref().def_id(),
1576 &object_safety_violations[..],
1579 return tcx.types.err;
1583 // Use a `BTreeSet` to keep output in a more consistent order.
1584 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1586 let regular_traits_refs_spans = bounds
1589 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1591 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1592 assert_eq!(constness, Constness::NotConst);
1594 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1596 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1597 obligation.predicate
1599 match obligation.predicate {
1600 ty::PredicateKind::Trait(pred, _) => {
1601 associated_types.entry(span).or_default().extend(
1602 tcx.associated_items(pred.def_id())
1603 .in_definition_order()
1604 .filter(|item| item.kind == ty::AssocKind::Type)
1605 .map(|item| item.def_id),
1608 ty::PredicateKind::Projection(pred) => {
1609 // A `Self` within the original bound will be substituted with a
1610 // `trait_object_dummy_self`, so check for that.
1611 let references_self =
1612 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1614 // If the projection output contains `Self`, force the user to
1615 // elaborate it explicitly to avoid a lot of complexity.
1617 // The "classicaly useful" case is the following:
1619 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1624 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1625 // but actually supporting that would "expand" to an infinitely-long type
1626 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1628 // Instead, we force the user to write
1629 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1630 // the discussion in #56288 for alternatives.
1631 if !references_self {
1632 // Include projections defined on supertraits.
1633 bounds.projection_bounds.push((pred, span));
1641 for (projection_bound, _) in &bounds.projection_bounds {
1642 for def_ids in associated_types.values_mut() {
1643 def_ids.remove(&projection_bound.projection_def_id());
1647 self.complain_about_missing_associated_types(
1649 potential_assoc_types,
1653 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1654 // `dyn Trait + Send`.
1655 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1656 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1657 debug!("regular_traits: {:?}", regular_traits);
1658 debug!("auto_traits: {:?}", auto_traits);
1660 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1661 // removing the dummy `Self` type (`trait_object_dummy_self`).
1662 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1663 if trait_ref.self_ty() != dummy_self {
1664 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1665 // which picks up non-supertraits where clauses - but also, the object safety
1666 // completely ignores trait aliases, which could be object safety hazards. We
1667 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1668 // disabled. (#66420)
1669 tcx.sess.delay_span_bug(
1672 "trait_ref_to_existential called on {:?} with non-dummy Self",
1677 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1680 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1681 let existential_trait_refs =
1682 regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1683 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1684 bound.map_bound(|b| {
1685 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1686 ty::ExistentialProjection {
1688 item_def_id: b.projection_ty.item_def_id,
1689 substs: trait_ref.substs,
1694 // Calling `skip_binder` is okay because the predicates are re-bound.
1695 let regular_trait_predicates = existential_trait_refs
1696 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1697 let auto_trait_predicates = auto_traits
1699 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1700 let mut v = regular_trait_predicates
1701 .chain(auto_trait_predicates)
1703 existential_projections
1704 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1706 .collect::<SmallVec<[_; 8]>>();
1707 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1709 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1711 // Use explicitly-specified region bound.
1712 let region_bound = if !lifetime.is_elided() {
1713 self.ast_region_to_region(lifetime, None)
1715 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1716 if tcx.named_region(lifetime.hir_id).is_some() {
1717 self.ast_region_to_region(lifetime, None)
1719 self.re_infer(None, span).unwrap_or_else(|| {
1720 // FIXME: these can be redundant with E0106, but not always.
1725 "the lifetime bound for this object type cannot be deduced \
1726 from context; please supply an explicit bound"
1729 tcx.lifetimes.re_static
1734 debug!("region_bound: {:?}", region_bound);
1736 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1737 debug!("trait_object_type: {:?}", ty);
1741 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1742 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1743 /// same trait bound have the same name (as they come from different super-traits), we instead
1744 /// emit a generic note suggesting using a `where` clause to constraint instead.
1745 fn complain_about_missing_associated_types(
1747 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1748 potential_assoc_types: Vec<Span>,
1749 trait_bounds: &[hir::PolyTraitRef<'_>],
1751 if associated_types.values().all(|v| v.is_empty()) {
1754 let tcx = self.tcx();
1755 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1756 // appropriate one, but this should be handled earlier in the span assignment.
1757 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1759 .map(|(span, def_ids)| {
1760 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1763 let mut names = vec![];
1765 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1766 // `issue-22560.rs`.
1767 let mut trait_bound_spans: Vec<Span> = vec![];
1768 for (span, items) in &associated_types {
1769 if !items.is_empty() {
1770 trait_bound_spans.push(*span);
1772 for assoc_item in items {
1773 let trait_def_id = assoc_item.container.id();
1775 "`{}` (from trait `{}`)",
1777 tcx.def_path_str(trait_def_id),
1781 if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
1782 match &bound.trait_ref.path.segments[..] {
1783 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1784 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1785 // around that bug here, even though it should be fixed elsewhere.
1786 // This would otherwise cause an invalid suggestion. For an example, look at
1787 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1789 // error[E0191]: the value of the associated type `Output`
1790 // (from trait `std::ops::BitXor`) must be specified
1791 // --> $DIR/issue-28344.rs:4:17
1793 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1794 // | ^^^^^^ help: specify the associated type:
1795 // | `BitXor<Output = Type>`
1799 // error[E0191]: the value of the associated type `Output`
1800 // (from trait `std::ops::BitXor`) must be specified
1801 // --> $DIR/issue-28344.rs:4:17
1803 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1804 // | ^^^^^^^^^^^^^ help: specify the associated type:
1805 // | `BitXor::bitor<Output = Type>`
1806 [segment] if segment.args.is_none() => {
1807 trait_bound_spans = vec![segment.ident.span];
1808 associated_types = associated_types
1810 .map(|(_, items)| (segment.ident.span, items))
1817 trait_bound_spans.sort();
1818 let mut err = struct_span_err!(
1822 "the value of the associated type{} {} must be specified",
1823 pluralize!(names.len()),
1826 let mut suggestions = vec![];
1827 let mut types_count = 0;
1828 let mut where_constraints = vec![];
1829 for (span, assoc_items) in &associated_types {
1830 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1831 for item in assoc_items {
1833 *names.entry(item.ident.name).or_insert(0) += 1;
1835 let mut dupes = false;
1836 for item in assoc_items {
1837 let prefix = if names[&item.ident.name] > 1 {
1838 let trait_def_id = item.container.id();
1840 format!("{}::", tcx.def_path_str(trait_def_id))
1844 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1845 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1848 if potential_assoc_types.len() == assoc_items.len() {
1849 // Only suggest when the amount of missing associated types equals the number of
1850 // extra type arguments present, as that gives us a relatively high confidence
1851 // that the user forgot to give the associtated type's name. The canonical
1852 // example would be trying to use `Iterator<isize>` instead of
1853 // `Iterator<Item = isize>`.
1854 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1855 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1856 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1859 } else if let (Ok(snippet), false) =
1860 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1863 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1864 let code = if snippet.ends_with('>') {
1865 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1866 // suggest, but at least we can clue them to the correct syntax
1867 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1869 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1871 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1872 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1873 format!("{}<{}>", snippet, types.join(", "))
1875 suggestions.push((*span, code));
1877 where_constraints.push(*span);
1880 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1881 using the fully-qualified path to the associated types";
1882 if !where_constraints.is_empty() && suggestions.is_empty() {
1883 // If there are duplicates associated type names and a single trait bound do not
1884 // use structured suggestion, it means that there are multiple super-traits with
1885 // the same associated type name.
1886 err.help(where_msg);
1888 if suggestions.len() != 1 {
1889 // We don't need this label if there's an inline suggestion, show otherwise.
1890 for (span, assoc_items) in &associated_types {
1891 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1892 for item in assoc_items {
1894 *names.entry(item.ident.name).or_insert(0) += 1;
1896 let mut label = vec![];
1897 for item in assoc_items {
1898 let postfix = if names[&item.ident.name] > 1 {
1899 let trait_def_id = item.container.id();
1900 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1904 label.push(format!("`{}`{}", item.ident, postfix));
1906 if !label.is_empty() {
1910 "associated type{} {} must be specified",
1911 pluralize!(label.len()),
1918 if !suggestions.is_empty() {
1919 err.multipart_suggestion(
1920 &format!("specify the associated type{}", pluralize!(types_count)),
1922 Applicability::HasPlaceholders,
1924 if !where_constraints.is_empty() {
1925 err.span_help(where_constraints, where_msg);
1931 fn report_ambiguous_associated_type(
1938 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1939 if let (Some(_), Ok(snippet)) = (
1940 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1941 self.tcx().sess.source_map().span_to_snippet(span),
1943 err.span_suggestion(
1945 "you are looking for the module in `std`, not the primitive type",
1946 format!("std::{}", snippet),
1947 Applicability::MachineApplicable,
1950 err.span_suggestion(
1952 "use fully-qualified syntax",
1953 format!("<{} as {}>::{}", type_str, trait_str, name),
1954 Applicability::HasPlaceholders,
1960 // Search for a bound on a type parameter which includes the associated item
1961 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1962 // This function will fail if there are no suitable bounds or there is
1964 fn find_bound_for_assoc_item(
1966 ty_param_def_id: LocalDefId,
1969 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1970 let tcx = self.tcx();
1973 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1974 ty_param_def_id, assoc_name, span,
1978 &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
1980 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1982 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id);
1983 let param_name = tcx.hir().ty_param_name(param_hir_id);
1984 self.one_bound_for_assoc_type(
1986 traits::transitive_bounds(
1988 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1991 || param_name.to_string(),
1998 // Checks that `bounds` contains exactly one element and reports appropriate
1999 // errors otherwise.
2000 fn one_bound_for_assoc_type<I>(
2002 all_candidates: impl Fn() -> I,
2003 ty_param_name: impl Fn() -> String,
2006 is_equality: impl Fn() -> Option<String>,
2007 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
2009 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2011 let mut matching_candidates = all_candidates()
2012 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
2014 let bound = match matching_candidates.next() {
2015 Some(bound) => bound,
2017 self.complain_about_assoc_type_not_found(
2023 return Err(ErrorReported);
2027 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
2029 if let Some(bound2) = matching_candidates.next() {
2030 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
2032 let is_equality = is_equality();
2033 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
2034 let mut err = if is_equality.is_some() {
2035 // More specific Error Index entry.
2040 "ambiguous associated type `{}` in bounds of `{}`",
2049 "ambiguous associated type `{}` in bounds of `{}`",
2054 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
2056 let mut where_bounds = vec![];
2057 for bound in bounds {
2058 let bound_id = bound.def_id();
2059 let bound_span = self
2061 .associated_items(bound_id)
2062 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
2063 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
2065 if let Some(bound_span) = bound_span {
2069 "ambiguous `{}` from `{}`",
2071 bound.print_only_trait_path(),
2074 if let Some(constraint) = &is_equality {
2075 where_bounds.push(format!(
2076 " T: {trait}::{assoc} = {constraint}",
2077 trait=bound.print_only_trait_path(),
2079 constraint=constraint,
2082 err.span_suggestion(
2084 "use fully qualified syntax to disambiguate",
2088 bound.print_only_trait_path(),
2091 Applicability::MaybeIncorrect,
2096 "associated type `{}` could derive from `{}`",
2098 bound.print_only_trait_path(),
2102 if !where_bounds.is_empty() {
2104 "consider introducing a new type parameter `T` and adding `where` constraints:\
2105 \n where\n T: {},\n{}",
2107 where_bounds.join(",\n"),
2111 if !where_bounds.is_empty() {
2112 return Err(ErrorReported);
2118 fn complain_about_assoc_type_not_found<I>(
2120 all_candidates: impl Fn() -> I,
2121 ty_param_name: &str,
2125 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2127 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2128 // valid span, so we point at the whole path segment instead.
2129 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2130 let mut err = struct_span_err!(
2134 "associated type `{}` not found for `{}`",
2139 let all_candidate_names: Vec<_> = all_candidates()
2140 .map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
2143 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2147 if let (Some(suggested_name), true) = (
2148 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2149 assoc_name.span != DUMMY_SP,
2151 err.span_suggestion(
2153 "there is an associated type with a similar name",
2154 suggested_name.to_string(),
2155 Applicability::MaybeIncorrect,
2158 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2164 // Create a type from a path to an associated type.
2165 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2166 // and item_segment is the path segment for `D`. We return a type and a def for
2168 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2169 // parameter or `Self`.
2170 pub fn associated_path_to_ty(
2172 hir_ref_id: hir::HirId,
2176 assoc_segment: &hir::PathSegment<'_>,
2177 permit_variants: bool,
2178 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2179 let tcx = self.tcx();
2180 let assoc_ident = assoc_segment.ident;
2182 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2184 // Check if we have an enum variant.
2185 let mut variant_resolution = None;
2186 if let ty::Adt(adt_def, _) = qself_ty.kind {
2187 if adt_def.is_enum() {
2188 let variant_def = adt_def
2191 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2192 if let Some(variant_def) = variant_def {
2193 if permit_variants {
2194 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2195 self.prohibit_generics(slice::from_ref(assoc_segment));
2196 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2198 variant_resolution = Some(variant_def.def_id);
2204 // Find the type of the associated item, and the trait where the associated
2205 // item is declared.
2206 let bound = match (&qself_ty.kind, qself_res) {
2207 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2208 // `Self` in an impl of a trait -- we have a concrete self type and a
2210 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2211 Some(trait_ref) => trait_ref,
2213 // A cycle error occurred, most likely.
2214 return Err(ErrorReported);
2218 self.one_bound_for_assoc_type(
2219 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2220 || "Self".to_string(),
2228 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
2229 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2231 if variant_resolution.is_some() {
2232 // Variant in type position
2233 let msg = format!("expected type, found variant `{}`", assoc_ident);
2234 tcx.sess.span_err(span, &msg);
2235 } else if qself_ty.is_enum() {
2236 let mut err = struct_span_err!(
2240 "no variant named `{}` found for enum `{}`",
2245 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2246 if let Some(suggested_name) = find_best_match_for_name(
2247 adt_def.variants.iter().map(|variant| &variant.ident.name),
2248 &assoc_ident.as_str(),
2251 err.span_suggestion(
2253 "there is a variant with a similar name",
2254 suggested_name.to_string(),
2255 Applicability::MaybeIncorrect,
2260 format!("variant not found in `{}`", qself_ty),
2264 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2265 let sp = tcx.sess.source_map().guess_head_span(sp);
2266 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2270 } else if !qself_ty.references_error() {
2271 // Don't print `TyErr` to the user.
2272 self.report_ambiguous_associated_type(
2274 &qself_ty.to_string(),
2279 return Err(ErrorReported);
2283 let trait_did = bound.def_id();
2284 let (assoc_ident, def_scope) =
2285 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2287 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2288 // of calling `filter_by_name_and_kind`.
2290 .associated_items(trait_did)
2291 .in_definition_order()
2293 i.kind.namespace() == Namespace::TypeNS
2294 && i.ident.normalize_to_macros_2_0() == assoc_ident
2296 .expect("missing associated type");
2298 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2299 let ty = self.normalize_ty(span, ty);
2301 let kind = DefKind::AssocTy;
2302 if !item.vis.is_accessible_from(def_scope, tcx) {
2303 let kind = kind.descr(item.def_id);
2304 let msg = format!("{} `{}` is private", kind, assoc_ident);
2306 .struct_span_err(span, &msg)
2307 .span_label(span, &format!("private {}", kind))
2310 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2312 if let Some(variant_def_id) = variant_resolution {
2313 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2314 let mut err = lint.build("ambiguous associated item");
2315 let mut could_refer_to = |kind: DefKind, def_id, also| {
2316 let note_msg = format!(
2317 "`{}` could{} refer to the {} defined here",
2322 err.span_note(tcx.def_span(def_id), ¬e_msg);
2325 could_refer_to(DefKind::Variant, variant_def_id, "");
2326 could_refer_to(kind, item.def_id, " also");
2328 err.span_suggestion(
2330 "use fully-qualified syntax",
2331 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2332 Applicability::MachineApplicable,
2338 Ok((ty, kind, item.def_id))
2344 opt_self_ty: Option<Ty<'tcx>>,
2346 trait_segment: &hir::PathSegment<'_>,
2347 item_segment: &hir::PathSegment<'_>,
2349 let tcx = self.tcx();
2351 let trait_def_id = tcx.parent(item_def_id).unwrap();
2353 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2355 let self_ty = if let Some(ty) = opt_self_ty {
2358 let path_str = tcx.def_path_str(trait_def_id);
2360 let def_id = self.item_def_id();
2362 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2364 let parent_def_id = def_id
2365 .and_then(|def_id| {
2366 def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id))
2368 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
2370 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2372 // If the trait in segment is the same as the trait defining the item,
2373 // use the `<Self as ..>` syntax in the error.
2374 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2375 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2377 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2383 self.report_ambiguous_associated_type(
2387 item_segment.ident.name,
2389 return tcx.types.err;
2392 debug!("qpath_to_ty: self_type={:?}", self_ty);
2394 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2396 let item_substs = self.create_substs_for_associated_item(
2404 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2406 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2409 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2413 let mut has_err = false;
2414 for segment in segments {
2415 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2416 for arg in segment.generic_args().args {
2417 let (span, kind) = match arg {
2418 hir::GenericArg::Lifetime(lt) => {
2424 (lt.span, "lifetime")
2426 hir::GenericArg::Type(ty) => {
2434 hir::GenericArg::Const(ct) => {
2443 let mut err = struct_span_err!(
2447 "{} arguments are not allowed for this type",
2450 err.span_label(span, format!("{} argument not allowed", kind));
2452 if err_for_lt && err_for_ty && err_for_ct {
2457 // Only emit the first error to avoid overloading the user with error messages.
2458 if let [binding, ..] = segment.generic_args().bindings {
2460 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2466 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2467 let mut err = struct_span_err!(
2471 "associated type bindings are not allowed here"
2473 err.span_label(span, "associated type not allowed here").emit();
2476 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2477 pub fn def_ids_for_value_path_segments(
2479 segments: &[hir::PathSegment<'_>],
2480 self_ty: Option<Ty<'tcx>>,
2484 // We need to extract the type parameters supplied by the user in
2485 // the path `path`. Due to the current setup, this is a bit of a
2486 // tricky-process; the problem is that resolve only tells us the
2487 // end-point of the path resolution, and not the intermediate steps.
2488 // Luckily, we can (at least for now) deduce the intermediate steps
2489 // just from the end-point.
2491 // There are basically five cases to consider:
2493 // 1. Reference to a constructor of a struct:
2495 // struct Foo<T>(...)
2497 // In this case, the parameters are declared in the type space.
2499 // 2. Reference to a constructor of an enum variant:
2501 // enum E<T> { Foo(...) }
2503 // In this case, the parameters are defined in the type space,
2504 // but may be specified either on the type or the variant.
2506 // 3. Reference to a fn item or a free constant:
2510 // In this case, the path will again always have the form
2511 // `a::b::foo::<T>` where only the final segment should have
2512 // type parameters. However, in this case, those parameters are
2513 // declared on a value, and hence are in the `FnSpace`.
2515 // 4. Reference to a method or an associated constant:
2517 // impl<A> SomeStruct<A> {
2521 // Here we can have a path like
2522 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2523 // may appear in two places. The penultimate segment,
2524 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2525 // final segment, `foo::<B>` contains parameters in fn space.
2527 // The first step then is to categorize the segments appropriately.
2529 let tcx = self.tcx();
2531 assert!(!segments.is_empty());
2532 let last = segments.len() - 1;
2534 let mut path_segs = vec![];
2537 // Case 1. Reference to a struct constructor.
2538 DefKind::Ctor(CtorOf::Struct, ..) => {
2539 // Everything but the final segment should have no
2540 // parameters at all.
2541 let generics = tcx.generics_of(def_id);
2542 // Variant and struct constructors use the
2543 // generics of their parent type definition.
2544 let generics_def_id = generics.parent.unwrap_or(def_id);
2545 path_segs.push(PathSeg(generics_def_id, last));
2548 // Case 2. Reference to a variant constructor.
2549 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2550 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2551 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2552 debug_assert!(adt_def.is_enum());
2554 } else if last >= 1 && segments[last - 1].args.is_some() {
2555 // Everything but the penultimate segment should have no
2556 // parameters at all.
2557 let mut def_id = def_id;
2559 // `DefKind::Ctor` -> `DefKind::Variant`
2560 if let DefKind::Ctor(..) = kind {
2561 def_id = tcx.parent(def_id).unwrap()
2564 // `DefKind::Variant` -> `DefKind::Enum`
2565 let enum_def_id = tcx.parent(def_id).unwrap();
2566 (enum_def_id, last - 1)
2568 // FIXME: lint here recommending `Enum::<...>::Variant` form
2569 // instead of `Enum::Variant::<...>` form.
2571 // Everything but the final segment should have no
2572 // parameters at all.
2573 let generics = tcx.generics_of(def_id);
2574 // Variant and struct constructors use the
2575 // generics of their parent type definition.
2576 (generics.parent.unwrap_or(def_id), last)
2578 path_segs.push(PathSeg(generics_def_id, index));
2581 // Case 3. Reference to a top-level value.
2582 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2583 path_segs.push(PathSeg(def_id, last));
2586 // Case 4. Reference to a method or associated const.
2587 DefKind::AssocFn | DefKind::AssocConst => {
2588 if segments.len() >= 2 {
2589 let generics = tcx.generics_of(def_id);
2590 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2592 path_segs.push(PathSeg(def_id, last));
2595 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2598 debug!("path_segs = {:?}", path_segs);
2603 // Check a type `Path` and convert it to a `Ty`.
2606 opt_self_ty: Option<Ty<'tcx>>,
2607 path: &hir::Path<'_>,
2608 permit_variants: bool,
2610 let tcx = self.tcx();
2613 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2614 path.res, opt_self_ty, path.segments
2617 let span = path.span;
2619 Res::Def(DefKind::OpaqueTy, did) => {
2620 // Check for desugared `impl Trait`.
2621 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2622 let item_segment = path.segments.split_last().unwrap();
2623 self.prohibit_generics(item_segment.1);
2624 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2625 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2632 | DefKind::ForeignTy,
2635 assert_eq!(opt_self_ty, None);
2636 self.prohibit_generics(path.segments.split_last().unwrap().1);
2637 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2639 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2640 // Convert "variant type" as if it were a real type.
2641 // The resulting `Ty` is type of the variant's enum for now.
2642 assert_eq!(opt_self_ty, None);
2645 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2646 let generic_segs: FxHashSet<_> =
2647 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2648 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2650 if !generic_segs.contains(&index) { Some(seg) } else { None }
2654 let PathSeg(def_id, index) = path_segs.last().unwrap();
2655 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2657 Res::Def(DefKind::TyParam, def_id) => {
2658 assert_eq!(opt_self_ty, None);
2659 self.prohibit_generics(path.segments);
2661 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
2662 let item_id = tcx.hir().get_parent_node(hir_id);
2663 let item_def_id = tcx.hir().local_def_id(item_id);
2664 let generics = tcx.generics_of(item_def_id);
2665 let index = generics.param_def_id_to_index[&def_id];
2666 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2668 Res::SelfTy(Some(_), None) => {
2669 // `Self` in trait or type alias.
2670 assert_eq!(opt_self_ty, None);
2671 self.prohibit_generics(path.segments);
2672 tcx.types.self_param
2674 Res::SelfTy(_, Some(def_id)) => {
2675 // `Self` in impl (we know the concrete type).
2676 assert_eq!(opt_self_ty, None);
2677 self.prohibit_generics(path.segments);
2678 // Try to evaluate any array length constants.
2679 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2681 Res::Def(DefKind::AssocTy, def_id) => {
2682 debug_assert!(path.segments.len() >= 2);
2683 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2688 &path.segments[path.segments.len() - 2],
2689 path.segments.last().unwrap(),
2692 Res::PrimTy(prim_ty) => {
2693 assert_eq!(opt_self_ty, None);
2694 self.prohibit_generics(path.segments);
2696 hir::PrimTy::Bool => tcx.types.bool,
2697 hir::PrimTy::Char => tcx.types.char,
2698 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2699 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2700 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2701 hir::PrimTy::Str => tcx.mk_str(),
2705 self.set_tainted_by_errors();
2706 self.tcx().types.err
2708 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2712 /// Parses the programmer's textual representation of a type into our
2713 /// internal notion of a type.
2714 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2715 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2717 let tcx = self.tcx();
2719 let result_ty = match ast_ty.kind {
2720 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2721 hir::TyKind::Ptr(ref mt) => {
2722 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2724 hir::TyKind::Rptr(ref region, ref mt) => {
2725 let r = self.ast_region_to_region(region, None);
2726 debug!("ast_ty_to_ty: r={:?}", r);
2727 let t = self.ast_ty_to_ty(&mt.ty);
2728 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2730 hir::TyKind::Never => tcx.types.never,
2731 hir::TyKind::Tup(ref fields) => {
2732 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2734 hir::TyKind::BareFn(ref bf) => {
2735 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2736 tcx.mk_fn_ptr(self.ty_of_fn(
2740 &hir::Generics::empty(),
2744 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2745 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2747 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2748 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2749 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2750 self.res_to_ty(opt_self_ty, path, false)
2752 hir::TyKind::Def(item_id, ref lifetimes) => {
2753 let did = tcx.hir().local_def_id(item_id.id);
2754 self.impl_trait_ty_to_ty(did.to_def_id(), lifetimes)
2756 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2757 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2758 let ty = self.ast_ty_to_ty(qself);
2760 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2765 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2766 .map(|(ty, _, _)| ty)
2767 .unwrap_or(tcx.types.err)
2769 hir::TyKind::Array(ref ty, ref length) => {
2770 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2771 let length = ty::Const::from_anon_const(tcx, length_def_id);
2772 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2773 self.normalize_ty(ast_ty.span, array_ty)
2775 hir::TyKind::Typeof(ref _e) => {
2780 "`typeof` is a reserved keyword but unimplemented"
2782 .span_label(ast_ty.span, "reserved keyword")
2787 hir::TyKind::Infer => {
2788 // Infer also appears as the type of arguments or return
2789 // values in a ExprKind::Closure, or as
2790 // the type of local variables. Both of these cases are
2791 // handled specially and will not descend into this routine.
2792 self.ty_infer(None, ast_ty.span)
2794 hir::TyKind::Err => tcx.types.err,
2797 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2799 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2803 pub fn impl_trait_ty_to_ty(
2806 lifetimes: &[hir::GenericArg<'_>],
2808 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2809 let tcx = self.tcx();
2811 let generics = tcx.generics_of(def_id);
2813 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2814 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2815 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2816 // Our own parameters are the resolved lifetimes.
2818 GenericParamDefKind::Lifetime => {
2819 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2820 self.ast_region_to_region(lifetime, None).into()
2828 // Replace all parent lifetimes with `'static`.
2830 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2831 _ => tcx.mk_param_from_def(param),
2835 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2837 let ty = tcx.mk_opaque(def_id, substs);
2838 debug!("impl_trait_ty_to_ty: {}", ty);
2842 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2844 hir::TyKind::Infer if expected_ty.is_some() => {
2845 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2846 expected_ty.unwrap()
2848 _ => self.ast_ty_to_ty(ty),
2854 unsafety: hir::Unsafety,
2856 decl: &hir::FnDecl<'_>,
2857 generics: &hir::Generics<'_>,
2858 ident_span: Option<Span>,
2859 ) -> ty::PolyFnSig<'tcx> {
2862 let tcx = self.tcx();
2864 // We proactively collect all the inferred type params to emit a single error per fn def.
2865 let mut visitor = PlaceholderHirTyCollector::default();
2866 for ty in decl.inputs {
2867 visitor.visit_ty(ty);
2869 walk_generics(&mut visitor, generics);
2871 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2872 let output_ty = match decl.output {
2873 hir::FnRetTy::Return(ref output) => {
2874 visitor.visit_ty(output);
2875 self.ast_ty_to_ty(output)
2877 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2880 debug!("ty_of_fn: output_ty={:?}", output_ty);
2883 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2885 if let (false, Some(ident_span)) = (self.allow_ty_infer(), ident_span) {
2886 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2887 // only want to emit an error complaining about them if infer types (`_`) are not
2888 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2889 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2890 crate::collect::placeholder_type_error(
2892 ident_span.shrink_to_hi(),
2893 &generics.params[..],
2899 // Find any late-bound regions declared in return type that do
2900 // not appear in the arguments. These are not well-formed.
2903 // for<'a> fn() -> &'a str <-- 'a is bad
2904 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2905 let inputs = bare_fn_ty.inputs();
2906 let late_bound_in_args =
2907 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2908 let output = bare_fn_ty.output();
2909 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2910 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2911 let lifetime_name = match *br {
2912 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2913 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2915 let mut err = struct_span_err!(
2919 "return type references {} which is not constrained by the fn input types",
2922 if let ty::BrAnon(_) = *br {
2923 // The only way for an anonymous lifetime to wind up
2924 // in the return type but **also** be unconstrained is
2925 // if it only appears in "associated types" in the
2926 // input. See #47511 for an example. In this case,
2927 // though we can easily give a hint that ought to be
2930 "lifetimes appearing in an associated type are not considered constrained",
2939 /// Given the bounds on an object, determines what single region bound (if any) we can
2940 /// use to summarize this type. The basic idea is that we will use the bound the user
2941 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2942 /// for region bounds. It may be that we can derive no bound at all, in which case
2943 /// we return `None`.
2944 fn compute_object_lifetime_bound(
2947 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2948 ) -> Option<ty::Region<'tcx>> // if None, use the default
2950 let tcx = self.tcx();
2952 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2954 // No explicit region bound specified. Therefore, examine trait
2955 // bounds and see if we can derive region bounds from those.
2956 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2958 // If there are no derived region bounds, then report back that we
2959 // can find no region bound. The caller will use the default.
2960 if derived_region_bounds.is_empty() {
2964 // If any of the derived region bounds are 'static, that is always
2966 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2967 return Some(tcx.lifetimes.re_static);
2970 // Determine whether there is exactly one unique region in the set
2971 // of derived region bounds. If so, use that. Otherwise, report an
2973 let r = derived_region_bounds[0];
2974 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2979 "ambiguous lifetime bound, explicit lifetime bound required"
2987 /// Collects together a list of bounds that are applied to some type,
2988 /// after they've been converted into `ty` form (from the HIR
2989 /// representations). These lists of bounds occur in many places in
2993 /// trait Foo: Bar + Baz { }
2994 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2996 /// fn foo<T: Bar + Baz>() { }
2997 /// ^^^^^^^^^ bounding the type parameter `T`
2999 /// impl dyn Bar + Baz
3000 /// ^^^^^^^^^ bounding the forgotten dynamic type
3003 /// Our representation is a bit mixed here -- in some cases, we
3004 /// include the self type (e.g., `trait_bounds`) but in others we do
3005 #[derive(Default, PartialEq, Eq, Clone, Debug)]
3006 pub struct Bounds<'tcx> {
3007 /// A list of region bounds on the (implicit) self type. So if you
3008 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
3009 /// the `T` is not explicitly included).
3010 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
3012 /// A list of trait bounds. So if you had `T: Debug` this would be
3013 /// `T: Debug`. Note that the self-type is explicit here.
3014 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>,
3016 /// A list of projection equality bounds. So if you had `T:
3017 /// Iterator<Item = u32>` this would include `<T as
3018 /// Iterator>::Item => u32`. Note that the self-type is explicit
3020 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
3022 /// `Some` if there is *no* `?Sized` predicate. The `span`
3023 /// is the location in the source of the `T` declaration which can
3024 /// be cited as the source of the `T: Sized` requirement.
3025 pub implicitly_sized: Option<Span>,
3028 impl<'tcx> Bounds<'tcx> {
3029 /// Converts a bounds list into a flat set of predicates (like
3030 /// where-clauses). Because some of our bounds listings (e.g.,
3031 /// regions) don't include the self-type, you must supply the
3032 /// self-type here (the `param_ty` parameter).
3037 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
3038 // If it could be sized, and is, add the `Sized` predicate.
3039 let sized_predicate = self.implicitly_sized.and_then(|span| {
3040 tcx.lang_items().sized_trait().map(|sized| {
3041 let trait_ref = ty::Binder::bind(ty::TraitRef {
3043 substs: tcx.mk_substs_trait(param_ty, &[]),
3045 (trait_ref.without_const().to_predicate(), span)
3054 .map(|&(region_bound, span)| {
3055 // Account for the binder being introduced below; no need to shift `param_ty`
3056 // because, at present at least, it either only refers to early-bound regions,
3057 // or it's a generic associated type that deliberately has escaping bound vars.
3058 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
3059 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
3060 (ty::Binder::bind(outlives).to_predicate(), span)
3062 .chain(self.trait_bounds.iter().map(|&(bound_trait_ref, span, constness)| {
3063 let predicate = bound_trait_ref.with_constness(constness).to_predicate();
3067 self.projection_bounds
3069 .map(|&(projection, span)| (projection.to_predicate(), span)),