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;
12 use rustc_ast::util::lev_distance::find_best_match_for_name;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_errors::ErrorReported;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError};
17 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
18 use rustc_hir::def_id::{DefId, LocalDefId};
19 use rustc_hir::intravisit::{walk_generics, Visitor as _};
20 use rustc_hir::lang_items::SizedTraitLangItem;
21 use rustc_hir::{Constness, GenericArg, GenericArgs};
22 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
23 use rustc_middle::ty::{
24 self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
26 use rustc_middle::ty::{GenericParamDef, GenericParamDefKind};
27 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS};
28 use rustc_session::parse::feature_err;
29 use rustc_session::Session;
30 use rustc_span::symbol::sym;
31 use rustc_span::{MultiSpan, Span, DUMMY_SP};
32 use rustc_target::spec::abi;
33 use rustc_trait_selection::traits;
34 use rustc_trait_selection::traits::astconv_object_safety_violations;
35 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
36 use rustc_trait_selection::traits::wf::object_region_bounds;
38 use smallvec::SmallVec;
39 use std::collections::BTreeSet;
44 pub struct PathSeg(pub DefId, pub usize);
46 pub trait AstConv<'tcx> {
47 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
49 fn item_def_id(&self) -> Option<DefId>;
51 fn default_constness_for_trait_bounds(&self) -> Constness;
53 /// Returns predicates in scope of the form `X: Foo`, where `X` is
54 /// a type parameter `X` with the given id `def_id`. This is a
55 /// subset of the full set of predicates.
57 /// This is used for one specific purpose: resolving "short-hand"
58 /// associated type references like `T::Item`. In principle, we
59 /// would do that by first getting the full set of predicates in
60 /// scope and then filtering down to find those that apply to `T`,
61 /// but this can lead to cycle errors. The problem is that we have
62 /// to do this resolution *in order to create the predicates in
63 /// the first place*. Hence, we have this "special pass".
64 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
66 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
67 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
68 -> Option<ty::Region<'tcx>>;
70 /// Returns the type to use when a type is omitted.
71 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
73 /// Returns `true` if `_` is allowed in type signatures in the current context.
74 fn allow_ty_infer(&self) -> bool;
76 /// Returns the const to use when a const is omitted.
80 param: Option<&ty::GenericParamDef>,
82 ) -> &'tcx Const<'tcx>;
84 /// Projecting an associated type from a (potentially)
85 /// higher-ranked trait reference is more complicated, because of
86 /// the possibility of late-bound regions appearing in the
87 /// associated type binding. This is not legal in function
88 /// signatures for that reason. In a function body, we can always
89 /// handle it because we can use inference variables to remove the
90 /// late-bound regions.
91 fn projected_ty_from_poly_trait_ref(
95 item_segment: &hir::PathSegment<'_>,
96 poly_trait_ref: ty::PolyTraitRef<'tcx>,
99 /// Normalize an associated type coming from the user.
100 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
102 /// Invoked when we encounter an error from some prior pass
103 /// (e.g., resolve) that is translated into a ty-error. This is
104 /// used to help suppress derived errors typeck might otherwise
106 fn set_tainted_by_errors(&self);
108 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
111 pub enum SizedByDefault {
116 struct ConvertedBinding<'a, 'tcx> {
117 item_name: ast::Ident,
118 kind: ConvertedBindingKind<'a, 'tcx>,
122 enum ConvertedBindingKind<'a, 'tcx> {
124 Constraint(&'a [hir::GenericBound<'a>]),
128 enum GenericArgPosition {
130 Value, // e.g., functions
134 /// A marker denoting that the generic arguments that were
135 /// provided did not match the respective generic parameters.
136 pub struct GenericArgCountMismatch {
137 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
138 pub reported: Option<ErrorReported>,
139 /// A list of spans of arguments provided that were not valid.
140 pub invalid_args: Vec<Span>,
143 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
144 pub fn ast_region_to_region(
146 lifetime: &hir::Lifetime,
147 def: Option<&ty::GenericParamDef>,
148 ) -> ty::Region<'tcx> {
149 let tcx = self.tcx();
150 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id));
152 let r = match tcx.named_region(lifetime.hir_id) {
153 Some(rl::Region::Static) => tcx.lifetimes.re_static,
155 Some(rl::Region::LateBound(debruijn, id, _)) => {
156 let name = lifetime_name(id.expect_local());
157 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
160 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
161 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
164 Some(rl::Region::EarlyBound(index, id, _)) => {
165 let name = lifetime_name(id.expect_local());
166 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
169 Some(rl::Region::Free(scope, id)) => {
170 let name = lifetime_name(id.expect_local());
171 tcx.mk_region(ty::ReFree(ty::FreeRegion {
173 bound_region: ty::BrNamed(id, name),
176 // (*) -- not late-bound, won't change
180 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
181 // This indicates an illegal lifetime
182 // elision. `resolve_lifetime` should have
183 // reported an error in this case -- but if
184 // not, let's error out.
185 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
187 // Supply some dummy value. We don't have an
188 // `re_error`, annoyingly, so use `'static`.
189 tcx.lifetimes.re_static
194 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
199 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
200 /// returns an appropriate set of substitutions for this particular reference to `I`.
201 pub fn ast_path_substs_for_ty(
205 item_segment: &hir::PathSegment<'_>,
206 ) -> SubstsRef<'tcx> {
207 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
211 item_segment.generic_args(),
212 item_segment.infer_args,
216 if let Some(b) = assoc_bindings.first() {
217 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
223 /// Report error if there is an explicit type parameter when using `impl Trait`.
226 seg: &hir::PathSegment<'_>,
227 generics: &ty::Generics,
229 let explicit = !seg.infer_args;
230 let impl_trait = generics.params.iter().any(|param| match param.kind {
231 ty::GenericParamDefKind::Type {
232 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
238 if explicit && impl_trait {
243 .filter_map(|arg| match arg {
244 GenericArg::Type(_) => Some(arg.span()),
247 .collect::<Vec<_>>();
249 let mut err = struct_span_err! {
253 "cannot provide explicit generic arguments when `impl Trait` is \
254 used in argument position"
258 err.span_label(span, "explicit generic argument not allowed");
267 /// Checks that the correct number of generic arguments have been provided.
268 /// Used specifically for function calls.
269 pub fn check_generic_arg_count_for_call(
273 seg: &hir::PathSegment<'_>,
274 is_method_call: bool,
275 ) -> Result<(), GenericArgCountMismatch> {
276 let empty_args = hir::GenericArgs::none();
277 let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
278 Self::check_generic_arg_count(
282 if let Some(ref args) = seg.args { args } else { &empty_args },
283 if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
284 def.parent.is_none() && def.has_self, // `has_self`
285 seg.infer_args || suppress_mismatch, // `infer_args`
289 /// Checks that the correct number of generic arguments have been provided.
290 /// This is used both for datatypes and function calls.
291 fn check_generic_arg_count(
295 args: &hir::GenericArgs<'_>,
296 position: GenericArgPosition,
299 ) -> Result<(), GenericArgCountMismatch> {
300 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
301 // that lifetimes will proceed types. So it suffices to check the number of each generic
302 // arguments in order to validate them with respect to the generic parameters.
303 let param_counts = def.own_counts();
304 let arg_counts = args.own_counts();
305 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
307 let mut defaults: ty::GenericParamCount = Default::default();
308 for param in &def.params {
310 GenericParamDefKind::Lifetime => {}
311 GenericParamDefKind::Type { has_default, .. } => {
312 defaults.types += has_default as usize
314 GenericParamDefKind::Const => {
315 // FIXME(const_generics:defaults)
320 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
321 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
324 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
325 let mut explicit_lifetimes = Ok(());
326 if !infer_lifetimes {
327 if let Some(span_late) = def.has_late_bound_regions {
328 let msg = "cannot specify lifetime arguments explicitly \
329 if late bound lifetime parameters are present";
330 let note = "the late bound lifetime parameter is introduced here";
331 let span = args.args[0].span();
332 if position == GenericArgPosition::Value
333 && arg_counts.lifetimes != param_counts.lifetimes
335 explicit_lifetimes = Err(true);
336 let mut err = tcx.sess.struct_span_err(span, msg);
337 err.span_note(span_late, note);
340 explicit_lifetimes = Err(false);
341 let mut multispan = MultiSpan::from_span(span);
342 multispan.push_span_label(span_late, note.to_string());
343 tcx.struct_span_lint_hir(
344 LATE_BOUND_LIFETIME_ARGUMENTS,
347 |lint| lint.build(msg).emit(),
353 let check_kind_count =
354 |kind, required, permitted, provided, offset, unexpected_spans: &mut Vec<Span>| {
356 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
357 kind, required, permitted, provided, offset
359 // We enforce the following: `required` <= `provided` <= `permitted`.
360 // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
361 // For other kinds (i.e., types), `permitted` may be greater than `required`.
362 if required <= provided && provided <= permitted {
366 // Unfortunately lifetime and type parameter mismatches are typically styled
367 // differently in diagnostics, which means we have a few cases to consider here.
368 let (bound, quantifier) = if required != permitted {
369 if provided < required {
370 (required, "at least ")
372 // provided > permitted
373 (permitted, "at most ")
379 let (spans, label) = if required == permitted && provided > permitted {
380 // In the case when the user has provided too many arguments,
381 // we want to point to the unexpected arguments.
382 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
384 .map(|arg| arg.span())
386 unexpected_spans.extend(spans.clone());
387 (spans, format!("unexpected {} argument", kind))
392 "expected {}{} {} argument{}",
401 let mut err = tcx.sess.struct_span_err_with_code(
404 "wrong number of {} arguments: expected {}{}, found {}",
405 kind, quantifier, bound, provided,
407 DiagnosticId::Error("E0107".into()),
410 err.span_label(span, label.as_str());
417 let mut arg_count_correct = explicit_lifetimes;
418 let mut unexpected_spans = vec![];
420 if arg_count_correct.is_ok()
421 && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
423 arg_count_correct = check_kind_count(
425 param_counts.lifetimes,
426 param_counts.lifetimes,
427 arg_counts.lifetimes,
429 &mut unexpected_spans,
431 .and(arg_count_correct);
433 // FIXME(const_generics:defaults)
434 if !infer_args || arg_counts.consts > param_counts.consts {
435 arg_count_correct = check_kind_count(
440 arg_counts.lifetimes + arg_counts.types,
441 &mut unexpected_spans,
443 .and(arg_count_correct);
445 // Note that type errors are currently be emitted *after* const errors.
446 if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
448 arg_count_correct = check_kind_count(
450 param_counts.types - defaults.types - has_self as usize,
451 param_counts.types - has_self as usize,
453 arg_counts.lifetimes,
454 &mut unexpected_spans,
456 .and(arg_count_correct);
459 arg_count_correct.map_err(|reported_err| GenericArgCountMismatch {
460 reported: if reported_err { Some(ErrorReported) } else { None },
461 invalid_args: unexpected_spans,
465 /// Report an error that a generic argument did not match the generic parameter that was
467 fn generic_arg_mismatch_err(sess: &Session, arg: &GenericArg<'_>, kind: &'static str) {
468 let mut err = struct_span_err!(
472 "{} provided when a {} was expected",
476 // This note will be true as long as generic parameters are strictly ordered by their kind.
477 err.note(&format!("{} arguments must be provided before {} arguments", kind, arg.descr()));
481 /// Creates the relevant generic argument substitutions
482 /// corresponding to a set of generic parameters. This is a
483 /// rather complex function. Let us try to explain the role
484 /// of each of its parameters:
486 /// To start, we are given the `def_id` of the thing we are
487 /// creating the substitutions for, and a partial set of
488 /// substitutions `parent_substs`. In general, the substitutions
489 /// for an item begin with substitutions for all the "parents" of
490 /// that item -- e.g., for a method it might include the
491 /// parameters from the impl.
493 /// Therefore, the method begins by walking down these parents,
494 /// starting with the outermost parent and proceed inwards until
495 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
496 /// first to see if the parent's substitutions are listed in there. If so,
497 /// we can append those and move on. Otherwise, it invokes the
498 /// three callback functions:
500 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
501 /// generic arguments that were given to that parent from within
502 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
503 /// might refer to the trait `Foo`, and the arguments might be
504 /// `[T]`. The boolean value indicates whether to infer values
505 /// for arguments whose values were not explicitly provided.
506 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
507 /// instantiate a `GenericArg`.
508 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
509 /// creates a suitable inference variable.
510 pub fn create_substs_for_generic_args<'b>(
513 parent_substs: &[subst::GenericArg<'tcx>],
515 self_ty: Option<Ty<'tcx>>,
516 arg_count_correct: bool,
517 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
518 mut provided_kind: impl FnMut(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
519 mut inferred_kind: impl FnMut(
520 Option<&[subst::GenericArg<'tcx>]>,
523 ) -> subst::GenericArg<'tcx>,
524 ) -> SubstsRef<'tcx> {
525 // Collect the segments of the path; we need to substitute arguments
526 // for parameters throughout the entire path (wherever there are
527 // generic parameters).
528 let mut parent_defs = tcx.generics_of(def_id);
529 let count = parent_defs.count();
530 let mut stack = vec![(def_id, parent_defs)];
531 while let Some(def_id) = parent_defs.parent {
532 parent_defs = tcx.generics_of(def_id);
533 stack.push((def_id, parent_defs));
536 // We manually build up the substitution, rather than using convenience
537 // methods in `subst.rs`, so that we can iterate over the arguments and
538 // parameters in lock-step linearly, instead of trying to match each pair.
539 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
540 // Iterate over each segment of the path.
541 while let Some((def_id, defs)) = stack.pop() {
542 let mut params = defs.params.iter().peekable();
544 // If we have already computed substitutions for parents, we can use those directly.
545 while let Some(¶m) = params.peek() {
546 if let Some(&kind) = parent_substs.get(param.index as usize) {
554 // `Self` is handled first, unless it's been handled in `parent_substs`.
556 if let Some(¶m) = params.peek() {
557 if param.index == 0 {
558 if let GenericParamDefKind::Type { .. } = param.kind {
562 .unwrap_or_else(|| inferred_kind(None, param, true)),
570 // Check whether this segment takes generic arguments and the user has provided any.
571 let (generic_args, infer_args) = args_for_def_id(def_id);
574 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
576 // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
577 // If we later encounter a lifetime, we know that the arguments were provided in the
578 // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
579 // inferred, so we can use it for diagnostics later.
580 let mut force_infer_lt = None;
583 // We're going to iterate through the generic arguments that the user
584 // provided, matching them with the generic parameters we expect.
585 // Mismatches can occur as a result of elided lifetimes, or for malformed
586 // input. We try to handle both sensibly.
587 match (args.peek(), params.peek()) {
588 (Some(&arg), Some(¶m)) => {
589 match (arg, ¶m.kind) {
590 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
591 | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
592 | (GenericArg::Const(_), GenericParamDefKind::Const) => {
593 substs.push(provided_kind(param, arg));
598 GenericArg::Type(_) | GenericArg::Const(_),
599 GenericParamDefKind::Lifetime,
601 // We expected a lifetime argument, but got a type or const
602 // argument. That means we're inferring the lifetimes.
603 substs.push(inferred_kind(None, param, infer_args));
604 force_infer_lt = Some(arg);
608 // We expected one kind of parameter, but the user provided
609 // another. This is an error. However, if we already know that
610 // the arguments don't match up with the parameters, we won't issue
611 // an additional error, as the user already knows what's wrong.
612 if arg_count_correct {
613 Self::generic_arg_mismatch_err(tcx.sess, arg, kind.descr());
616 // We've reported the error, but we want to make sure that this
617 // problem doesn't bubble down and create additional, irrelevant
618 // errors. In this case, we're simply going to ignore the argument
619 // and any following arguments. The rest of the parameters will be
621 while args.next().is_some() {}
626 (Some(&arg), None) => {
627 // We should never be able to reach this point with well-formed input.
628 // There are two situations in which we can encounter this issue.
630 // 1. The number of arguments is incorrect. In this case, an error
631 // will already have been emitted, and we can ignore it. This case
632 // also occurs when late-bound lifetime parameters are present, yet
633 // the lifetime arguments have also been explicitly specified by the
635 // 2. We've inferred some lifetimes, which have been provided later (i.e.
636 // after a type or const). We want to throw an error in this case.
638 if arg_count_correct {
639 let kind = arg.descr();
640 assert_eq!(kind, "lifetime");
642 force_infer_lt.expect("lifetimes ought to have been inferred");
643 Self::generic_arg_mismatch_err(tcx.sess, provided, kind);
649 (None, Some(¶m)) => {
650 // If there are fewer arguments than parameters, it means
651 // we're inferring the remaining arguments.
652 substs.push(inferred_kind(Some(&substs), param, infer_args));
656 (None, None) => break,
661 tcx.intern_substs(&substs)
664 /// Given the type/lifetime/const arguments provided to some path (along with
665 /// an implicit `Self`, if this is a trait reference), returns the complete
666 /// set of substitutions. This may involve applying defaulted type parameters.
667 /// Also returns back constraints on associated types.
672 /// T: std::ops::Index<usize, Output = u32>
673 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
676 /// 1. The `self_ty` here would refer to the type `T`.
677 /// 2. The path in question is the path to the trait `std::ops::Index`,
678 /// which will have been resolved to a `def_id`
679 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
680 /// parameters are returned in the `SubstsRef`, the associated type bindings like
681 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
683 /// Note that the type listing given here is *exactly* what the user provided.
685 /// For (generic) associated types
688 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
691 /// We have the parent substs are the substs for the parent trait:
692 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
693 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
694 /// lists: `[Vec<u8>, u8, 'a]`.
695 fn create_substs_for_ast_path<'a>(
699 parent_substs: &[subst::GenericArg<'tcx>],
700 generic_args: &'a hir::GenericArgs<'_>,
702 self_ty: Option<Ty<'tcx>>,
703 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Result<(), GenericArgCountMismatch>)
705 // If the type is parameterized by this region, then replace this
706 // region with the current anon region binding (in other words,
707 // whatever & would get replaced with).
709 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
711 def_id, self_ty, generic_args
714 let tcx = self.tcx();
715 let generic_params = tcx.generics_of(def_id);
717 if generic_params.has_self {
718 if generic_params.parent.is_some() {
719 // The parent is a trait so it should have at least one subst
720 // for the `Self` type.
721 assert!(!parent_substs.is_empty())
723 // This item (presumably a trait) needs a self-type.
724 assert!(self_ty.is_some());
727 assert!(self_ty.is_none() && parent_substs.is_empty());
730 let arg_count_correct = Self::check_generic_arg_count(
735 GenericArgPosition::Type,
740 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
741 let default_needs_object_self = |param: &ty::GenericParamDef| {
742 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
743 if is_object && has_default {
744 let default_ty = tcx.at(span).type_of(param.def_id);
745 let self_param = tcx.types.self_param;
746 if default_ty.walk().any(|arg| arg == self_param.into()) {
747 // There is no suitable inference default for a type parameter
748 // that references self, in an object type.
757 let mut missing_type_params = vec![];
758 let mut inferred_params = vec![];
759 let substs = Self::create_substs_for_generic_args(
765 arg_count_correct.is_ok(),
766 // Provide the generic args, and whether types should be inferred.
769 (Some(generic_args), infer_args)
771 // The last component of this tuple is unimportant.
775 // Provide substitutions for parameters for which (valid) arguments have been provided.
776 |param, arg| match (¶m.kind, arg) {
777 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
778 self.ast_region_to_region(<, Some(param)).into()
780 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
781 if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
782 inferred_params.push(ty.span);
785 self.ast_ty_to_ty(&ty).into()
788 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
789 let ct_def_id = tcx.hir().local_def_id(ct.value.hir_id);
790 ty::Const::from_anon_const(tcx, ct_def_id).into()
794 // Provide substitutions for parameters for which arguments are inferred.
795 |substs, param, infer_args| {
797 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
798 GenericParamDefKind::Type { has_default, .. } => {
799 if !infer_args && has_default {
800 // No type parameter provided, but a default exists.
802 // If we are converting an object type, then the
803 // `Self` parameter is unknown. However, some of the
804 // other type parameters may reference `Self` in their
805 // defaults. This will lead to an ICE if we are not
807 if default_needs_object_self(param) {
808 missing_type_params.push(param.name.to_string());
811 // This is a default type parameter.
814 tcx.at(span).type_of(param.def_id).subst_spanned(
822 } else if infer_args {
823 // No type parameters were provided, we can infer all.
825 if !default_needs_object_self(param) { Some(param) } else { None };
826 self.ty_infer(param, span).into()
828 // We've already errored above about the mismatch.
832 GenericParamDefKind::Const => {
833 let ty = tcx.at(span).type_of(param.def_id);
834 // FIXME(const_generics:defaults)
836 // No const parameters were provided, we can infer all.
837 self.ct_infer(ty, Some(param), span).into()
839 // We've already errored above about the mismatch.
840 tcx.mk_const(ty::Const { val: ty::ConstKind::Error, ty }).into()
847 self.complain_about_missing_type_params(
851 generic_args.args.is_empty(),
854 // Convert associated-type bindings or constraints into a separate vector.
855 // Example: Given this:
857 // T: Iterator<Item = u32>
859 // The `T` is passed in as a self-type; the `Item = u32` is
860 // not a "type parameter" of the `Iterator` trait, but rather
861 // a restriction on `<T as Iterator>::Item`, so it is passed
863 let assoc_bindings = generic_args
867 let kind = match binding.kind {
868 hir::TypeBindingKind::Equality { ref ty } => {
869 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
871 hir::TypeBindingKind::Constraint { ref bounds } => {
872 ConvertedBindingKind::Constraint(bounds)
875 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
880 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
881 generic_params, self_ty, substs
884 (substs, assoc_bindings, arg_count_correct)
887 crate fn create_substs_for_associated_item(
892 item_segment: &hir::PathSegment<'_>,
893 parent_substs: SubstsRef<'tcx>,
894 ) -> SubstsRef<'tcx> {
895 if tcx.generics_of(item_def_id).params.is_empty() {
896 self.prohibit_generics(slice::from_ref(item_segment));
900 self.create_substs_for_ast_path(
904 item_segment.generic_args(),
905 item_segment.infer_args,
912 /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
913 /// the type parameter's name as a placeholder.
914 fn complain_about_missing_type_params(
916 missing_type_params: Vec<String>,
919 empty_generic_args: bool,
921 if missing_type_params.is_empty() {
925 missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
926 let mut err = struct_span_err!(
930 "the type parameter{} {} must be explicitly specified",
931 pluralize!(missing_type_params.len()),
935 self.tcx().def_span(def_id),
937 "type parameter{} {} must be specified for this",
938 pluralize!(missing_type_params.len()),
942 let mut suggested = false;
943 if let (Ok(snippet), true) = (
944 self.tcx().sess.source_map().span_to_snippet(span),
945 // Don't suggest setting the type params if there are some already: the order is
946 // tricky to get right and the user will already know what the syntax is.
949 if snippet.ends_with('>') {
950 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
951 // we would have to preserve the right order. For now, as clearly the user is
952 // aware of the syntax, we do nothing.
954 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
955 // least we can clue them to the correct syntax `Iterator<Type>`.
959 "set the type parameter{plural} to the desired type{plural}",
960 plural = pluralize!(missing_type_params.len()),
962 format!("{}<{}>", snippet, missing_type_params.join(", ")),
963 Applicability::HasPlaceholders,
972 "missing reference{} to {}",
973 pluralize!(missing_type_params.len()),
979 "because of the default `Self` reference, type parameters must be \
980 specified on object types",
985 /// Instantiates the path for the given trait reference, assuming that it's
986 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
987 /// The type _cannot_ be a type other than a trait type.
989 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
990 /// are disallowed. Otherwise, they are pushed onto the vector given.
991 pub fn instantiate_mono_trait_ref(
993 trait_ref: &hir::TraitRef<'_>,
995 ) -> ty::TraitRef<'tcx> {
996 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
998 self.ast_path_to_mono_trait_ref(
1000 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
1002 trait_ref.path.segments.last().unwrap(),
1006 /// The given trait-ref must actually be a trait.
1007 pub(super) fn instantiate_poly_trait_ref_inner(
1009 trait_ref: &hir::TraitRef<'_>,
1011 constness: Constness,
1013 bounds: &mut Bounds<'tcx>,
1015 ) -> Result<(), GenericArgCountMismatch> {
1016 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
1018 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
1020 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1022 let (substs, assoc_bindings, arg_count_correct) = self.create_substs_for_ast_trait_ref(
1023 trait_ref.path.span,
1026 trait_ref.path.segments.last().unwrap(),
1028 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
1030 bounds.trait_bounds.push((poly_trait_ref, span, constness));
1032 let mut dup_bindings = FxHashMap::default();
1033 for binding in &assoc_bindings {
1034 // Specify type to assert that error was already reported in `Err` case.
1035 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
1036 trait_ref.hir_ref_id,
1044 // Okay to ignore `Err` because of `ErrorReported` (see above).
1048 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
1049 trait_ref, bounds, poly_trait_ref
1055 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
1056 /// a full trait reference. The resulting trait reference is returned. This may also generate
1057 /// auxiliary bounds, which are added to `bounds`.
1062 /// poly_trait_ref = Iterator<Item = u32>
1066 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
1068 /// **A note on binders:** against our usual convention, there is an implied bounder around
1069 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
1070 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
1071 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
1072 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
1074 pub fn instantiate_poly_trait_ref(
1076 poly_trait_ref: &hir::PolyTraitRef<'_>,
1077 constness: Constness,
1079 bounds: &mut Bounds<'tcx>,
1080 ) -> Result<(), GenericArgCountMismatch> {
1081 self.instantiate_poly_trait_ref_inner(
1082 &poly_trait_ref.trait_ref,
1083 poly_trait_ref.span,
1091 fn ast_path_to_mono_trait_ref(
1094 trait_def_id: DefId,
1096 trait_segment: &hir::PathSegment<'_>,
1097 ) -> ty::TraitRef<'tcx> {
1098 let (substs, assoc_bindings, _) =
1099 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1100 if let Some(b) = assoc_bindings.first() {
1101 AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span);
1103 ty::TraitRef::new(trait_def_id, substs)
1106 /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1107 /// an error and attempt to build a reasonable structured suggestion.
1108 fn complain_about_internal_fn_trait(
1111 trait_def_id: DefId,
1112 trait_segment: &'a hir::PathSegment<'a>,
1114 let trait_def = self.tcx().trait_def(trait_def_id);
1116 if !self.tcx().features().unboxed_closures
1117 && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1119 let sess = &self.tcx().sess.parse_sess;
1120 // For now, require that parenthetical notation be used only with `Fn()` etc.
1121 let (msg, sugg) = if trait_def.paren_sugar {
1123 "the precise format of `Fn`-family traits' type parameters is subject to \
1127 trait_segment.ident,
1131 .and_then(|args| args.args.get(0))
1132 .and_then(|arg| match arg {
1133 hir::GenericArg::Type(ty) => {
1134 sess.source_map().span_to_snippet(ty.span).ok()
1138 .unwrap_or_else(|| "()".to_string()),
1143 .find_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1144 (true, hir::TypeBindingKind::Equality { ty }) => {
1145 sess.source_map().span_to_snippet(ty.span).ok()
1149 .unwrap_or_else(|| "()".to_string()),
1153 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1155 let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1156 if let Some(sugg) = sugg {
1157 let msg = "use parenthetical notation instead";
1158 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1164 fn create_substs_for_ast_trait_ref<'a>(
1167 trait_def_id: DefId,
1169 trait_segment: &'a hir::PathSegment<'a>,
1170 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Result<(), GenericArgCountMismatch>)
1172 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1174 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1176 self.create_substs_for_ast_path(
1180 trait_segment.generic_args(),
1181 trait_segment.infer_args,
1186 fn trait_defines_associated_type_named(
1188 trait_def_id: DefId,
1189 assoc_name: ast::Ident,
1192 .associated_items(trait_def_id)
1193 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
1197 // Returns `true` if a bounds list includes `?Sized`.
1198 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1199 let tcx = self.tcx();
1201 // Try to find an unbound in bounds.
1202 let mut unbound = None;
1203 for ab in ast_bounds {
1204 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1205 if unbound.is_none() {
1206 unbound = Some(&ptr.trait_ref);
1212 "type parameter has more than one relaxed default \
1213 bound, only one is supported"
1220 let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1223 // FIXME(#8559) currently requires the unbound to be built-in.
1224 if let Ok(kind_id) = kind_id {
1225 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1228 "default bound relaxed for a type parameter, but \
1229 this does nothing because the given bound is not \
1230 a default; only `?Sized` is supported",
1235 _ if kind_id.is_ok() => {
1238 // No lang item for `Sized`, so we can't add it as a bound.
1245 /// This helper takes a *converted* parameter type (`param_ty`)
1246 /// and an *unconverted* list of bounds:
1249 /// fn foo<T: Debug>
1250 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
1252 /// `param_ty`, in ty form
1255 /// It adds these `ast_bounds` into the `bounds` structure.
1257 /// **A note on binders:** there is an implied binder around
1258 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1259 /// for more details.
1263 ast_bounds: &[hir::GenericBound<'_>],
1264 bounds: &mut Bounds<'tcx>,
1266 let mut trait_bounds = Vec::new();
1267 let mut region_bounds = Vec::new();
1269 let constness = self.default_constness_for_trait_bounds();
1270 for ast_bound in ast_bounds {
1272 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1273 trait_bounds.push((b, constness))
1275 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
1276 trait_bounds.push((b, Constness::NotConst))
1278 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1279 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1283 for (bound, constness) in trait_bounds {
1284 let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
1287 bounds.region_bounds.extend(
1288 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1292 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1293 /// The self-type for the bounds is given by `param_ty`.
1298 /// fn foo<T: Bar + Baz>() { }
1299 /// ^ ^^^^^^^^^ ast_bounds
1303 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1304 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1305 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1307 /// `span` should be the declaration size of the parameter.
1308 pub fn compute_bounds(
1311 ast_bounds: &[hir::GenericBound<'_>],
1312 sized_by_default: SizedByDefault,
1315 let mut bounds = Bounds::default();
1317 self.add_bounds(param_ty, ast_bounds, &mut bounds);
1318 bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
1320 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1321 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1329 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1332 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1333 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1334 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1335 fn add_predicates_for_ast_type_binding(
1337 hir_ref_id: hir::HirId,
1338 trait_ref: ty::PolyTraitRef<'tcx>,
1339 binding: &ConvertedBinding<'_, 'tcx>,
1340 bounds: &mut Bounds<'tcx>,
1342 dup_bindings: &mut FxHashMap<DefId, Span>,
1344 ) -> Result<(), ErrorReported> {
1345 let tcx = self.tcx();
1348 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1349 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1350 // subtle in the event that `T` is defined in a supertrait of
1351 // `SomeTrait`, because in that case we need to upcast.
1353 // That is, consider this case:
1356 // trait SubTrait: SuperTrait<int> { }
1357 // trait SuperTrait<A> { type T; }
1359 // ... B: SubTrait<T = foo> ...
1362 // We want to produce `<B as SuperTrait<int>>::T == foo`.
1364 // Find any late-bound regions declared in `ty` that are not
1365 // declared in the trait-ref. These are not well-formed.
1369 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1370 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1371 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1372 let late_bound_in_trait_ref =
1373 tcx.collect_constrained_late_bound_regions(&trait_ref);
1374 let late_bound_in_ty =
1375 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1376 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1377 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1378 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1379 let br_name = match *br {
1380 ty::BrNamed(_, name) => name,
1384 "anonymous bound region {:?} in binding but not trait ref",
1389 // FIXME: point at the type params that don't have appropriate lifetimes:
1390 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1391 // ---- ---- ^^^^^^^
1396 "binding for associated type `{}` references lifetime `{}`, \
1397 which does not appear in the trait input types",
1407 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1408 // Simple case: X is defined in the current trait.
1411 // Otherwise, we have to walk through the supertraits to find
1413 self.one_bound_for_assoc_type(
1414 || traits::supertraits(tcx, trait_ref),
1415 || trait_ref.print_only_trait_path().to_string(),
1418 || match binding.kind {
1419 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1425 let (assoc_ident, def_scope) =
1426 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1428 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1429 // of calling `filter_by_name_and_kind`.
1431 .associated_items(candidate.def_id())
1432 .filter_by_name_unhygienic(assoc_ident.name)
1434 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1436 .expect("missing associated type");
1438 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1442 &format!("associated type `{}` is private", binding.item_name),
1444 .span_label(binding.span, "private associated type")
1447 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1451 .entry(assoc_ty.def_id)
1452 .and_modify(|prev_span| {
1457 "the value of the associated type `{}` (from trait `{}`) \
1458 is already specified",
1460 tcx.def_path_str(assoc_ty.container.id())
1462 .span_label(binding.span, "re-bound here")
1463 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1466 .or_insert(binding.span);
1469 match binding.kind {
1470 ConvertedBindingKind::Equality(ref ty) => {
1471 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1472 // the "projection predicate" for:
1474 // `<T as Iterator>::Item = u32`
1475 bounds.projection_bounds.push((
1476 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1477 projection_ty: ty::ProjectionTy::from_ref_and_name(
1487 ConvertedBindingKind::Constraint(ast_bounds) => {
1488 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1490 // `<T as Iterator>::Item: Debug`
1492 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1493 // parameter to have a skipped binder.
1494 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1495 self.add_bounds(param_ty, ast_bounds, bounds);
1505 item_segment: &hir::PathSegment<'_>,
1507 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1508 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1511 fn conv_object_ty_poly_trait_ref(
1514 trait_bounds: &[hir::PolyTraitRef<'_>],
1515 lifetime: &hir::Lifetime,
1517 let tcx = self.tcx();
1519 let mut bounds = Bounds::default();
1520 let mut potential_assoc_types = Vec::new();
1521 let dummy_self = self.tcx().types.trait_object_dummy_self;
1522 for trait_bound in trait_bounds.iter().rev() {
1523 if let Err(GenericArgCountMismatch {
1524 invalid_args: cur_potential_assoc_types, ..
1525 }) = self.instantiate_poly_trait_ref(
1527 Constness::NotConst,
1531 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1535 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1536 // is used and no 'maybe' bounds are used.
1537 let expanded_traits =
1538 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1539 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1540 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1541 if regular_traits.len() > 1 {
1542 let first_trait = ®ular_traits[0];
1543 let additional_trait = ®ular_traits[1];
1544 let mut err = struct_span_err!(
1546 additional_trait.bottom().1,
1548 "only auto traits can be used as additional traits in a trait object"
1550 additional_trait.label_with_exp_info(
1552 "additional non-auto trait",
1555 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1559 if regular_traits.is_empty() && auto_traits.is_empty() {
1564 "at least one trait is required for an object type"
1567 return tcx.types.err;
1570 // Check that there are no gross object safety violations;
1571 // most importantly, that the supertraits don't contain `Self`,
1573 for item in ®ular_traits {
1574 let object_safety_violations =
1575 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1576 if !object_safety_violations.is_empty() {
1577 report_object_safety_error(
1580 item.trait_ref().def_id(),
1581 &object_safety_violations[..],
1584 return tcx.types.err;
1588 // Use a `BTreeSet` to keep output in a more consistent order.
1589 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1591 let regular_traits_refs_spans = bounds
1594 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1596 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1597 assert_eq!(constness, Constness::NotConst);
1599 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1601 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1602 obligation.predicate
1604 match obligation.predicate {
1605 ty::Predicate::Trait(pred, _) => {
1606 associated_types.entry(span).or_default().extend(
1607 tcx.associated_items(pred.def_id())
1608 .in_definition_order()
1609 .filter(|item| item.kind == ty::AssocKind::Type)
1610 .map(|item| item.def_id),
1613 ty::Predicate::Projection(pred) => {
1614 // A `Self` within the original bound will be substituted with a
1615 // `trait_object_dummy_self`, so check for that.
1616 let references_self =
1617 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1619 // If the projection output contains `Self`, force the user to
1620 // elaborate it explicitly to avoid a lot of complexity.
1622 // The "classicaly useful" case is the following:
1624 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1629 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1630 // but actually supporting that would "expand" to an infinitely-long type
1631 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1633 // Instead, we force the user to write
1634 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1635 // the discussion in #56288 for alternatives.
1636 if !references_self {
1637 // Include projections defined on supertraits.
1638 bounds.projection_bounds.push((pred, span));
1646 for (projection_bound, _) in &bounds.projection_bounds {
1647 for def_ids in associated_types.values_mut() {
1648 def_ids.remove(&projection_bound.projection_def_id());
1652 self.complain_about_missing_associated_types(
1654 potential_assoc_types,
1658 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1659 // `dyn Trait + Send`.
1660 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1661 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1662 debug!("regular_traits: {:?}", regular_traits);
1663 debug!("auto_traits: {:?}", auto_traits);
1665 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1666 // removing the dummy `Self` type (`trait_object_dummy_self`).
1667 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1668 if trait_ref.self_ty() != dummy_self {
1669 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1670 // which picks up non-supertraits where clauses - but also, the object safety
1671 // completely ignores trait aliases, which could be object safety hazards. We
1672 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1673 // disabled. (#66420)
1674 tcx.sess.delay_span_bug(
1677 "trait_ref_to_existential called on {:?} with non-dummy Self",
1682 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1685 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1686 let existential_trait_refs =
1687 regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1688 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1689 bound.map_bound(|b| {
1690 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1691 ty::ExistentialProjection {
1693 item_def_id: b.projection_ty.item_def_id,
1694 substs: trait_ref.substs,
1699 // Calling `skip_binder` is okay because the predicates are re-bound.
1700 let regular_trait_predicates = existential_trait_refs
1701 .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1702 let auto_trait_predicates = auto_traits
1704 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1705 let mut v = regular_trait_predicates
1706 .chain(auto_trait_predicates)
1708 existential_projections
1709 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1711 .collect::<SmallVec<[_; 8]>>();
1712 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1714 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1716 // Use explicitly-specified region bound.
1717 let region_bound = if !lifetime.is_elided() {
1718 self.ast_region_to_region(lifetime, None)
1720 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1721 if tcx.named_region(lifetime.hir_id).is_some() {
1722 self.ast_region_to_region(lifetime, None)
1724 self.re_infer(None, span).unwrap_or_else(|| {
1725 // FIXME: these can be redundant with E0106, but not always.
1730 "the lifetime bound for this object type cannot be deduced \
1731 from context; please supply an explicit bound"
1734 tcx.lifetimes.re_static
1739 debug!("region_bound: {:?}", region_bound);
1741 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1742 debug!("trait_object_type: {:?}", ty);
1746 /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1747 /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1748 /// same trait bound have the same name (as they come from different super-traits), we instead
1749 /// emit a generic note suggesting using a `where` clause to constraint instead.
1750 fn complain_about_missing_associated_types(
1752 associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1753 potential_assoc_types: Vec<Span>,
1754 trait_bounds: &[hir::PolyTraitRef<'_>],
1756 if associated_types.values().all(|v| v.is_empty()) {
1759 let tcx = self.tcx();
1760 // FIXME: Marked `mut` so that we can replace the spans further below with a more
1761 // appropriate one, but this should be handled earlier in the span assignment.
1762 let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1764 .map(|(span, def_ids)| {
1765 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1768 let mut names = vec![];
1770 // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1771 // `issue-22560.rs`.
1772 let mut trait_bound_spans: Vec<Span> = vec![];
1773 for (span, items) in &associated_types {
1774 if !items.is_empty() {
1775 trait_bound_spans.push(*span);
1777 for assoc_item in items {
1778 let trait_def_id = assoc_item.container.id();
1780 "`{}` (from trait `{}`)",
1782 tcx.def_path_str(trait_def_id),
1786 if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
1787 match &bound.trait_ref.path.segments[..] {
1788 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1789 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1790 // around that bug here, even though it should be fixed elsewhere.
1791 // This would otherwise cause an invalid suggestion. For an example, look at
1792 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1794 // error[E0191]: the value of the associated type `Output`
1795 // (from trait `std::ops::BitXor`) must be specified
1796 // --> $DIR/issue-28344.rs:4:17
1798 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1799 // | ^^^^^^ help: specify the associated type:
1800 // | `BitXor<Output = Type>`
1804 // error[E0191]: the value of the associated type `Output`
1805 // (from trait `std::ops::BitXor`) must be specified
1806 // --> $DIR/issue-28344.rs:4:17
1808 // LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1809 // | ^^^^^^^^^^^^^ help: specify the associated type:
1810 // | `BitXor::bitor<Output = Type>`
1811 [segment] if segment.args.is_none() => {
1812 trait_bound_spans = vec![segment.ident.span];
1813 associated_types = associated_types
1815 .map(|(_, items)| (segment.ident.span, items))
1822 trait_bound_spans.sort();
1823 let mut err = struct_span_err!(
1827 "the value of the associated type{} {} must be specified",
1828 pluralize!(names.len()),
1831 let mut suggestions = vec![];
1832 let mut types_count = 0;
1833 let mut where_constraints = vec![];
1834 for (span, assoc_items) in &associated_types {
1835 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1836 for item in assoc_items {
1838 *names.entry(item.ident.name).or_insert(0) += 1;
1840 let mut dupes = false;
1841 for item in assoc_items {
1842 let prefix = if names[&item.ident.name] > 1 {
1843 let trait_def_id = item.container.id();
1845 format!("{}::", tcx.def_path_str(trait_def_id))
1849 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1850 err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1853 if potential_assoc_types.len() == assoc_items.len() {
1854 // Only suggest when the amount of missing associated types equals the number of
1855 // extra type arguments present, as that gives us a relatively high confidence
1856 // that the user forgot to give the associtated type's name. The canonical
1857 // example would be trying to use `Iterator<isize>` instead of
1858 // `Iterator<Item = isize>`.
1859 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1860 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1861 suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1864 } else if let (Ok(snippet), false) =
1865 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1868 assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1869 let code = if snippet.ends_with('>') {
1870 // The user wrote `Trait<'a>` or similar and we don't have a type we can
1871 // suggest, but at least we can clue them to the correct syntax
1872 // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1874 format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1876 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1877 // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1878 format!("{}<{}>", snippet, types.join(", "))
1880 suggestions.push((*span, code));
1882 where_constraints.push(*span);
1885 let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1886 using the fully-qualified path to the associated types";
1887 if !where_constraints.is_empty() && suggestions.is_empty() {
1888 // If there are duplicates associated type names and a single trait bound do not
1889 // use structured suggestion, it means that there are multiple super-traits with
1890 // the same associated type name.
1891 err.help(where_msg);
1893 if suggestions.len() != 1 {
1894 // We don't need this label if there's an inline suggestion, show otherwise.
1895 for (span, assoc_items) in &associated_types {
1896 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1897 for item in assoc_items {
1899 *names.entry(item.ident.name).or_insert(0) += 1;
1901 let mut label = vec![];
1902 for item in assoc_items {
1903 let postfix = if names[&item.ident.name] > 1 {
1904 let trait_def_id = item.container.id();
1905 format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1909 label.push(format!("`{}`{}", item.ident, postfix));
1911 if !label.is_empty() {
1915 "associated type{} {} must be specified",
1916 pluralize!(label.len()),
1923 if !suggestions.is_empty() {
1924 err.multipart_suggestion(
1925 &format!("specify the associated type{}", pluralize!(types_count)),
1927 Applicability::HasPlaceholders,
1929 if !where_constraints.is_empty() {
1930 err.span_help(where_constraints, where_msg);
1936 fn report_ambiguous_associated_type(
1943 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1944 if let (Some(_), Ok(snippet)) = (
1945 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1946 self.tcx().sess.source_map().span_to_snippet(span),
1948 err.span_suggestion(
1950 "you are looking for the module in `std`, not the primitive type",
1951 format!("std::{}", snippet),
1952 Applicability::MachineApplicable,
1955 err.span_suggestion(
1957 "use fully-qualified syntax",
1958 format!("<{} as {}>::{}", type_str, trait_str, name),
1959 Applicability::HasPlaceholders,
1965 // Search for a bound on a type parameter which includes the associated item
1966 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1967 // This function will fail if there are no suitable bounds or there is
1969 fn find_bound_for_assoc_item(
1971 ty_param_def_id: LocalDefId,
1972 assoc_name: ast::Ident,
1974 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1975 let tcx = self.tcx();
1978 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1979 ty_param_def_id, assoc_name, span,
1983 &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
1985 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1987 let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id);
1988 let param_name = tcx.hir().ty_param_name(param_hir_id);
1989 self.one_bound_for_assoc_type(
1991 traits::transitive_bounds(
1993 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1996 || param_name.to_string(),
2003 // Checks that `bounds` contains exactly one element and reports appropriate
2004 // errors otherwise.
2005 fn one_bound_for_assoc_type<I>(
2007 all_candidates: impl Fn() -> I,
2008 ty_param_name: impl Fn() -> String,
2009 assoc_name: ast::Ident,
2011 is_equality: impl Fn() -> Option<String>,
2012 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
2014 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2016 let mut matching_candidates = all_candidates()
2017 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
2019 let bound = match matching_candidates.next() {
2020 Some(bound) => bound,
2022 self.complain_about_assoc_type_not_found(
2028 return Err(ErrorReported);
2032 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
2034 if let Some(bound2) = matching_candidates.next() {
2035 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
2037 let is_equality = is_equality();
2038 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
2039 let mut err = if is_equality.is_some() {
2040 // More specific Error Index entry.
2045 "ambiguous associated type `{}` in bounds of `{}`",
2054 "ambiguous associated type `{}` in bounds of `{}`",
2059 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
2061 let mut where_bounds = vec![];
2062 for bound in bounds {
2063 let bound_id = bound.def_id();
2064 let bound_span = self
2066 .associated_items(bound_id)
2067 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
2068 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
2070 if let Some(bound_span) = bound_span {
2074 "ambiguous `{}` from `{}`",
2076 bound.print_only_trait_path(),
2079 if let Some(constraint) = &is_equality {
2080 where_bounds.push(format!(
2081 " T: {trait}::{assoc} = {constraint}",
2082 trait=bound.print_only_trait_path(),
2084 constraint=constraint,
2087 err.span_suggestion(
2089 "use fully qualified syntax to disambiguate",
2093 bound.print_only_trait_path(),
2096 Applicability::MaybeIncorrect,
2101 "associated type `{}` could derive from `{}`",
2103 bound.print_only_trait_path(),
2107 if !where_bounds.is_empty() {
2109 "consider introducing a new type parameter `T` and adding `where` constraints:\
2110 \n where\n T: {},\n{}",
2112 where_bounds.join(",\n"),
2116 if !where_bounds.is_empty() {
2117 return Err(ErrorReported);
2123 fn complain_about_assoc_type_not_found<I>(
2125 all_candidates: impl Fn() -> I,
2126 ty_param_name: &str,
2127 assoc_name: ast::Ident,
2130 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2132 // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2133 // valid span, so we point at the whole path segment instead.
2134 let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2135 let mut err = struct_span_err!(
2139 "associated type `{}` not found for `{}`",
2144 let all_candidate_names: Vec<_> = all_candidates()
2145 .map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
2148 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2152 if let (Some(suggested_name), true) = (
2153 find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2154 assoc_name.span != DUMMY_SP,
2156 err.span_suggestion(
2158 "there is an associated type with a similar name",
2159 suggested_name.to_string(),
2160 Applicability::MaybeIncorrect,
2163 err.span_label(span, format!("associated type `{}` not found", assoc_name));
2169 // Create a type from a path to an associated type.
2170 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2171 // and item_segment is the path segment for `D`. We return a type and a def for
2173 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2174 // parameter or `Self`.
2175 pub fn associated_path_to_ty(
2177 hir_ref_id: hir::HirId,
2181 assoc_segment: &hir::PathSegment<'_>,
2182 permit_variants: bool,
2183 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2184 let tcx = self.tcx();
2185 let assoc_ident = assoc_segment.ident;
2187 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2189 // Check if we have an enum variant.
2190 let mut variant_resolution = None;
2191 if let ty::Adt(adt_def, _) = qself_ty.kind {
2192 if adt_def.is_enum() {
2193 let variant_def = adt_def
2196 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2197 if let Some(variant_def) = variant_def {
2198 if permit_variants {
2199 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2200 self.prohibit_generics(slice::from_ref(assoc_segment));
2201 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2203 variant_resolution = Some(variant_def.def_id);
2209 // Find the type of the associated item, and the trait where the associated
2210 // item is declared.
2211 let bound = match (&qself_ty.kind, qself_res) {
2212 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2213 // `Self` in an impl of a trait -- we have a concrete self type and a
2215 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2216 Some(trait_ref) => trait_ref,
2218 // A cycle error occurred, most likely.
2219 return Err(ErrorReported);
2223 self.one_bound_for_assoc_type(
2224 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2225 || "Self".to_string(),
2233 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
2234 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2236 if variant_resolution.is_some() {
2237 // Variant in type position
2238 let msg = format!("expected type, found variant `{}`", assoc_ident);
2239 tcx.sess.span_err(span, &msg);
2240 } else if qself_ty.is_enum() {
2241 let mut err = struct_span_err!(
2245 "no variant named `{}` found for enum `{}`",
2250 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2251 if let Some(suggested_name) = find_best_match_for_name(
2252 adt_def.variants.iter().map(|variant| &variant.ident.name),
2253 &assoc_ident.as_str(),
2256 err.span_suggestion(
2258 "there is a variant with a similar name",
2259 suggested_name.to_string(),
2260 Applicability::MaybeIncorrect,
2265 format!("variant not found in `{}`", qself_ty),
2269 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2270 let sp = tcx.sess.source_map().guess_head_span(sp);
2271 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2275 } else if !qself_ty.references_error() {
2276 // Don't print `TyErr` to the user.
2277 self.report_ambiguous_associated_type(
2279 &qself_ty.to_string(),
2284 return Err(ErrorReported);
2288 let trait_did = bound.def_id();
2289 let (assoc_ident, def_scope) =
2290 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2292 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2293 // of calling `filter_by_name_and_kind`.
2295 .associated_items(trait_did)
2296 .in_definition_order()
2298 i.kind.namespace() == Namespace::TypeNS
2299 && i.ident.normalize_to_macros_2_0() == assoc_ident
2301 .expect("missing associated type");
2303 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2304 let ty = self.normalize_ty(span, ty);
2306 let kind = DefKind::AssocTy;
2307 if !item.vis.is_accessible_from(def_scope, tcx) {
2308 let kind = kind.descr(item.def_id);
2309 let msg = format!("{} `{}` is private", kind, assoc_ident);
2311 .struct_span_err(span, &msg)
2312 .span_label(span, &format!("private {}", kind))
2315 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2317 if let Some(variant_def_id) = variant_resolution {
2318 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2319 let mut err = lint.build("ambiguous associated item");
2320 let mut could_refer_to = |kind: DefKind, def_id, also| {
2321 let note_msg = format!(
2322 "`{}` could{} refer to the {} defined here",
2327 err.span_note(tcx.def_span(def_id), ¬e_msg);
2330 could_refer_to(DefKind::Variant, variant_def_id, "");
2331 could_refer_to(kind, item.def_id, " also");
2333 err.span_suggestion(
2335 "use fully-qualified syntax",
2336 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2337 Applicability::MachineApplicable,
2343 Ok((ty, kind, item.def_id))
2349 opt_self_ty: Option<Ty<'tcx>>,
2351 trait_segment: &hir::PathSegment<'_>,
2352 item_segment: &hir::PathSegment<'_>,
2354 let tcx = self.tcx();
2356 let trait_def_id = tcx.parent(item_def_id).unwrap();
2358 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2360 let self_ty = if let Some(ty) = opt_self_ty {
2363 let path_str = tcx.def_path_str(trait_def_id);
2365 let def_id = self.item_def_id();
2367 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2369 let parent_def_id = def_id
2370 .and_then(|def_id| {
2371 def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id))
2373 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
2375 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2377 // If the trait in segment is the same as the trait defining the item,
2378 // use the `<Self as ..>` syntax in the error.
2379 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2380 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2382 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2388 self.report_ambiguous_associated_type(
2392 item_segment.ident.name,
2394 return tcx.types.err;
2397 debug!("qpath_to_ty: self_type={:?}", self_ty);
2399 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2401 let item_substs = self.create_substs_for_associated_item(
2409 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2411 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2414 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2418 let mut has_err = false;
2419 for segment in segments {
2420 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2421 for arg in segment.generic_args().args {
2422 let (span, kind) = match arg {
2423 hir::GenericArg::Lifetime(lt) => {
2429 (lt.span, "lifetime")
2431 hir::GenericArg::Type(ty) => {
2439 hir::GenericArg::Const(ct) => {
2448 let mut err = struct_span_err!(
2452 "{} arguments are not allowed for this type",
2455 err.span_label(span, format!("{} argument not allowed", kind));
2457 if err_for_lt && err_for_ty && err_for_ct {
2462 // Only emit the first error to avoid overloading the user with error messages.
2463 if let [binding, ..] = segment.generic_args().bindings {
2465 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2471 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2472 let mut err = struct_span_err!(
2476 "associated type bindings are not allowed here"
2478 err.span_label(span, "associated type not allowed here").emit();
2481 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2482 pub fn def_ids_for_value_path_segments(
2484 segments: &[hir::PathSegment<'_>],
2485 self_ty: Option<Ty<'tcx>>,
2489 // We need to extract the type parameters supplied by the user in
2490 // the path `path`. Due to the current setup, this is a bit of a
2491 // tricky-process; the problem is that resolve only tells us the
2492 // end-point of the path resolution, and not the intermediate steps.
2493 // Luckily, we can (at least for now) deduce the intermediate steps
2494 // just from the end-point.
2496 // There are basically five cases to consider:
2498 // 1. Reference to a constructor of a struct:
2500 // struct Foo<T>(...)
2502 // In this case, the parameters are declared in the type space.
2504 // 2. Reference to a constructor of an enum variant:
2506 // enum E<T> { Foo(...) }
2508 // In this case, the parameters are defined in the type space,
2509 // but may be specified either on the type or the variant.
2511 // 3. Reference to a fn item or a free constant:
2515 // In this case, the path will again always have the form
2516 // `a::b::foo::<T>` where only the final segment should have
2517 // type parameters. However, in this case, those parameters are
2518 // declared on a value, and hence are in the `FnSpace`.
2520 // 4. Reference to a method or an associated constant:
2522 // impl<A> SomeStruct<A> {
2526 // Here we can have a path like
2527 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2528 // may appear in two places. The penultimate segment,
2529 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2530 // final segment, `foo::<B>` contains parameters in fn space.
2532 // The first step then is to categorize the segments appropriately.
2534 let tcx = self.tcx();
2536 assert!(!segments.is_empty());
2537 let last = segments.len() - 1;
2539 let mut path_segs = vec![];
2542 // Case 1. Reference to a struct constructor.
2543 DefKind::Ctor(CtorOf::Struct, ..) => {
2544 // Everything but the final segment should have no
2545 // parameters at all.
2546 let generics = tcx.generics_of(def_id);
2547 // Variant and struct constructors use the
2548 // generics of their parent type definition.
2549 let generics_def_id = generics.parent.unwrap_or(def_id);
2550 path_segs.push(PathSeg(generics_def_id, last));
2553 // Case 2. Reference to a variant constructor.
2554 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2555 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2556 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2557 debug_assert!(adt_def.is_enum());
2559 } else if last >= 1 && segments[last - 1].args.is_some() {
2560 // Everything but the penultimate segment should have no
2561 // parameters at all.
2562 let mut def_id = def_id;
2564 // `DefKind::Ctor` -> `DefKind::Variant`
2565 if let DefKind::Ctor(..) = kind {
2566 def_id = tcx.parent(def_id).unwrap()
2569 // `DefKind::Variant` -> `DefKind::Enum`
2570 let enum_def_id = tcx.parent(def_id).unwrap();
2571 (enum_def_id, last - 1)
2573 // FIXME: lint here recommending `Enum::<...>::Variant` form
2574 // instead of `Enum::Variant::<...>` form.
2576 // Everything but the final segment should have no
2577 // parameters at all.
2578 let generics = tcx.generics_of(def_id);
2579 // Variant and struct constructors use the
2580 // generics of their parent type definition.
2581 (generics.parent.unwrap_or(def_id), last)
2583 path_segs.push(PathSeg(generics_def_id, index));
2586 // Case 3. Reference to a top-level value.
2587 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2588 path_segs.push(PathSeg(def_id, last));
2591 // Case 4. Reference to a method or associated const.
2592 DefKind::AssocFn | DefKind::AssocConst => {
2593 if segments.len() >= 2 {
2594 let generics = tcx.generics_of(def_id);
2595 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2597 path_segs.push(PathSeg(def_id, last));
2600 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2603 debug!("path_segs = {:?}", path_segs);
2608 // Check a type `Path` and convert it to a `Ty`.
2611 opt_self_ty: Option<Ty<'tcx>>,
2612 path: &hir::Path<'_>,
2613 permit_variants: bool,
2615 let tcx = self.tcx();
2618 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2619 path.res, opt_self_ty, path.segments
2622 let span = path.span;
2624 Res::Def(DefKind::OpaqueTy, did) => {
2625 // Check for desugared `impl Trait`.
2626 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2627 let item_segment = path.segments.split_last().unwrap();
2628 self.prohibit_generics(item_segment.1);
2629 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2630 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2637 | DefKind::ForeignTy,
2640 assert_eq!(opt_self_ty, None);
2641 self.prohibit_generics(path.segments.split_last().unwrap().1);
2642 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2644 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2645 // Convert "variant type" as if it were a real type.
2646 // The resulting `Ty` is type of the variant's enum for now.
2647 assert_eq!(opt_self_ty, None);
2650 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2651 let generic_segs: FxHashSet<_> =
2652 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2653 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2655 if !generic_segs.contains(&index) { Some(seg) } else { None }
2659 let PathSeg(def_id, index) = path_segs.last().unwrap();
2660 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2662 Res::Def(DefKind::TyParam, def_id) => {
2663 assert_eq!(opt_self_ty, None);
2664 self.prohibit_generics(path.segments);
2666 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
2667 let item_id = tcx.hir().get_parent_node(hir_id);
2668 let item_def_id = tcx.hir().local_def_id(item_id);
2669 let generics = tcx.generics_of(item_def_id);
2670 let index = generics.param_def_id_to_index[&def_id];
2671 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2673 Res::SelfTy(Some(_), None) => {
2674 // `Self` in trait or type alias.
2675 assert_eq!(opt_self_ty, None);
2676 self.prohibit_generics(path.segments);
2677 tcx.types.self_param
2679 Res::SelfTy(_, Some(def_id)) => {
2680 // `Self` in impl (we know the concrete type).
2681 assert_eq!(opt_self_ty, None);
2682 self.prohibit_generics(path.segments);
2683 // Try to evaluate any array length constants.
2684 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2686 Res::Def(DefKind::AssocTy, def_id) => {
2687 debug_assert!(path.segments.len() >= 2);
2688 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2693 &path.segments[path.segments.len() - 2],
2694 path.segments.last().unwrap(),
2697 Res::PrimTy(prim_ty) => {
2698 assert_eq!(opt_self_ty, None);
2699 self.prohibit_generics(path.segments);
2701 hir::PrimTy::Bool => tcx.types.bool,
2702 hir::PrimTy::Char => tcx.types.char,
2703 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2704 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2705 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2706 hir::PrimTy::Str => tcx.mk_str(),
2710 self.set_tainted_by_errors();
2711 self.tcx().types.err
2713 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2717 /// Parses the programmer's textual representation of a type into our
2718 /// internal notion of a type.
2719 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2720 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2722 let tcx = self.tcx();
2724 let result_ty = match ast_ty.kind {
2725 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2726 hir::TyKind::Ptr(ref mt) => {
2727 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2729 hir::TyKind::Rptr(ref region, ref mt) => {
2730 let r = self.ast_region_to_region(region, None);
2731 debug!("ast_ty_to_ty: r={:?}", r);
2732 let t = self.ast_ty_to_ty(&mt.ty);
2733 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2735 hir::TyKind::Never => tcx.types.never,
2736 hir::TyKind::Tup(ref fields) => {
2737 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2739 hir::TyKind::BareFn(ref bf) => {
2740 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2741 tcx.mk_fn_ptr(self.ty_of_fn(
2745 &hir::Generics::empty(),
2749 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2750 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2752 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2753 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2754 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2755 self.res_to_ty(opt_self_ty, path, false)
2757 hir::TyKind::Def(item_id, ref lifetimes) => {
2758 let did = tcx.hir().local_def_id(item_id.id);
2759 self.impl_trait_ty_to_ty(did.to_def_id(), lifetimes)
2761 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2762 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2763 let ty = self.ast_ty_to_ty(qself);
2765 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2770 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2771 .map(|(ty, _, _)| ty)
2772 .unwrap_or(tcx.types.err)
2774 hir::TyKind::Array(ref ty, ref length) => {
2775 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2776 let length = ty::Const::from_anon_const(tcx, length_def_id);
2777 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2778 self.normalize_ty(ast_ty.span, array_ty)
2780 hir::TyKind::Typeof(ref _e) => {
2785 "`typeof` is a reserved keyword but unimplemented"
2787 .span_label(ast_ty.span, "reserved keyword")
2792 hir::TyKind::Infer => {
2793 // Infer also appears as the type of arguments or return
2794 // values in a ExprKind::Closure, or as
2795 // the type of local variables. Both of these cases are
2796 // handled specially and will not descend into this routine.
2797 self.ty_infer(None, ast_ty.span)
2799 hir::TyKind::Err => tcx.types.err,
2802 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2804 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2808 pub fn impl_trait_ty_to_ty(
2811 lifetimes: &[hir::GenericArg<'_>],
2813 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2814 let tcx = self.tcx();
2816 let generics = tcx.generics_of(def_id);
2818 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2819 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2820 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2821 // Our own parameters are the resolved lifetimes.
2823 GenericParamDefKind::Lifetime => {
2824 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2825 self.ast_region_to_region(lifetime, None).into()
2833 // Replace all parent lifetimes with `'static`.
2835 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2836 _ => tcx.mk_param_from_def(param),
2840 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2842 let ty = tcx.mk_opaque(def_id, substs);
2843 debug!("impl_trait_ty_to_ty: {}", ty);
2847 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2849 hir::TyKind::Infer if expected_ty.is_some() => {
2850 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2851 expected_ty.unwrap()
2853 _ => self.ast_ty_to_ty(ty),
2859 unsafety: hir::Unsafety,
2861 decl: &hir::FnDecl<'_>,
2862 generics: &hir::Generics<'_>,
2863 ident_span: Option<Span>,
2864 ) -> ty::PolyFnSig<'tcx> {
2867 let tcx = self.tcx();
2869 // We proactively collect all the inferred type params to emit a single error per fn def.
2870 let mut visitor = PlaceholderHirTyCollector::default();
2871 for ty in decl.inputs {
2872 visitor.visit_ty(ty);
2874 walk_generics(&mut visitor, generics);
2876 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2877 let output_ty = match decl.output {
2878 hir::FnRetTy::Return(ref output) => {
2879 visitor.visit_ty(output);
2880 self.ast_ty_to_ty(output)
2882 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2885 debug!("ty_of_fn: output_ty={:?}", output_ty);
2888 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2890 if let (false, Some(ident_span)) = (self.allow_ty_infer(), ident_span) {
2891 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2892 // only want to emit an error complaining about them if infer types (`_`) are not
2893 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2894 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2895 crate::collect::placeholder_type_error(
2897 ident_span.shrink_to_hi(),
2898 &generics.params[..],
2904 // Find any late-bound regions declared in return type that do
2905 // not appear in the arguments. These are not well-formed.
2908 // for<'a> fn() -> &'a str <-- 'a is bad
2909 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2910 let inputs = bare_fn_ty.inputs();
2911 let late_bound_in_args =
2912 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2913 let output = bare_fn_ty.output();
2914 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2915 for br in late_bound_in_ret.difference(&late_bound_in_args) {
2916 let lifetime_name = match *br {
2917 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2918 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2920 let mut err = struct_span_err!(
2924 "return type references {} which is not constrained by the fn input types",
2927 if let ty::BrAnon(_) = *br {
2928 // The only way for an anonymous lifetime to wind up
2929 // in the return type but **also** be unconstrained is
2930 // if it only appears in "associated types" in the
2931 // input. See #47511 for an example. In this case,
2932 // though we can easily give a hint that ought to be
2935 "lifetimes appearing in an associated type are not considered constrained",
2944 /// Given the bounds on an object, determines what single region bound (if any) we can
2945 /// use to summarize this type. The basic idea is that we will use the bound the user
2946 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2947 /// for region bounds. It may be that we can derive no bound at all, in which case
2948 /// we return `None`.
2949 fn compute_object_lifetime_bound(
2952 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2953 ) -> Option<ty::Region<'tcx>> // if None, use the default
2955 let tcx = self.tcx();
2957 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2959 // No explicit region bound specified. Therefore, examine trait
2960 // bounds and see if we can derive region bounds from those.
2961 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2963 // If there are no derived region bounds, then report back that we
2964 // can find no region bound. The caller will use the default.
2965 if derived_region_bounds.is_empty() {
2969 // If any of the derived region bounds are 'static, that is always
2971 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2972 return Some(tcx.lifetimes.re_static);
2975 // Determine whether there is exactly one unique region in the set
2976 // of derived region bounds. If so, use that. Otherwise, report an
2978 let r = derived_region_bounds[0];
2979 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2984 "ambiguous lifetime bound, explicit lifetime bound required"
2992 /// Collects together a list of bounds that are applied to some type,
2993 /// after they've been converted into `ty` form (from the HIR
2994 /// representations). These lists of bounds occur in many places in
2998 /// trait Foo: Bar + Baz { }
2999 /// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
3001 /// fn foo<T: Bar + Baz>() { }
3002 /// ^^^^^^^^^ bounding the type parameter `T`
3004 /// impl dyn Bar + Baz
3005 /// ^^^^^^^^^ bounding the forgotten dynamic type
3008 /// Our representation is a bit mixed here -- in some cases, we
3009 /// include the self type (e.g., `trait_bounds`) but in others we do
3010 #[derive(Default, PartialEq, Eq, Clone, Debug)]
3011 pub struct Bounds<'tcx> {
3012 /// A list of region bounds on the (implicit) self type. So if you
3013 /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
3014 /// the `T` is not explicitly included).
3015 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
3017 /// A list of trait bounds. So if you had `T: Debug` this would be
3018 /// `T: Debug`. Note that the self-type is explicit here.
3019 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>,
3021 /// A list of projection equality bounds. So if you had `T:
3022 /// Iterator<Item = u32>` this would include `<T as
3023 /// Iterator>::Item => u32`. Note that the self-type is explicit
3025 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
3027 /// `Some` if there is *no* `?Sized` predicate. The `span`
3028 /// is the location in the source of the `T` declaration which can
3029 /// be cited as the source of the `T: Sized` requirement.
3030 pub implicitly_sized: Option<Span>,
3033 impl<'tcx> Bounds<'tcx> {
3034 /// Converts a bounds list into a flat set of predicates (like
3035 /// where-clauses). Because some of our bounds listings (e.g.,
3036 /// regions) don't include the self-type, you must supply the
3037 /// self-type here (the `param_ty` parameter).
3042 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
3043 // If it could be sized, and is, add the `Sized` predicate.
3044 let sized_predicate = self.implicitly_sized.and_then(|span| {
3045 tcx.lang_items().sized_trait().map(|sized| {
3046 let trait_ref = ty::Binder::bind(ty::TraitRef {
3048 substs: tcx.mk_substs_trait(param_ty, &[]),
3050 (trait_ref.without_const().to_predicate(), span)
3059 .map(|&(region_bound, span)| {
3060 // Account for the binder being introduced below; no need to shift `param_ty`
3061 // because, at present at least, it either only refers to early-bound regions,
3062 // or it's a generic associated type that deliberately has escaping bound vars.
3063 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
3064 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
3065 (ty::Binder::bind(outlives).to_predicate(), span)
3067 .chain(self.trait_bounds.iter().map(|&(bound_trait_ref, span, constness)| {
3068 let predicate = bound_trait_ref.with_constness(constness).to_predicate();
3072 self.projection_bounds
3074 .map(|&(projection, span)| (projection.to_predicate(), span)),