]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
rustc: use DefKind instead of Def, where possible.
[rust.git] / src / librustc_typeck / astconv.rs
1 //! Conversion from AST representation of types to the `ty.rs` representation.
2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
3 //! instance of `AstConv`.
4
5 use errors::{Applicability, DiagnosticId};
6 use crate::hir::{self, GenericArg, GenericArgs, ExprKind};
7 use crate::hir::def::{CtorOf, Def, DefKind};
8 use crate::hir::def_id::DefId;
9 use crate::hir::HirVec;
10 use crate::lint;
11 use crate::middle::resolve_lifetime as rl;
12 use crate::namespace::Namespace;
13 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
14 use rustc::traits;
15 use rustc::ty::{self, DefIdTree, Ty, TyCtxt, ToPredicate, TypeFoldable};
16 use rustc::ty::{GenericParamDef, GenericParamDefKind};
17 use rustc::ty::subst::{Kind, Subst, InternalSubsts, SubstsRef};
18 use rustc::ty::wf::object_region_bounds;
19 use rustc::mir::interpret::ConstValue;
20 use rustc_data_structures::sync::Lrc;
21 use rustc_target::spec::abi;
22 use crate::require_c_abi_if_c_variadic;
23 use smallvec::SmallVec;
24 use syntax::ast;
25 use syntax::feature_gate::{GateIssue, emit_feature_err};
26 use syntax::ptr::P;
27 use syntax::util::lev_distance::find_best_match_for_name;
28 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
29 use crate::util::common::ErrorReported;
30 use crate::util::nodemap::FxHashMap;
31
32 use std::collections::BTreeSet;
33 use std::iter;
34 use std::slice;
35
36 use super::{check_type_alias_enum_variants_enabled};
37 use rustc_data_structures::fx::FxHashSet;
38
39 #[derive(Debug)]
40 pub struct PathSeg(pub DefId, pub usize);
41
42 pub trait AstConv<'gcx, 'tcx> {
43     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
44
45     /// Returns the set of bounds in scope for the type parameter with
46     /// the given id.
47     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
48                                  -> Lrc<ty::GenericPredicates<'tcx>>;
49
50     /// What lifetime should we use when a lifetime is omitted (and not elided)?
51     fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
52                 -> Option<ty::Region<'tcx>>;
53
54     /// What type should we use when a type is omitted?
55     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
56
57     /// Same as ty_infer, but with a known type parameter definition.
58     fn ty_infer_for_def(&self,
59                         _def: &ty::GenericParamDef,
60                         span: Span) -> Ty<'tcx> {
61         self.ty_infer(span)
62     }
63
64     /// Projecting an associated type from a (potentially)
65     /// higher-ranked trait reference is more complicated, because of
66     /// the possibility of late-bound regions appearing in the
67     /// associated type binding. This is not legal in function
68     /// signatures for that reason. In a function body, we can always
69     /// handle it because we can use inference variables to remove the
70     /// late-bound regions.
71     fn projected_ty_from_poly_trait_ref(&self,
72                                         span: Span,
73                                         item_def_id: DefId,
74                                         poly_trait_ref: ty::PolyTraitRef<'tcx>)
75                                         -> Ty<'tcx>;
76
77     /// Normalize an associated type coming from the user.
78     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
79
80     /// Invoked when we encounter an error from some prior pass
81     /// (e.g., resolve) that is translated into a ty-error. This is
82     /// used to help suppress derived errors typeck might otherwise
83     /// report.
84     fn set_tainted_by_errors(&self);
85
86     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
87 }
88
89 struct ConvertedBinding<'tcx> {
90     item_name: ast::Ident,
91     ty: Ty<'tcx>,
92     span: Span,
93 }
94
95 #[derive(PartialEq)]
96 enum GenericArgPosition {
97     Type,
98     Value, // e.g., functions
99     MethodCall,
100 }
101
102 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
103     pub fn ast_region_to_region(&self,
104         lifetime: &hir::Lifetime,
105         def: Option<&ty::GenericParamDef>)
106         -> ty::Region<'tcx>
107     {
108         let tcx = self.tcx();
109         let lifetime_name = |def_id| {
110             tcx.hir().name_by_hir_id(tcx.hir().as_local_hir_id(def_id).unwrap()).as_interned_str()
111         };
112
113         let r = match tcx.named_region(lifetime.hir_id) {
114             Some(rl::Region::Static) => {
115                 tcx.lifetimes.re_static
116             }
117
118             Some(rl::Region::LateBound(debruijn, id, _)) => {
119                 let name = lifetime_name(id);
120                 tcx.mk_region(ty::ReLateBound(debruijn,
121                     ty::BrNamed(id, name)))
122             }
123
124             Some(rl::Region::LateBoundAnon(debruijn, index)) => {
125                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
126             }
127
128             Some(rl::Region::EarlyBound(index, id, _)) => {
129                 let name = lifetime_name(id);
130                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
131                     def_id: id,
132                     index,
133                     name,
134                 }))
135             }
136
137             Some(rl::Region::Free(scope, id)) => {
138                 let name = lifetime_name(id);
139                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
140                     scope,
141                     bound_region: ty::BrNamed(id, name)
142                 }))
143
144                 // (*) -- not late-bound, won't change
145             }
146
147             None => {
148                 self.re_infer(lifetime.span, def)
149                     .unwrap_or_else(|| {
150                         // This indicates an illegal lifetime
151                         // elision. `resolve_lifetime` should have
152                         // reported an error in this case -- but if
153                         // not, let's error out.
154                         tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
155
156                         // Supply some dummy value. We don't have an
157                         // `re_error`, annoyingly, so use `'static`.
158                         tcx.lifetimes.re_static
159                     })
160             }
161         };
162
163         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
164                lifetime,
165                r);
166
167         r
168     }
169
170     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
171     /// returns an appropriate set of substitutions for this particular reference to `I`.
172     pub fn ast_path_substs_for_ty(&self,
173         span: Span,
174         def_id: DefId,
175         item_segment: &hir::PathSegment)
176         -> SubstsRef<'tcx>
177     {
178         let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
179             self.create_substs_for_ast_path(
180                 span,
181                 def_id,
182                 generic_args,
183                 item_segment.infer_types,
184                 None,
185             )
186         });
187
188         assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
189
190         substs
191     }
192
193     /// Report error if there is an explicit type parameter when using `impl Trait`.
194     fn check_impl_trait(
195         tcx: TyCtxt<'_, '_, '_>,
196         span: Span,
197         seg: &hir::PathSegment,
198         generics: &ty::Generics,
199     ) -> bool {
200         let explicit = !seg.infer_types;
201         let impl_trait = generics.params.iter().any(|param| match param.kind {
202             ty::GenericParamDefKind::Type {
203                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
204             } => true,
205             _ => false,
206         });
207
208         if explicit && impl_trait {
209             let mut err = struct_span_err! {
210                 tcx.sess,
211                 span,
212                 E0632,
213                 "cannot provide explicit type parameters when `impl Trait` is \
214                  used in argument position."
215             };
216
217             err.emit();
218         }
219
220         impl_trait
221     }
222
223     /// Checks that the correct number of generic arguments have been provided.
224     /// Used specifically for function calls.
225     pub fn check_generic_arg_count_for_call(
226         tcx: TyCtxt<'_, '_, '_>,
227         span: Span,
228         def: &ty::Generics,
229         seg: &hir::PathSegment,
230         is_method_call: bool,
231     ) -> bool {
232         let empty_args = P(hir::GenericArgs {
233             args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
234         });
235         let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
236         Self::check_generic_arg_count(
237             tcx,
238             span,
239             def,
240             if let Some(ref args) = seg.args {
241                 args
242             } else {
243                 &empty_args
244             },
245             if is_method_call {
246                 GenericArgPosition::MethodCall
247             } else {
248                 GenericArgPosition::Value
249             },
250             def.parent.is_none() && def.has_self, // `has_self`
251             seg.infer_types || suppress_mismatch, // `infer_types`
252         ).0
253     }
254
255     /// Checks that the correct number of generic arguments have been provided.
256     /// This is used both for datatypes and function calls.
257     fn check_generic_arg_count(
258         tcx: TyCtxt<'_, '_, '_>,
259         span: Span,
260         def: &ty::Generics,
261         args: &hir::GenericArgs,
262         position: GenericArgPosition,
263         has_self: bool,
264         infer_types: bool,
265     ) -> (bool, Option<Vec<Span>>) {
266         // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
267         // that lifetimes will proceed types. So it suffices to check the number of each generic
268         // arguments in order to validate them with respect to the generic parameters.
269         let param_counts = def.own_counts();
270         let arg_counts = args.own_counts();
271         let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
272         let infer_consts = position != GenericArgPosition::Type && arg_counts.consts == 0;
273
274         let mut defaults: ty::GenericParamCount = Default::default();
275         for param in &def.params {
276             match param.kind {
277                 GenericParamDefKind::Lifetime => {}
278                 GenericParamDefKind::Type { has_default, .. } => {
279                     defaults.types += has_default as usize
280                 }
281                 GenericParamDefKind::Const => {
282                     // FIXME(const_generics:defaults)
283                 }
284             };
285         }
286
287         if position != GenericArgPosition::Type && !args.bindings.is_empty() {
288             AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
289         }
290
291         // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
292         if !infer_lifetimes {
293             if let Some(span_late) = def.has_late_bound_regions {
294                 let msg = "cannot specify lifetime arguments explicitly \
295                            if late bound lifetime parameters are present";
296                 let note = "the late bound lifetime parameter is introduced here";
297                 let span = args.args[0].span();
298                 if position == GenericArgPosition::Value
299                     && arg_counts.lifetimes != param_counts.lifetimes {
300                     let mut err = tcx.sess.struct_span_err(span, msg);
301                     err.span_note(span_late, note);
302                     err.emit();
303                     return (true, None);
304                 } else {
305                     let mut multispan = MultiSpan::from_span(span);
306                     multispan.push_span_label(span_late, note.to_string());
307                     tcx.lint_hir(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
308                                  args.args[0].id(), multispan, msg);
309                     return (false, None);
310                 }
311             }
312         }
313
314         let check_kind_count = |kind, required, permitted, provided, offset| {
315             debug!(
316                 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
317                 kind,
318                 required,
319                 permitted,
320                 provided,
321                 offset
322             );
323             // We enforce the following: `required` <= `provided` <= `permitted`.
324             // For kinds without defaults (i.e., lifetimes), `required == permitted`.
325             // For other kinds (i.e., types), `permitted` may be greater than `required`.
326             if required <= provided && provided <= permitted {
327                 return (false, None);
328             }
329
330             // Unfortunately lifetime and type parameter mismatches are typically styled
331             // differently in diagnostics, which means we have a few cases to consider here.
332             let (bound, quantifier) = if required != permitted {
333                 if provided < required {
334                     (required, "at least ")
335                 } else { // provided > permitted
336                     (permitted, "at most ")
337                 }
338             } else {
339                 (required, "")
340             };
341
342             let mut potential_assoc_types: Option<Vec<Span>> = None;
343             let (spans, label) = if required == permitted && provided > permitted {
344                 // In the case when the user has provided too many arguments,
345                 // we want to point to the unexpected arguments.
346                 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
347                         .iter()
348                         .map(|arg| arg.span())
349                         .collect();
350                 potential_assoc_types = Some(spans.clone());
351                 (spans, format!( "unexpected {} argument", kind))
352             } else {
353                 (vec![span], format!(
354                     "expected {}{} {} argument{}",
355                     quantifier,
356                     bound,
357                     kind,
358                     if bound != 1 { "s" } else { "" },
359                 ))
360             };
361
362             let mut err = tcx.sess.struct_span_err_with_code(
363                 spans.clone(),
364                 &format!(
365                     "wrong number of {} arguments: expected {}{}, found {}",
366                     kind,
367                     quantifier,
368                     bound,
369                     provided,
370                 ),
371                 DiagnosticId::Error("E0107".into())
372             );
373             for span in spans {
374                 err.span_label(span, label.as_str());
375             }
376             err.emit();
377
378             (provided > required, // `suppress_error`
379              potential_assoc_types)
380         };
381
382         if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
383             check_kind_count(
384                 "lifetime",
385                 param_counts.lifetimes,
386                 param_counts.lifetimes,
387                 arg_counts.lifetimes,
388                 0,
389             );
390         }
391         // FIXME(const_generics:defaults)
392         if !infer_consts || arg_counts.consts > param_counts.consts {
393             check_kind_count(
394                 "const",
395                 param_counts.consts,
396                 param_counts.consts,
397                 arg_counts.consts,
398                 arg_counts.lifetimes + arg_counts.types,
399             );
400         }
401         // Note that type errors are currently be emitted *after* const errors.
402         if !infer_types
403             || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
404             check_kind_count(
405                 "type",
406                 param_counts.types - defaults.types - has_self as usize,
407                 param_counts.types - has_self as usize,
408                 arg_counts.types,
409                 arg_counts.lifetimes,
410             )
411         } else {
412             (false, None)
413         }
414     }
415
416     /// Creates the relevant generic argument substitutions
417     /// corresponding to a set of generic parameters. This is a
418     /// rather complex function. Let us try to explain the role
419     /// of each of its parameters:
420     ///
421     /// To start, we are given the `def_id` of the thing we are
422     /// creating the substitutions for, and a partial set of
423     /// substitutions `parent_substs`. In general, the substitutions
424     /// for an item begin with substitutions for all the "parents" of
425     /// that item -- e.g., for a method it might include the
426     /// parameters from the impl.
427     ///
428     /// Therefore, the method begins by walking down these parents,
429     /// starting with the outermost parent and proceed inwards until
430     /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
431     /// first to see if the parent's substitutions are listed in there. If so,
432     /// we can append those and move on. Otherwise, it invokes the
433     /// three callback functions:
434     ///
435     /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
436     ///   generic arguments that were given to that parent from within
437     ///   the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
438     ///   might refer to the trait `Foo`, and the arguments might be
439     ///   `[T]`. The boolean value indicates whether to infer values
440     ///   for arguments whose values were not explicitly provided.
441     /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
442     ///   instantiate a `Kind`.
443     /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
444     ///   creates a suitable inference variable.
445     pub fn create_substs_for_generic_args<'a, 'b>(
446         tcx: TyCtxt<'a, 'gcx, 'tcx>,
447         def_id: DefId,
448         parent_substs: &[Kind<'tcx>],
449         has_self: bool,
450         self_ty: Option<Ty<'tcx>>,
451         args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
452         provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
453         inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
454     ) -> SubstsRef<'tcx> {
455         // Collect the segments of the path; we need to substitute arguments
456         // for parameters throughout the entire path (wherever there are
457         // generic parameters).
458         let mut parent_defs = tcx.generics_of(def_id);
459         let count = parent_defs.count();
460         let mut stack = vec![(def_id, parent_defs)];
461         while let Some(def_id) = parent_defs.parent {
462             parent_defs = tcx.generics_of(def_id);
463             stack.push((def_id, parent_defs));
464         }
465
466         // We manually build up the substitution, rather than using convenience
467         // methods in `subst.rs`, so that we can iterate over the arguments and
468         // parameters in lock-step linearly, instead of trying to match each pair.
469         let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
470
471         // Iterate over each segment of the path.
472         while let Some((def_id, defs)) = stack.pop() {
473             let mut params = defs.params.iter().peekable();
474
475             // If we have already computed substitutions for parents, we can use those directly.
476             while let Some(&param) = params.peek() {
477                 if let Some(&kind) = parent_substs.get(param.index as usize) {
478                     substs.push(kind);
479                     params.next();
480                 } else {
481                     break;
482                 }
483             }
484
485             // `Self` is handled first, unless it's been handled in `parent_substs`.
486             if has_self {
487                 if let Some(&param) = params.peek() {
488                     if param.index == 0 {
489                         if let GenericParamDefKind::Type { .. } = param.kind {
490                             substs.push(self_ty.map(|ty| ty.into())
491                                 .unwrap_or_else(|| inferred_kind(None, param, true)));
492                             params.next();
493                         }
494                     }
495                 }
496             }
497
498             // Check whether this segment takes generic arguments and the user has provided any.
499             let (generic_args, infer_types) = args_for_def_id(def_id);
500
501             let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
502                 .peekable();
503
504             loop {
505                 // We're going to iterate through the generic arguments that the user
506                 // provided, matching them with the generic parameters we expect.
507                 // Mismatches can occur as a result of elided lifetimes, or for malformed
508                 // input. We try to handle both sensibly.
509                 match (args.peek(), params.peek()) {
510                     (Some(&arg), Some(&param)) => {
511                         match (arg, &param.kind) {
512                             (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
513                             | (GenericArg::Type(_), GenericParamDefKind::Type { .. })
514                             | (GenericArg::Const(_), GenericParamDefKind::Const) => {
515                                 substs.push(provided_kind(param, arg));
516                                 args.next();
517                                 params.next();
518                             }
519                             (GenericArg::Type(_), GenericParamDefKind::Lifetime)
520                             | (GenericArg::Const(_), GenericParamDefKind::Lifetime) => {
521                                 // We expected a lifetime argument, but got a type or const
522                                 // argument. That means we're inferring the lifetimes.
523                                 substs.push(inferred_kind(None, param, infer_types));
524                                 params.next();
525                             }
526                             (_, _) => {
527                                 // We expected one kind of parameter, but the user provided
528                                 // another. This is an error, but we need to handle it
529                                 // gracefully so we can report sensible errors.
530                                 // In this case, we're simply going to infer this argument.
531                                 args.next();
532                             }
533                         }
534                     }
535                     (Some(_), None) => {
536                         // We should never be able to reach this point with well-formed input.
537                         // Getting to this point means the user supplied more arguments than
538                         // there are parameters.
539                         args.next();
540                     }
541                     (None, Some(&param)) => {
542                         // If there are fewer arguments than parameters, it means
543                         // we're inferring the remaining arguments.
544                         substs.push(inferred_kind(Some(&substs), param, infer_types));
545                         args.next();
546                         params.next();
547                     }
548                     (None, None) => break,
549                 }
550             }
551         }
552
553         tcx.intern_substs(&substs)
554     }
555
556     /// Given the type/region arguments provided to some path (along with
557     /// an implicit `Self`, if this is a trait reference) returns the complete
558     /// set of substitutions. This may involve applying defaulted type parameters.
559     ///
560     /// Note that the type listing given here is *exactly* what the user provided.
561     fn create_substs_for_ast_path(&self,
562         span: Span,
563         def_id: DefId,
564         generic_args: &hir::GenericArgs,
565         infer_types: bool,
566         self_ty: Option<Ty<'tcx>>)
567         -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
568     {
569         // If the type is parameterized by this region, then replace this
570         // region with the current anon region binding (in other words,
571         // whatever & would get replaced with).
572         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
573                 generic_args={:?})",
574                def_id, self_ty, generic_args);
575
576         let tcx = self.tcx();
577         let generic_params = tcx.generics_of(def_id);
578
579         // If a self-type was declared, one should be provided.
580         assert_eq!(generic_params.has_self, self_ty.is_some());
581
582         let has_self = generic_params.has_self;
583         let (_, potential_assoc_types) = Self::check_generic_arg_count(
584             tcx,
585             span,
586             &generic_params,
587             &generic_args,
588             GenericArgPosition::Type,
589             has_self,
590             infer_types,
591         );
592
593         let is_object = self_ty.map_or(false, |ty| {
594             ty == self.tcx().types.trait_object_dummy_self
595         });
596         let default_needs_object_self = |param: &ty::GenericParamDef| {
597             if let GenericParamDefKind::Type { has_default, .. } = param.kind {
598                 if is_object && has_default {
599                     if tcx.at(span).type_of(param.def_id).has_self_ty() {
600                         // There is no suitable inference default for a type parameter
601                         // that references self, in an object type.
602                         return true;
603                     }
604                 }
605             }
606
607             false
608         };
609
610         let substs = Self::create_substs_for_generic_args(
611             tcx,
612             def_id,
613             &[][..],
614             self_ty.is_some(),
615             self_ty,
616             // Provide the generic args, and whether types should be inferred.
617             |_| (Some(generic_args), infer_types),
618             // Provide substitutions for parameters for which (valid) arguments have been provided.
619             |param, arg| {
620                 match (&param.kind, arg) {
621                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
622                         self.ast_region_to_region(&lt, Some(param)).into()
623                     }
624                     (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
625                         self.ast_ty_to_ty(&ty).into()
626                     }
627                     (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
628                         self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
629                     }
630                     _ => unreachable!(),
631                 }
632             },
633             // Provide substitutions for parameters for which arguments are inferred.
634             |substs, param, infer_types| {
635                 match param.kind {
636                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
637                     GenericParamDefKind::Type { has_default, .. } => {
638                         if !infer_types && has_default {
639                             // No type parameter provided, but a default exists.
640
641                             // If we are converting an object type, then the
642                             // `Self` parameter is unknown. However, some of the
643                             // other type parameters may reference `Self` in their
644                             // defaults. This will lead to an ICE if we are not
645                             // careful!
646                             if default_needs_object_self(param) {
647                                 struct_span_err!(tcx.sess, span, E0393,
648                                                     "the type parameter `{}` must be explicitly \
649                                                      specified",
650                                                     param.name)
651                                     .span_label(span,
652                                                 format!("missing reference to `{}`", param.name))
653                                     .note(&format!("because of the default `Self` reference, \
654                                                     type parameters must be specified on object \
655                                                     types"))
656                                     .emit();
657                                 tcx.types.err.into()
658                             } else {
659                                 // This is a default type parameter.
660                                 self.normalize_ty(
661                                     span,
662                                     tcx.at(span).type_of(param.def_id)
663                                        .subst_spanned(tcx, substs.unwrap(), Some(span))
664                                 ).into()
665                             }
666                         } else if infer_types {
667                             // No type parameters were provided, we can infer all.
668                             if !default_needs_object_self(param) {
669                                 self.ty_infer_for_def(param, span).into()
670                             } else {
671                                 self.ty_infer(span).into()
672                             }
673                         } else {
674                             // We've already errored above about the mismatch.
675                             tcx.types.err.into()
676                         }
677                     }
678                     GenericParamDefKind::Const => {
679                         // FIXME(const_generics:defaults)
680                         // We've already errored above about the mismatch.
681                         tcx.types.err.into()
682                     }
683                 }
684             },
685         );
686
687         let assoc_bindings = generic_args.bindings.iter().map(|binding| {
688             ConvertedBinding {
689                 item_name: binding.ident,
690                 ty: self.ast_ty_to_ty(&binding.ty),
691                 span: binding.span,
692             }
693         }).collect();
694
695         debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
696                generic_params, self_ty, substs);
697
698         (substs, assoc_bindings, potential_assoc_types)
699     }
700
701     /// Instantiates the path for the given trait reference, assuming that it's
702     /// bound to a valid trait type. Returns the def_id for the defining trait.
703     /// The type _cannot_ be a type other than a trait type.
704     ///
705     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
706     /// are disallowed. Otherwise, they are pushed onto the vector given.
707     pub fn instantiate_mono_trait_ref(&self,
708         trait_ref: &hir::TraitRef,
709         self_ty: Ty<'tcx>)
710         -> ty::TraitRef<'tcx>
711     {
712         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
713
714         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
715                                         trait_ref.trait_def_id(),
716                                         self_ty,
717                                         trait_ref.path.segments.last().unwrap())
718     }
719
720     /// The given trait-ref must actually be a trait.
721     pub(super) fn instantiate_poly_trait_ref_inner(&self,
722         trait_ref: &hir::TraitRef,
723         self_ty: Ty<'tcx>,
724         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
725         speculative: bool)
726         -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
727     {
728         let trait_def_id = trait_ref.trait_def_id();
729
730         debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
731
732         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
733
734         let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
735             trait_ref.path.span,
736             trait_def_id,
737             self_ty,
738             trait_ref.path.segments.last().unwrap(),
739         );
740         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
741
742         let mut dup_bindings = FxHashMap::default();
743         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
744             // specify type to assert that error was already reported in Err case:
745             let predicate: Result<_, ErrorReported> =
746                 self.ast_type_binding_to_poly_projection_predicate(
747                     trait_ref.hir_ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
748             // okay to ignore Err because of ErrorReported (see above)
749             Some((predicate.ok()?, binding.span))
750         }));
751
752         debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
753                trait_ref, poly_projections, poly_trait_ref);
754         (poly_trait_ref, potential_assoc_types)
755     }
756
757     pub fn instantiate_poly_trait_ref(&self,
758         poly_trait_ref: &hir::PolyTraitRef,
759         self_ty: Ty<'tcx>,
760         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
761         -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
762     {
763         self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
764                                               poly_projections, false)
765     }
766
767     fn ast_path_to_mono_trait_ref(&self,
768                                   span: Span,
769                                   trait_def_id: DefId,
770                                   self_ty: Ty<'tcx>,
771                                   trait_segment: &hir::PathSegment)
772                                   -> ty::TraitRef<'tcx>
773     {
774         let (substs, assoc_bindings, _) =
775             self.create_substs_for_ast_trait_ref(span,
776                                                  trait_def_id,
777                                                  self_ty,
778                                                  trait_segment);
779         assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
780         ty::TraitRef::new(trait_def_id, substs)
781     }
782
783     fn create_substs_for_ast_trait_ref(
784         &self,
785         span: Span,
786         trait_def_id: DefId,
787         self_ty: Ty<'tcx>,
788         trait_segment: &hir::PathSegment,
789     ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
790         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
791                trait_segment);
792
793         let trait_def = self.tcx().trait_def(trait_def_id);
794
795         if !self.tcx().features().unboxed_closures &&
796             trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
797             != trait_def.paren_sugar {
798             // For now, require that parenthetical notation be used only with `Fn()` etc.
799             let msg = if trait_def.paren_sugar {
800                 "the precise format of `Fn`-family traits' type parameters is subject to change. \
801                  Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
802             } else {
803                 "parenthetical notation is only stable when used with `Fn`-family traits"
804             };
805             emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
806                              span, GateIssue::Language, msg);
807         }
808
809         trait_segment.with_generic_args(|generic_args| {
810             self.create_substs_for_ast_path(span,
811                                             trait_def_id,
812                                             generic_args,
813                                             trait_segment.infer_types,
814                                             Some(self_ty))
815         })
816     }
817
818     fn trait_defines_associated_type_named(&self,
819                                            trait_def_id: DefId,
820                                            assoc_name: ast::Ident)
821                                            -> bool
822     {
823         self.tcx().associated_items(trait_def_id).any(|item| {
824             item.kind == ty::AssociatedKind::Type &&
825             self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
826         })
827     }
828
829     fn ast_type_binding_to_poly_projection_predicate(
830         &self,
831         hir_ref_id: hir::HirId,
832         trait_ref: ty::PolyTraitRef<'tcx>,
833         binding: &ConvertedBinding<'tcx>,
834         speculative: bool,
835         dup_bindings: &mut FxHashMap<DefId, Span>)
836         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
837     {
838         let tcx = self.tcx();
839
840         if !speculative {
841             // Given something like `U: SomeTrait<T = X>`, we want to produce a
842             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
843             // subtle in the event that `T` is defined in a supertrait of
844             // `SomeTrait`, because in that case we need to upcast.
845             //
846             // That is, consider this case:
847             //
848             // ```
849             // trait SubTrait: SuperTrait<int> { }
850             // trait SuperTrait<A> { type T; }
851             //
852             // ... B : SubTrait<T=foo> ...
853             // ```
854             //
855             // We want to produce `<B as SuperTrait<int>>::T == foo`.
856
857             // Find any late-bound regions declared in `ty` that are not
858             // declared in the trait-ref. These are not wellformed.
859             //
860             // Example:
861             //
862             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
863             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
864             let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
865             let late_bound_in_ty =
866                 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
867             debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
868             debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
869             for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
870                 let br_name = match *br {
871                     ty::BrNamed(_, name) => name,
872                     _ => {
873                         span_bug!(
874                             binding.span,
875                             "anonymous bound region {:?} in binding but not trait ref",
876                             br);
877                     }
878                 };
879                 struct_span_err!(tcx.sess,
880                                 binding.span,
881                                 E0582,
882                                 "binding for associated type `{}` references lifetime `{}`, \
883                                  which does not appear in the trait input types",
884                                 binding.item_name, br_name)
885                     .emit();
886             }
887         }
888
889         let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
890                                                                     binding.item_name) {
891             // Simple case: X is defined in the current trait.
892             Ok(trait_ref)
893         } else {
894             // Otherwise, we have to walk through the supertraits to find
895             // those that do.
896             let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
897                 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
898             });
899             self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
900                                           binding.item_name, binding.span)
901         }?;
902
903         let (assoc_ident, def_scope) =
904             tcx.adjust_ident(binding.item_name, candidate.def_id(), hir_ref_id);
905         let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
906             i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
907         }).expect("missing associated type");
908
909         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
910             let msg = format!("associated type `{}` is private", binding.item_name);
911             tcx.sess.span_err(binding.span, &msg);
912         }
913         tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
914
915         if !speculative {
916             dup_bindings.entry(assoc_ty.def_id)
917                 .and_modify(|prev_span| {
918                     struct_span_err!(self.tcx().sess, binding.span, E0719,
919                                      "the value of the associated type `{}` (from the trait `{}`) \
920                                       is already specified",
921                                      binding.item_name,
922                                      tcx.def_path_str(assoc_ty.container.id()))
923                         .span_label(binding.span, "re-bound here")
924                         .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
925                         .emit();
926                 })
927                 .or_insert(binding.span);
928         }
929
930         Ok(candidate.map_bound(|trait_ref| {
931             ty::ProjectionPredicate {
932                 projection_ty: ty::ProjectionTy::from_ref_and_name(
933                     tcx,
934                     trait_ref,
935                     binding.item_name,
936                 ),
937                 ty: binding.ty,
938             }
939         }))
940     }
941
942     fn ast_path_to_ty(&self,
943         span: Span,
944         did: DefId,
945         item_segment: &hir::PathSegment)
946         -> Ty<'tcx>
947     {
948         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
949         self.normalize_ty(
950             span,
951             self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
952         )
953     }
954
955     /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
956     /// removing the dummy `Self` type (`trait_object_dummy_self`).
957     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
958                                 -> ty::ExistentialTraitRef<'tcx> {
959         if trait_ref.self_ty() != self.tcx().types.trait_object_dummy_self {
960             bug!("trait_ref_to_existential called on {:?} with non-dummy Self", trait_ref);
961         }
962         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
963     }
964
965     fn conv_object_ty_poly_trait_ref(&self,
966         span: Span,
967         trait_bounds: &[hir::PolyTraitRef],
968         lifetime: &hir::Lifetime)
969         -> Ty<'tcx>
970     {
971         let tcx = self.tcx();
972
973         if trait_bounds.is_empty() {
974             span_err!(tcx.sess, span, E0224,
975                       "at least one non-builtin trait is required for an object type");
976             return tcx.types.err;
977         }
978
979         let mut projection_bounds = Vec::new();
980         let dummy_self = self.tcx().types.trait_object_dummy_self;
981         let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
982             &trait_bounds[0],
983             dummy_self,
984             &mut projection_bounds,
985         );
986         debug!("principal: {:?}", principal);
987
988         for trait_bound in trait_bounds[1..].iter() {
989             // sanity check for non-principal trait bounds
990             self.instantiate_poly_trait_ref(trait_bound,
991                                             dummy_self,
992                                             &mut vec![]);
993         }
994
995         let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
996
997         if !trait_bounds.is_empty() {
998             let b = &trait_bounds[0];
999             let span = b.trait_ref.path.span;
1000             struct_span_err!(self.tcx().sess, span, E0225,
1001                 "only auto traits can be used as additional traits in a trait object")
1002                 .span_label(span, "non-auto additional trait")
1003                 .emit();
1004         }
1005
1006         // Check that there are no gross object safety violations;
1007         // most importantly, that the supertraits don't contain `Self`,
1008         // to avoid ICEs.
1009         let object_safety_violations =
1010             tcx.global_tcx().astconv_object_safety_violations(principal.def_id());
1011         if !object_safety_violations.is_empty() {
1012             tcx.report_object_safety_error(span, principal.def_id(), object_safety_violations)
1013                 .map(|mut err| err.emit());
1014             return tcx.types.err;
1015         }
1016
1017         // Use a `BTreeSet` to keep output in a more consistent order.
1018         let mut associated_types = BTreeSet::default();
1019
1020         for tr in traits::elaborate_trait_ref(tcx, principal) {
1021             debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", tr);
1022             match tr {
1023                 ty::Predicate::Trait(pred) => {
1024                     associated_types.extend(tcx.associated_items(pred.def_id())
1025                                     .filter(|item| item.kind == ty::AssociatedKind::Type)
1026                                     .map(|item| item.def_id));
1027                 }
1028                 ty::Predicate::Projection(pred) => {
1029                     // A `Self` within the original bound will be substituted with a
1030                     // `trait_object_dummy_self`, so check for that.
1031                     let references_self =
1032                         pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1033
1034                     // If the projection output contains `Self`, force the user to
1035                     // elaborate it explicitly to avoid a bunch of complexity.
1036                     //
1037                     // The "classicaly useful" case is the following:
1038                     // ```
1039                     //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1040                     //         type MyOutput;
1041                     //     }
1042                     // ```
1043                     //
1044                     // Here, the user could theoretically write `dyn MyTrait<Output=X>`,
1045                     // but actually supporting that would "expand" to an infinitely-long type
1046                     // `fix $ Ï„ â†’ dyn MyTrait<MyOutput=X, Output=<Ï„ as MyTrait>::MyOutput`.
1047                     //
1048                     // Instead, we force the user to write `dyn MyTrait<MyOutput=X, Output=X>`,
1049                     // which is uglier but works. See the discussion in #56288 for alternatives.
1050                     if !references_self {
1051                         // Include projections defined on supertraits,
1052                         projection_bounds.push((pred, DUMMY_SP))
1053                     }
1054                 }
1055                 _ => ()
1056             }
1057         }
1058
1059         for (projection_bound, _) in &projection_bounds {
1060             associated_types.remove(&projection_bound.projection_def_id());
1061         }
1062
1063         if !associated_types.is_empty() {
1064             let names = associated_types.iter().map(|item_def_id| {
1065                 let assoc_item = tcx.associated_item(*item_def_id);
1066                 let trait_def_id = assoc_item.container.id();
1067                 format!(
1068                     "`{}` (from the trait `{}`)",
1069                     assoc_item.ident,
1070                     tcx.def_path_str(trait_def_id),
1071                 )
1072             }).collect::<Vec<_>>().join(", ");
1073             let mut err = struct_span_err!(
1074                 tcx.sess,
1075                 span,
1076                 E0191,
1077                 "the value of the associated type{} {} must be specified",
1078                 if associated_types.len() == 1 { "" } else { "s" },
1079                 names,
1080             );
1081             let mut suggest = false;
1082             let mut potential_assoc_types_spans = vec![];
1083             if let Some(potential_assoc_types) = potential_assoc_types {
1084                 if potential_assoc_types.len() == associated_types.len() {
1085                     // Only suggest when the amount of missing associated types is equals to the
1086                     // extra type arguments present, as that gives us a relatively high confidence
1087                     // that the user forgot to give the associtated type's name. The canonical
1088                     // example would be trying to use `Iterator<isize>` instead of
1089                     // `Iterator<Item=isize>`.
1090                     suggest = true;
1091                     potential_assoc_types_spans = potential_assoc_types;
1092                 }
1093             }
1094             let mut suggestions = vec![];
1095             for (i, item_def_id) in associated_types.iter().enumerate() {
1096                 let assoc_item = tcx.associated_item(*item_def_id);
1097                 err.span_label(
1098                     span,
1099                     format!("associated type `{}` must be specified", assoc_item.ident),
1100                 );
1101                 if item_def_id.is_local() {
1102                     err.span_label(
1103                         tcx.def_span(*item_def_id),
1104                         format!("`{}` defined here", assoc_item.ident),
1105                     );
1106                 }
1107                 if suggest {
1108                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1109                         potential_assoc_types_spans[i],
1110                     ) {
1111                         suggestions.push((
1112                             potential_assoc_types_spans[i],
1113                             format!("{} = {}", assoc_item.ident, snippet),
1114                         ));
1115                     }
1116                 }
1117             }
1118             if !suggestions.is_empty() {
1119                 let msg = format!("if you meant to specify the associated {}, write",
1120                     if suggestions.len() == 1 { "type" } else { "types" });
1121                 err.multipart_suggestion(
1122                     &msg,
1123                     suggestions,
1124                     Applicability::MaybeIncorrect,
1125                 );
1126             }
1127             err.emit();
1128         }
1129
1130         // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1131         let existential_principal = principal.map_bound(|trait_ref| {
1132             self.trait_ref_to_existential(trait_ref)
1133         });
1134         let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1135             bound.map_bound(|b| {
1136                 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1137                 ty::ExistentialProjection {
1138                     ty: b.ty,
1139                     item_def_id: b.projection_ty.item_def_id,
1140                     substs: trait_ref.substs,
1141                 }
1142             })
1143         });
1144
1145         // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1146         auto_traits.sort();
1147         auto_traits.dedup();
1148
1149         // Calling `skip_binder` is okay, because the predicates are re-bound.
1150         let principal = if tcx.trait_is_auto(existential_principal.def_id()) {
1151             ty::ExistentialPredicate::AutoTrait(existential_principal.def_id())
1152         } else {
1153             ty::ExistentialPredicate::Trait(*existential_principal.skip_binder())
1154         };
1155         let mut v =
1156             iter::once(principal)
1157             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1158             .chain(existential_projections
1159                 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1160             .collect::<SmallVec<[_; 8]>>();
1161         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1162         v.dedup();
1163         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1164
1165         // Use explicitly-specified region bound.
1166         let region_bound = if !lifetime.is_elided() {
1167             self.ast_region_to_region(lifetime, None)
1168         } else {
1169             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1170                 if tcx.named_region(lifetime.hir_id).is_some() {
1171                     self.ast_region_to_region(lifetime, None)
1172                 } else {
1173                     self.re_infer(span, None).unwrap_or_else(|| {
1174                         span_err!(tcx.sess, span, E0228,
1175                                   "the lifetime bound for this object type cannot be deduced \
1176                                    from context; please supply an explicit bound");
1177                         tcx.lifetimes.re_static
1178                     })
1179                 }
1180             })
1181         };
1182
1183         debug!("region_bound: {:?}", region_bound);
1184
1185         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1186         debug!("trait_object_type: {:?}", ty);
1187         ty
1188     }
1189
1190     fn report_ambiguous_associated_type(
1191         &self,
1192         span: Span,
1193         type_str: &str,
1194         trait_str: &str,
1195         name: &str,
1196     ) {
1197         let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1198         if let (Some(_), Ok(snippet)) = (
1199             self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1200             self.tcx().sess.source_map().span_to_snippet(span),
1201          ) {
1202             err.span_suggestion(
1203                 span,
1204                 "you are looking for the module in `std`, not the primitive type",
1205                 format!("std::{}", snippet),
1206                 Applicability::MachineApplicable,
1207             );
1208         } else {
1209             err.span_suggestion(
1210                     span,
1211                     "use fully-qualified syntax",
1212                     format!("<{} as {}>::{}", type_str, trait_str, name),
1213                     Applicability::HasPlaceholders
1214             );
1215         }
1216         err.emit();
1217     }
1218
1219     // Search for a bound on a type parameter which includes the associated item
1220     // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1221     // This function will fail if there are no suitable bounds or there is
1222     // any ambiguity.
1223     fn find_bound_for_assoc_item(&self,
1224                                  ty_param_def_id: DefId,
1225                                  assoc_name: ast::Ident,
1226                                  span: Span)
1227                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1228     {
1229         let tcx = self.tcx();
1230
1231         let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1232         let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1233
1234         // Check that there is exactly one way to find an associated type with the
1235         // correct name.
1236         let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1237             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1238
1239         let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1240         let param_name = tcx.hir().ty_param_name(param_hir_id);
1241         self.one_bound_for_assoc_type(suitable_bounds,
1242                                       &param_name.as_str(),
1243                                       assoc_name,
1244                                       span)
1245     }
1246
1247     // Checks that `bounds` contains exactly one element and reports appropriate
1248     // errors otherwise.
1249     fn one_bound_for_assoc_type<I>(&self,
1250                                    mut bounds: I,
1251                                    ty_param_name: &str,
1252                                    assoc_name: ast::Ident,
1253                                    span: Span)
1254         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1255         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1256     {
1257         let bound = match bounds.next() {
1258             Some(bound) => bound,
1259             None => {
1260                 struct_span_err!(self.tcx().sess, span, E0220,
1261                                  "associated type `{}` not found for `{}`",
1262                                  assoc_name,
1263                                  ty_param_name)
1264                   .span_label(span, format!("associated type `{}` not found", assoc_name))
1265                   .emit();
1266                 return Err(ErrorReported);
1267             }
1268         };
1269
1270         if let Some(bound2) = bounds.next() {
1271             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1272             let mut err = struct_span_err!(
1273                 self.tcx().sess, span, E0221,
1274                 "ambiguous associated type `{}` in bounds of `{}`",
1275                 assoc_name,
1276                 ty_param_name);
1277             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1278
1279             for bound in bounds {
1280                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1281                     item.kind == ty::AssociatedKind::Type &&
1282                         self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1283                 })
1284                 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1285
1286                 if let Some(span) = bound_span {
1287                     err.span_label(span, format!("ambiguous `{}` from `{}`",
1288                                                  assoc_name,
1289                                                  bound));
1290                 } else {
1291                     span_note!(&mut err, span,
1292                                "associated type `{}` could derive from `{}`",
1293                                ty_param_name,
1294                                bound);
1295                 }
1296             }
1297             err.emit();
1298         }
1299
1300         return Ok(bound);
1301     }
1302
1303     // Create a type from a path to an associated type.
1304     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1305     // and item_segment is the path segment for `D`. We return a type and a def for
1306     // the whole path.
1307     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1308     // parameter or `Self`.
1309     pub fn associated_path_to_ty(
1310         &self,
1311         hir_ref_id: hir::HirId,
1312         span: Span,
1313         qself_ty: Ty<'tcx>,
1314         qself_def: Def,
1315         assoc_segment: &hir::PathSegment,
1316         permit_variants: bool,
1317     ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1318         let tcx = self.tcx();
1319         let assoc_ident = assoc_segment.ident;
1320
1321         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1322
1323         self.prohibit_generics(slice::from_ref(assoc_segment));
1324
1325         // Check if we have an enum variant.
1326         let mut variant_resolution = None;
1327         if let ty::Adt(adt_def, _) = qself_ty.sty {
1328             if adt_def.is_enum() {
1329                 let variant_def = adt_def.variants.iter().find(|vd| {
1330                     tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1331                 });
1332                 if let Some(variant_def) = variant_def {
1333                     if permit_variants {
1334                         check_type_alias_enum_variants_enabled(tcx, span);
1335                         tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1336                         return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1337                     } else {
1338                         variant_resolution = Some(variant_def.def_id);
1339                     }
1340                 }
1341             }
1342         }
1343
1344         // Find the type of the associated item, and the trait where the associated
1345         // item is declared.
1346         let bound = match (&qself_ty.sty, qself_def) {
1347             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1348                 // `Self` in an impl of a trait -- we have a concrete self type and a
1349                 // trait reference.
1350                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1351                     Some(trait_ref) => trait_ref,
1352                     None => {
1353                         // A cycle error occurred, most likely.
1354                         return Err(ErrorReported);
1355                     }
1356                 };
1357
1358                 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1359                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1360
1361                 self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span)?
1362             }
1363             (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1364             (&ty::Param(_), Def::Def(DefKind::TyParam, param_did)) => {
1365                 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
1366             }
1367             _ => {
1368                 if variant_resolution.is_some() {
1369                     // Variant in type position
1370                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1371                     tcx.sess.span_err(span, &msg);
1372                 } else if qself_ty.is_enum() {
1373                     let mut err = tcx.sess.struct_span_err(
1374                         assoc_ident.span,
1375                         &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
1376                     );
1377
1378                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1379                     if let Some(suggested_name) = find_best_match_for_name(
1380                         adt_def.variants.iter().map(|variant| &variant.ident.name),
1381                         &assoc_ident.as_str(),
1382                         None,
1383                     ) {
1384                         err.span_suggestion(
1385                             assoc_ident.span,
1386                             "there is a variant with a similar name",
1387                             suggested_name.to_string(),
1388                             Applicability::MaybeIncorrect,
1389                         );
1390                     } else {
1391                         err.span_label(span, format!("variant not found in `{}`", qself_ty));
1392                     }
1393
1394                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1395                         let sp = tcx.sess.source_map().def_span(sp);
1396                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1397                     }
1398
1399                     err.emit();
1400                 } else if !qself_ty.references_error() {
1401                     // Don't print `TyErr` to the user.
1402                     self.report_ambiguous_associated_type(
1403                         span,
1404                         &qself_ty.to_string(),
1405                         "Trait",
1406                         &assoc_ident.as_str(),
1407                     );
1408                 }
1409                 return Err(ErrorReported);
1410             }
1411         };
1412
1413         let trait_did = bound.def_id();
1414         let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_ident, trait_did, hir_ref_id);
1415         let item = tcx.associated_items(trait_did).find(|i| {
1416             Namespace::from(i.kind) == Namespace::Type &&
1417                 i.ident.modern() == assoc_ident
1418         }).expect("missing associated type");
1419
1420         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1421         let ty = self.normalize_ty(span, ty);
1422
1423         let kind = DefKind::AssociatedTy;
1424         if !item.vis.is_accessible_from(def_scope, tcx) {
1425             let msg = format!("{} `{}` is private", kind.descr(), assoc_ident);
1426             tcx.sess.span_err(span, &msg);
1427         }
1428         tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1429
1430         if let Some(variant_def_id) = variant_resolution {
1431             let mut err = tcx.struct_span_lint_hir(
1432                 AMBIGUOUS_ASSOCIATED_ITEMS,
1433                 hir_ref_id,
1434                 span,
1435                 "ambiguous associated item",
1436             );
1437
1438             let mut could_refer_to = |kind: DefKind, def_id, also| {
1439                 let note_msg = format!("`{}` could{} refer to {} defined here",
1440                                        assoc_ident, also, kind.descr());
1441                 err.span_note(tcx.def_span(def_id), &note_msg);
1442             };
1443             could_refer_to(DefKind::Variant, variant_def_id, "");
1444             could_refer_to(kind, item.def_id, " also");
1445
1446             err.span_suggestion(
1447                 span,
1448                 "use fully-qualified syntax",
1449                 format!("<{} as {}>::{}", qself_ty, "Trait", assoc_ident),
1450                 Applicability::HasPlaceholders,
1451             ).emit();
1452         }
1453
1454         Ok((ty, kind, item.def_id))
1455     }
1456
1457     fn qpath_to_ty(&self,
1458                    span: Span,
1459                    opt_self_ty: Option<Ty<'tcx>>,
1460                    item_def_id: DefId,
1461                    trait_segment: &hir::PathSegment,
1462                    item_segment: &hir::PathSegment)
1463                    -> Ty<'tcx>
1464     {
1465         let tcx = self.tcx();
1466         let trait_def_id = tcx.parent(item_def_id).unwrap();
1467
1468         self.prohibit_generics(slice::from_ref(item_segment));
1469
1470         let self_ty = if let Some(ty) = opt_self_ty {
1471             ty
1472         } else {
1473             let path_str = tcx.def_path_str(trait_def_id);
1474             self.report_ambiguous_associated_type(
1475                 span,
1476                 "Type",
1477                 &path_str,
1478                 &item_segment.ident.as_str(),
1479             );
1480             return tcx.types.err;
1481         };
1482
1483         debug!("qpath_to_ty: self_type={:?}", self_ty);
1484
1485         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1486                                                         trait_def_id,
1487                                                         self_ty,
1488                                                         trait_segment);
1489
1490         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1491
1492         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1493     }
1494
1495     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1496             &self, segments: T) -> bool {
1497         let mut has_err = false;
1498         for segment in segments {
1499             segment.with_generic_args(|generic_args| {
1500                 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1501                 for arg in &generic_args.args {
1502                     let (span, kind) = match arg {
1503                         hir::GenericArg::Lifetime(lt) => {
1504                             if err_for_lt { continue }
1505                             err_for_lt = true;
1506                             has_err = true;
1507                             (lt.span, "lifetime")
1508                         }
1509                         hir::GenericArg::Type(ty) => {
1510                             if err_for_ty { continue }
1511                             err_for_ty = true;
1512                             has_err = true;
1513                             (ty.span, "type")
1514                         }
1515                         hir::GenericArg::Const(ct) => {
1516                             if err_for_ct { continue }
1517                             err_for_ct = true;
1518                             (ct.span, "const")
1519                         }
1520                     };
1521                     let mut err = struct_span_err!(
1522                         self.tcx().sess,
1523                         span,
1524                         E0109,
1525                         "{} arguments are not allowed for this type",
1526                         kind,
1527                     );
1528                     err.span_label(span, format!("{} argument not allowed", kind));
1529                     err.emit();
1530                     if err_for_lt && err_for_ty && err_for_ct {
1531                         break;
1532                     }
1533                 }
1534                 for binding in &generic_args.bindings {
1535                     has_err = true;
1536                     Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1537                     break;
1538                 }
1539             })
1540         }
1541         has_err
1542     }
1543
1544     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_, '_, '_>, span: Span) {
1545         let mut err = struct_span_err!(tcx.sess, span, E0229,
1546                                        "associated type bindings are not allowed here");
1547         err.span_label(span, "associated type not allowed here").emit();
1548     }
1549
1550     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1551     pub fn def_ids_for_value_path_segments(
1552         &self,
1553         segments: &[hir::PathSegment],
1554         self_ty: Option<Ty<'tcx>>,
1555         kind: DefKind,
1556         def_id: DefId,
1557     ) -> Vec<PathSeg> {
1558         // We need to extract the type parameters supplied by the user in
1559         // the path `path`. Due to the current setup, this is a bit of a
1560         // tricky-process; the problem is that resolve only tells us the
1561         // end-point of the path resolution, and not the intermediate steps.
1562         // Luckily, we can (at least for now) deduce the intermediate steps
1563         // just from the end-point.
1564         //
1565         // There are basically five cases to consider:
1566         //
1567         // 1. Reference to a constructor of a struct:
1568         //
1569         //        struct Foo<T>(...)
1570         //
1571         //    In this case, the parameters are declared in the type space.
1572         //
1573         // 2. Reference to a constructor of an enum variant:
1574         //
1575         //        enum E<T> { Foo(...) }
1576         //
1577         //    In this case, the parameters are defined in the type space,
1578         //    but may be specified either on the type or the variant.
1579         //
1580         // 3. Reference to a fn item or a free constant:
1581         //
1582         //        fn foo<T>() { }
1583         //
1584         //    In this case, the path will again always have the form
1585         //    `a::b::foo::<T>` where only the final segment should have
1586         //    type parameters. However, in this case, those parameters are
1587         //    declared on a value, and hence are in the `FnSpace`.
1588         //
1589         // 4. Reference to a method or an associated constant:
1590         //
1591         //        impl<A> SomeStruct<A> {
1592         //            fn foo<B>(...)
1593         //        }
1594         //
1595         //    Here we can have a path like
1596         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1597         //    may appear in two places. The penultimate segment,
1598         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1599         //    final segment, `foo::<B>` contains parameters in fn space.
1600         //
1601         // The first step then is to categorize the segments appropriately.
1602
1603         let tcx = self.tcx();
1604
1605         assert!(!segments.is_empty());
1606         let last = segments.len() - 1;
1607
1608         let mut path_segs = vec![];
1609
1610         match kind {
1611             // Case 1. Reference to a struct constructor.
1612             DefKind::Ctor(CtorOf::Struct, ..) => {
1613                 // Everything but the final segment should have no
1614                 // parameters at all.
1615                 let generics = tcx.generics_of(def_id);
1616                 // Variant and struct constructors use the
1617                 // generics of their parent type definition.
1618                 let generics_def_id = generics.parent.unwrap_or(def_id);
1619                 path_segs.push(PathSeg(generics_def_id, last));
1620             }
1621
1622             // Case 2. Reference to a variant constructor.
1623             DefKind::Ctor(CtorOf::Variant, ..)
1624             | DefKind::Variant => {
1625                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1626                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1627                     debug_assert!(adt_def.is_enum());
1628                     (adt_def.did, last)
1629                 } else if last >= 1 && segments[last - 1].args.is_some() {
1630                     // Everything but the penultimate segment should have no
1631                     // parameters at all.
1632                     let mut def_id = def_id;
1633
1634                     // `DefKind::Ctor` -> `DefKind::Variant`
1635                     if let DefKind::Ctor(..) = kind {
1636                         def_id = tcx.parent(def_id).unwrap()
1637                     }
1638
1639                     // `DefKind::Variant` -> `DefKind::Enum`
1640                     let enum_def_id = tcx.parent(def_id).unwrap();
1641                     (enum_def_id, last - 1)
1642                 } else {
1643                     // FIXME: lint here recommending `Enum::<...>::Variant` form
1644                     // instead of `Enum::Variant::<...>` form.
1645
1646                     // Everything but the final segment should have no
1647                     // parameters at all.
1648                     let generics = tcx.generics_of(def_id);
1649                     // Variant and struct constructors use the
1650                     // generics of their parent type definition.
1651                     (generics.parent.unwrap_or(def_id), last)
1652                 };
1653                 path_segs.push(PathSeg(generics_def_id, index));
1654             }
1655
1656             // Case 3. Reference to a top-level value.
1657             DefKind::Fn
1658             | DefKind::Const
1659             | DefKind::ConstParam
1660             | DefKind::Static => {
1661                 path_segs.push(PathSeg(def_id, last));
1662             }
1663
1664             // Case 4. Reference to a method or associated const.
1665             DefKind::Method
1666             | DefKind::AssociatedConst => {
1667                 if segments.len() >= 2 {
1668                     let generics = tcx.generics_of(def_id);
1669                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1670                 }
1671                 path_segs.push(PathSeg(def_id, last));
1672             }
1673
1674             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1675         }
1676
1677         debug!("path_segs = {:?}", path_segs);
1678
1679         path_segs
1680     }
1681
1682     // Check a type `Path` and convert it to a `Ty`.
1683     pub fn def_to_ty(&self,
1684                      opt_self_ty: Option<Ty<'tcx>>,
1685                      path: &hir::Path,
1686                      permit_variants: bool)
1687                      -> Ty<'tcx> {
1688         let tcx = self.tcx();
1689
1690         debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1691                path.def, opt_self_ty, path.segments);
1692
1693         let span = path.span;
1694         match path.def {
1695             Def::Def(DefKind::Existential, did) => {
1696                 // Check for desugared impl trait.
1697                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1698                 let item_segment = path.segments.split_last().unwrap();
1699                 self.prohibit_generics(item_segment.1);
1700                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1701                 self.normalize_ty(
1702                     span,
1703                     tcx.mk_opaque(did, substs),
1704                 )
1705             }
1706             Def::Def(DefKind::Enum, did)
1707             | Def::Def(DefKind::TyAlias, did)
1708             | Def::Def(DefKind::Struct, did)
1709             | Def::Def(DefKind::Union, did)
1710             | Def::Def(DefKind::ForeignTy, did) => {
1711                 assert_eq!(opt_self_ty, None);
1712                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1713                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1714             }
1715             Def::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
1716                 // Convert "variant type" as if it were a real type.
1717                 // The resulting `Ty` is type of the variant's enum for now.
1718                 assert_eq!(opt_self_ty, None);
1719
1720                 let path_segs =
1721                     self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
1722                 let generic_segs: FxHashSet<_> =
1723                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
1724                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1725                     if !generic_segs.contains(&index) {
1726                         Some(seg)
1727                     } else {
1728                         None
1729                     }
1730                 }));
1731
1732                 let PathSeg(def_id, index) = path_segs.last().unwrap();
1733                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1734             }
1735             Def::Def(DefKind::TyParam, did) => {
1736                 assert_eq!(opt_self_ty, None);
1737                 self.prohibit_generics(&path.segments);
1738
1739                 let hir_id = tcx.hir().as_local_hir_id(did).unwrap();
1740                 let item_id = tcx.hir().get_parent_node_by_hir_id(hir_id);
1741                 let item_def_id = tcx.hir().local_def_id_from_hir_id(item_id);
1742                 let generics = tcx.generics_of(item_def_id);
1743                 let index = generics.param_def_id_to_index[
1744                     &tcx.hir().local_def_id_from_hir_id(hir_id)];
1745                 tcx.mk_ty_param(index, tcx.hir().name_by_hir_id(hir_id).as_interned_str())
1746             }
1747             Def::SelfTy(_, Some(def_id)) => {
1748                 // `Self` in impl (we know the concrete type).
1749                 assert_eq!(opt_self_ty, None);
1750                 self.prohibit_generics(&path.segments);
1751                 // Try to evaluate any array length constants
1752                 self.normalize_ty(span, tcx.at(span).type_of(def_id))
1753             }
1754             Def::SelfTy(Some(_), None) => {
1755                 // `Self` in trait.
1756                 assert_eq!(opt_self_ty, None);
1757                 self.prohibit_generics(&path.segments);
1758                 tcx.mk_self_type()
1759             }
1760             Def::Def(DefKind::AssociatedTy, def_id) => {
1761                 debug_assert!(path.segments.len() >= 2);
1762                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1763                 self.qpath_to_ty(span,
1764                                  opt_self_ty,
1765                                  def_id,
1766                                  &path.segments[path.segments.len() - 2],
1767                                  path.segments.last().unwrap())
1768             }
1769             Def::PrimTy(prim_ty) => {
1770                 assert_eq!(opt_self_ty, None);
1771                 self.prohibit_generics(&path.segments);
1772                 match prim_ty {
1773                     hir::Bool => tcx.types.bool,
1774                     hir::Char => tcx.types.char,
1775                     hir::Int(it) => tcx.mk_mach_int(it),
1776                     hir::Uint(uit) => tcx.mk_mach_uint(uit),
1777                     hir::Float(ft) => tcx.mk_mach_float(ft),
1778                     hir::Str => tcx.mk_str()
1779                 }
1780             }
1781             Def::Err => {
1782                 self.set_tainted_by_errors();
1783                 return self.tcx().types.err;
1784             }
1785             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1786         }
1787     }
1788
1789     /// Parses the programmer's textual representation of a type into our
1790     /// internal notion of a type.
1791     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1792         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1793                ast_ty.hir_id, ast_ty, ast_ty.node);
1794
1795         let tcx = self.tcx();
1796
1797         let result_ty = match ast_ty.node {
1798             hir::TyKind::Slice(ref ty) => {
1799                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1800             }
1801             hir::TyKind::Ptr(ref mt) => {
1802                 tcx.mk_ptr(ty::TypeAndMut {
1803                     ty: self.ast_ty_to_ty(&mt.ty),
1804                     mutbl: mt.mutbl
1805                 })
1806             }
1807             hir::TyKind::Rptr(ref region, ref mt) => {
1808                 let r = self.ast_region_to_region(region, None);
1809                 debug!("Ref r={:?}", r);
1810                 let t = self.ast_ty_to_ty(&mt.ty);
1811                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1812             }
1813             hir::TyKind::Never => {
1814                 tcx.types.never
1815             },
1816             hir::TyKind::Tup(ref fields) => {
1817                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1818             }
1819             hir::TyKind::BareFn(ref bf) => {
1820                 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1821                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1822             }
1823             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1824                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1825             }
1826             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1827                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1828                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1829                     self.ast_ty_to_ty(qself)
1830                 });
1831                 self.def_to_ty(opt_self_ty, path, false)
1832             }
1833             hir::TyKind::Def(item_id, ref lifetimes) => {
1834                 let did = tcx.hir().local_def_id_from_hir_id(item_id.id);
1835                 self.impl_trait_ty_to_ty(did, lifetimes)
1836             },
1837             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1838                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1839                 let ty = self.ast_ty_to_ty(qself);
1840
1841                 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1842                     path.def
1843                 } else {
1844                     Def::Err
1845                 };
1846                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, def, segment, false)
1847                     .map(|(ty, _, _)| ty).unwrap_or(tcx.types.err)
1848             }
1849             hir::TyKind::Array(ref ty, ref length) => {
1850                 let length = self.ast_const_to_const(length, tcx.types.usize);
1851                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1852                 self.normalize_ty(ast_ty.span, array_ty)
1853             }
1854             hir::TyKind::Typeof(ref _e) => {
1855                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1856                                  "`typeof` is a reserved keyword but unimplemented")
1857                     .span_label(ast_ty.span, "reserved keyword")
1858                     .emit();
1859
1860                 tcx.types.err
1861             }
1862             hir::TyKind::Infer => {
1863                 // Infer also appears as the type of arguments or return
1864                 // values in a ExprKind::Closure, or as
1865                 // the type of local variables. Both of these cases are
1866                 // handled specially and will not descend into this routine.
1867                 self.ty_infer(ast_ty.span)
1868             }
1869             hir::TyKind::Err => {
1870                 tcx.types.err
1871             }
1872             hir::TyKind::CVarArgs(lt) => {
1873                 let va_list_did = match tcx.lang_items().va_list() {
1874                     Some(did) => did,
1875                     None => span_bug!(ast_ty.span,
1876                                       "`va_list` lang item required for variadics"),
1877                 };
1878                 let region = self.ast_region_to_region(&lt, None);
1879                 tcx.type_of(va_list_did).subst(tcx, &[region.into()])
1880             }
1881         };
1882
1883         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1884         result_ty
1885     }
1886
1887     pub fn ast_const_to_const(
1888         &self,
1889         ast_const: &hir::AnonConst,
1890         ty: Ty<'tcx>
1891     ) -> &'tcx ty::Const<'tcx> {
1892         debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
1893
1894         let tcx = self.tcx();
1895         let def_id = tcx.hir().local_def_id_from_hir_id(ast_const.hir_id);
1896
1897         let mut const_ = ty::Const {
1898             val: ConstValue::Unevaluated(
1899                 def_id,
1900                 InternalSubsts::identity_for_item(tcx, def_id),
1901             ),
1902             ty,
1903         };
1904
1905         let expr = &tcx.hir().body(ast_const.body).value;
1906         if let ExprKind::Path(ref qpath) = expr.node {
1907             if let hir::QPath::Resolved(_, ref path) = qpath {
1908                 if let Def::Def(DefKind::ConstParam, def_id) = path.def {
1909                     let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
1910                     let item_id = tcx.hir().get_parent_node(node_id);
1911                     let item_def_id = tcx.hir().local_def_id(item_id);
1912                     let generics = tcx.generics_of(item_def_id);
1913                     let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(node_id)];
1914                     let name = tcx.hir().name(node_id).as_interned_str();
1915                     const_.val = ConstValue::Param(ty::ParamConst::new(index, name));
1916                 }
1917             }
1918         };
1919
1920         tcx.mk_const(const_)
1921     }
1922
1923     pub fn impl_trait_ty_to_ty(
1924         &self,
1925         def_id: DefId,
1926         lifetimes: &[hir::GenericArg],
1927     ) -> Ty<'tcx> {
1928         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1929         let tcx = self.tcx();
1930
1931         let generics = tcx.generics_of(def_id);
1932
1933         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1934         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
1935             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1936                 // Our own parameters are the resolved lifetimes.
1937                 match param.kind {
1938                     GenericParamDefKind::Lifetime => {
1939                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1940                             self.ast_region_to_region(lifetime, None).into()
1941                         } else {
1942                             bug!()
1943                         }
1944                     }
1945                     _ => bug!()
1946                 }
1947             } else {
1948                 // Replace all parent lifetimes with 'static.
1949                 match param.kind {
1950                     GenericParamDefKind::Lifetime => {
1951                         tcx.lifetimes.re_static.into()
1952                     }
1953                     _ => tcx.mk_param_from_def(param)
1954                 }
1955             }
1956         });
1957         debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1958
1959         let ty = tcx.mk_opaque(def_id, substs);
1960         debug!("impl_trait_ty_to_ty: {}", ty);
1961         ty
1962     }
1963
1964     pub fn ty_of_arg(&self,
1965                      ty: &hir::Ty,
1966                      expected_ty: Option<Ty<'tcx>>)
1967                      -> Ty<'tcx>
1968     {
1969         match ty.node {
1970             hir::TyKind::Infer if expected_ty.is_some() => {
1971                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1972                 expected_ty.unwrap()
1973             }
1974             _ => self.ast_ty_to_ty(ty),
1975         }
1976     }
1977
1978     pub fn ty_of_fn(&self,
1979                     unsafety: hir::Unsafety,
1980                     abi: abi::Abi,
1981                     decl: &hir::FnDecl)
1982                     -> ty::PolyFnSig<'tcx> {
1983         debug!("ty_of_fn");
1984
1985         let tcx = self.tcx();
1986         let input_tys =
1987             decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1988
1989         let output_ty = match decl.output {
1990             hir::Return(ref output) => self.ast_ty_to_ty(output),
1991             hir::DefaultReturn(..) => tcx.mk_unit(),
1992         };
1993
1994         debug!("ty_of_fn: output_ty={:?}", output_ty);
1995
1996         let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1997             input_tys,
1998             output_ty,
1999             decl.c_variadic,
2000             unsafety,
2001             abi
2002         ));
2003
2004         // Find any late-bound regions declared in return type that do
2005         // not appear in the arguments. These are not well-formed.
2006         //
2007         // Example:
2008         //     for<'a> fn() -> &'a str <-- 'a is bad
2009         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2010         let inputs = bare_fn_ty.inputs();
2011         let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
2012             &inputs.map_bound(|i| i.to_owned()));
2013         let output = bare_fn_ty.output();
2014         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2015         for br in late_bound_in_ret.difference(&late_bound_in_args) {
2016             let lifetime_name = match *br {
2017                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2018                 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2019             };
2020             let mut err = struct_span_err!(tcx.sess,
2021                                            decl.output.span(),
2022                                            E0581,
2023                                            "return type references {} \
2024                                             which is not constrained by the fn input types",
2025                                            lifetime_name);
2026             if let ty::BrAnon(_) = *br {
2027                 // The only way for an anonymous lifetime to wind up
2028                 // in the return type but **also** be unconstrained is
2029                 // if it only appears in "associated types" in the
2030                 // input. See #47511 for an example. In this case,
2031                 // though we can easily give a hint that ought to be
2032                 // relevant.
2033                 err.note("lifetimes appearing in an associated type \
2034                           are not considered constrained");
2035             }
2036             err.emit();
2037         }
2038
2039         bare_fn_ty
2040     }
2041
2042     /// Given the bounds on an object, determines what single region bound (if any) we can
2043     /// use to summarize this type. The basic idea is that we will use the bound the user
2044     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2045     /// for region bounds. It may be that we can derive no bound at all, in which case
2046     /// we return `None`.
2047     fn compute_object_lifetime_bound(&self,
2048         span: Span,
2049         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
2050         -> Option<ty::Region<'tcx>> // if None, use the default
2051     {
2052         let tcx = self.tcx();
2053
2054         debug!("compute_opt_region_bound(existential_predicates={:?})",
2055                existential_predicates);
2056
2057         // No explicit region bound specified. Therefore, examine trait
2058         // bounds and see if we can derive region bounds from those.
2059         let derived_region_bounds =
2060             object_region_bounds(tcx, existential_predicates);
2061
2062         // If there are no derived region bounds, then report back that we
2063         // can find no region bound. The caller will use the default.
2064         if derived_region_bounds.is_empty() {
2065             return None;
2066         }
2067
2068         // If any of the derived region bounds are 'static, that is always
2069         // the best choice.
2070         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2071             return Some(tcx.lifetimes.re_static);
2072         }
2073
2074         // Determine whether there is exactly one unique region in the set
2075         // of derived region bounds. If so, use that. Otherwise, report an
2076         // error.
2077         let r = derived_region_bounds[0];
2078         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2079             span_err!(tcx.sess, span, E0227,
2080                       "ambiguous lifetime bound, explicit lifetime bound required");
2081         }
2082         return Some(r);
2083     }
2084 }
2085
2086 /// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
2087 /// the remaining general trait bounds.
2088 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
2089                                          trait_bounds: &'b [hir::PolyTraitRef])
2090     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
2091 {
2092     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
2093         // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
2094         match bound.trait_ref.path.def {
2095             Def::Def(DefKind::Trait, trait_did) if tcx.trait_is_auto(trait_did) => {
2096                 true
2097             }
2098             _ => false
2099         }
2100     });
2101
2102     let auto_traits = auto_traits.into_iter().map(|tr| {
2103         if let Def::Def(DefKind::Trait, trait_did) = tr.trait_ref.path.def {
2104             trait_did
2105         } else {
2106             unreachable!()
2107         }
2108     }).collect::<Vec<_>>();
2109
2110     (auto_traits, trait_bounds)
2111 }
2112
2113 // A helper struct for conveniently grouping a set of bounds which we pass to
2114 // and return from functions in multiple places.
2115 #[derive(PartialEq, Eq, Clone, Debug)]
2116 pub struct Bounds<'tcx> {
2117     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2118     pub implicitly_sized: Option<Span>,
2119     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2120     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2121 }
2122
2123 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2124     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2125                       -> Vec<(ty::Predicate<'tcx>, Span)>
2126     {
2127         // If it could be sized, and is, add the sized predicate.
2128         let sized_predicate = self.implicitly_sized.and_then(|span| {
2129             tcx.lang_items().sized_trait().map(|sized| {
2130                 let trait_ref = ty::TraitRef {
2131                     def_id: sized,
2132                     substs: tcx.mk_substs_trait(param_ty, &[])
2133                 };
2134                 (trait_ref.to_predicate(), span)
2135             })
2136         });
2137
2138         sized_predicate.into_iter().chain(
2139             self.region_bounds.iter().map(|&(region_bound, span)| {
2140                 // Account for the binder being introduced below; no need to shift `param_ty`
2141                 // because, at present at least, it can only refer to early-bound regions.
2142                 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2143                 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2144                 (ty::Binder::dummy(outlives).to_predicate(), span)
2145             }).chain(
2146                 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2147                     (bound_trait_ref.to_predicate(), span)
2148                 })
2149             ).chain(
2150                 self.projection_bounds.iter().map(|&(projection, span)| {
2151                     (projection.to_predicate(), span)
2152                 })
2153             )
2154         ).collect()
2155     }
2156 }