]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Nest the `impl Trait` existential item inside the return type
[rust.git] / src / librustc_typeck / astconv.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Conversion from AST representation of types to the ty.rs
12 //! representation.  The main routine here is `ast_ty_to_ty()`: each use
13 //! is parameterized by an instance of `AstConv`.
14
15 use smallvec::SmallVec;
16 use hir::{self, GenericArg, GenericArgs};
17 use hir::def::Def;
18 use hir::def_id::DefId;
19 use hir::HirVec;
20 use middle::resolve_lifetime as rl;
21 use namespace::Namespace;
22 use rustc::ty::subst::{Kind, Subst, Substs};
23 use rustc::traits;
24 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
25 use rustc::ty::{GenericParamDef, GenericParamDefKind};
26 use rustc::ty::wf::object_region_bounds;
27 use rustc_target::spec::abi;
28 use std::collections::BTreeSet;
29 use std::slice;
30 use require_c_abi_if_variadic;
31 use util::common::ErrorReported;
32 use util::nodemap::FxHashMap;
33 use errors::{FatalError, DiagnosticId};
34 use lint;
35
36 use std::iter;
37 use syntax::ast;
38 use syntax::ptr::P;
39 use syntax::feature_gate::{GateIssue, emit_feature_err};
40 use syntax_pos::{Span, MultiSpan};
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                                  -> 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 /// Dummy type used for the `Self` of a `TraitRef` created for converting
103 /// a trait object, and which gets removed in `ExistentialTraitRef`.
104 /// This type must not appear anywhere in other converted types.
105 const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
106
107 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o {
108     pub fn ast_region_to_region(&self,
109         lifetime: &hir::Lifetime,
110         def: Option<&ty::GenericParamDef>)
111         -> ty::Region<'tcx>
112     {
113         let tcx = self.tcx();
114         let lifetime_name = |def_id| {
115             tcx.hir.name(tcx.hir.as_local_node_id(def_id).unwrap()).as_interned_str()
116         };
117
118         let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
119         let r = match tcx.named_region(hir_id) {
120             Some(rl::Region::Static) => {
121                 tcx.types.re_static
122             }
123
124             Some(rl::Region::LateBound(debruijn, id, _)) => {
125                 let name = lifetime_name(id);
126                 tcx.mk_region(ty::ReLateBound(debruijn,
127                     ty::BrNamed(id, name)))
128             }
129
130             Some(rl::Region::LateBoundAnon(debruijn, index)) => {
131                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
132             }
133
134             Some(rl::Region::EarlyBound(index, id, _)) => {
135                 let name = lifetime_name(id);
136                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
137                     def_id: id,
138                     index,
139                     name,
140                 }))
141             }
142
143             Some(rl::Region::Free(scope, id)) => {
144                 let name = lifetime_name(id);
145                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
146                     scope,
147                     bound_region: ty::BrNamed(id, name)
148                 }))
149
150                 // (*) -- not late-bound, won't change
151             }
152
153             None => {
154                 self.re_infer(lifetime.span, def)
155                     .unwrap_or_else(|| {
156                         // This indicates an illegal lifetime
157                         // elision. `resolve_lifetime` should have
158                         // reported an error in this case -- but if
159                         // not, let's error out.
160                         tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
161
162                         // Supply some dummy value. We don't have an
163                         // `re_error`, annoyingly, so use `'static`.
164                         tcx.types.re_static
165                     })
166             }
167         };
168
169         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
170                lifetime,
171                r);
172
173         r
174     }
175
176     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
177     /// returns an appropriate set of substitutions for this particular reference to `I`.
178     pub fn ast_path_substs_for_ty(&self,
179         span: Span,
180         def_id: DefId,
181         item_segment: &hir::PathSegment)
182         -> &'tcx Substs<'tcx>
183     {
184
185         let (substs, assoc_bindings) = item_segment.with_generic_args(|generic_args| {
186             self.create_substs_for_ast_path(
187                 span,
188                 def_id,
189                 generic_args,
190                 item_segment.infer_types,
191                 None,
192             )
193         });
194
195         assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
196
197         substs
198     }
199
200     /// Report error if there is an explicit type parameter when using `impl Trait`.
201     fn check_impl_trait(
202         tcx: TyCtxt,
203         span: Span,
204         seg: &hir::PathSegment,
205         generics: &ty::Generics,
206     ) -> bool {
207         let explicit = !seg.infer_types;
208         let impl_trait = generics.params.iter().any(|param| match param.kind {
209             ty::GenericParamDefKind::Type {
210                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
211             } => true,
212             _ => false,
213         });
214
215         if explicit && impl_trait {
216             let mut err = struct_span_err! {
217                 tcx.sess,
218                 span,
219                 E0632,
220                 "cannot provide explicit type parameters when `impl Trait` is \
221                  used in argument position."
222             };
223
224             err.emit();
225         }
226
227         impl_trait
228     }
229
230     /// Check that the correct number of generic arguments have been provided.
231     /// Used specifically for function calls.
232     pub fn check_generic_arg_count_for_call(
233         tcx: TyCtxt,
234         span: Span,
235         def: &ty::Generics,
236         seg: &hir::PathSegment,
237         is_method_call: bool,
238     ) -> bool {
239         let empty_args = P(hir::GenericArgs {
240             args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
241         });
242         let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
243         Self::check_generic_arg_count(
244             tcx,
245             span,
246             def,
247             if let Some(ref args) = seg.args {
248                 args
249             } else {
250                 &empty_args
251             },
252             if is_method_call {
253                 GenericArgPosition::MethodCall
254             } else {
255                 GenericArgPosition::Value
256             },
257             def.parent.is_none() && def.has_self, // `has_self`
258             seg.infer_types || suppress_mismatch, // `infer_types`
259         )
260     }
261
262     /// Check that the correct number of generic arguments have been provided.
263     /// This is used both for datatypes and function calls.
264     fn check_generic_arg_count(
265         tcx: TyCtxt,
266         span: Span,
267         def: &ty::Generics,
268         args: &hir::GenericArgs,
269         position: GenericArgPosition,
270         has_self: bool,
271         infer_types: bool,
272     ) -> bool {
273         // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
274         // that lifetimes will proceed types. So it suffices to check the number of each generic
275         // arguments in order to validate them with respect to the generic parameters.
276         let param_counts = def.own_counts();
277         let arg_counts = args.own_counts();
278         let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
279
280         let mut defaults: ty::GenericParamCount = Default::default();
281         for param in &def.params {
282             match param.kind {
283                 GenericParamDefKind::Lifetime => {}
284                 GenericParamDefKind::Type { has_default, .. } => {
285                     defaults.types += has_default as usize
286                 }
287             };
288         }
289
290         if position != GenericArgPosition::Type && !args.bindings.is_empty() {
291             AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
292         }
293
294         // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
295         if !infer_lifetimes {
296             if let Some(span_late) = def.has_late_bound_regions {
297                 let msg = "cannot specify lifetime arguments explicitly \
298                            if late bound lifetime parameters are present";
299                 let note = "the late bound lifetime parameter is introduced here";
300                 let span = args.args[0].span();
301                 if position == GenericArgPosition::Value
302                     && arg_counts.lifetimes != param_counts.lifetimes {
303                     let mut err = tcx.sess.struct_span_err(span, msg);
304                     err.span_note(span_late, note);
305                     err.emit();
306                     return true;
307                 } else {
308                     let mut multispan = MultiSpan::from_span(span);
309                     multispan.push_span_label(span_late, note.to_string());
310                     tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
311                                   args.args[0].id(), multispan, msg);
312                     return false;
313                 }
314             }
315         }
316
317         let check_kind_count = |kind,
318                                 required,
319                                 permitted,
320                                 provided,
321                                 offset| {
322             // We enforce the following: `required` <= `provided` <= `permitted`.
323             // For kinds without defaults (i.e. lifetimes), `required == permitted`.
324             // For other kinds (i.e. types), `permitted` may be greater than `required`.
325             if required <= provided && provided <= permitted {
326                 return false;
327             }
328
329             // Unfortunately lifetime and type parameter mismatches are typically styled
330             // differently in diagnostics, which means we have a few cases to consider here.
331             let (bound, quantifier) = if required != permitted {
332                 if provided < required {
333                     (required, "at least ")
334                 } else { // provided > permitted
335                     (permitted, "at most ")
336                 }
337             } else {
338                 (required, "")
339             };
340
341             let mut span = span;
342             let label = if required == permitted && provided > permitted {
343                 let diff = provided - permitted;
344                 if diff == 1 {
345                     // In the case when the user has provided too many arguments,
346                     // we want to point to the first unexpected argument.
347                     let first_superfluous_arg: &GenericArg = &args.args[offset + permitted];
348                     span = first_superfluous_arg.span();
349                 }
350                 format!(
351                     "{}unexpected {} argument{}",
352                     if diff != 1 { format!("{} ", diff) } else { String::new() },
353                     kind,
354                     if diff != 1 { "s" } else { "" },
355                 )
356             } else {
357                 format!(
358                     "expected {}{} {} argument{}",
359                     quantifier,
360                     bound,
361                     kind,
362                     if bound != 1 { "s" } else { "" },
363                 )
364             };
365
366             tcx.sess.struct_span_err_with_code(
367                 span,
368                 &format!(
369                     "wrong number of {} arguments: expected {}{}, found {}",
370                     kind,
371                     quantifier,
372                     bound,
373                     provided,
374                 ),
375                 DiagnosticId::Error("E0107".into())
376             ).span_label(span, label).emit();
377
378             provided > required // `suppress_error`
379         };
380
381         if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
382             check_kind_count(
383                 "lifetime",
384                 param_counts.lifetimes,
385                 param_counts.lifetimes,
386                 arg_counts.lifetimes,
387                 0,
388             );
389         }
390         if !infer_types
391             || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
392             check_kind_count(
393                 "type",
394                 param_counts.types - defaults.types - has_self as usize,
395                 param_counts.types - has_self as usize,
396                 arg_counts.types,
397                 arg_counts.lifetimes,
398             )
399         } else {
400             false
401         }
402     }
403
404     /// Creates the relevant generic argument substitutions
405     /// corresponding to a set of generic parameters.
406     pub fn create_substs_for_generic_args<'a, 'b, A, P, I>(
407         tcx: TyCtxt<'a, 'gcx, 'tcx>,
408         def_id: DefId,
409         parent_substs: &[Kind<'tcx>],
410         has_self: bool,
411         self_ty: Option<Ty<'tcx>>,
412         args_for_def_id: A,
413         provided_kind: P,
414         inferred_kind: I,
415     ) -> &'tcx Substs<'tcx> where
416         A: Fn(DefId) -> (Option<&'b GenericArgs>, bool),
417         P: Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
418         I: Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>
419     {
420         // Collect the segments of the path: we need to substitute arguments
421         // for parameters throughout the entire path (wherever there are
422         // generic parameters).
423         let mut parent_defs = tcx.generics_of(def_id);
424         let count = parent_defs.count();
425         let mut stack = vec![(def_id, parent_defs)];
426         while let Some(def_id) = parent_defs.parent {
427             parent_defs = tcx.generics_of(def_id);
428             stack.push((def_id, parent_defs));
429         }
430
431         // We manually build up the substitution, rather than using convenience
432         // methods in subst.rs so that we can iterate over the arguments and
433         // parameters in lock-step linearly, rather than trying to match each pair.
434         let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
435
436         // Iterate over each segment of the path.
437         while let Some((def_id, defs)) = stack.pop() {
438             let mut params = defs.params.iter().peekable();
439
440             // If we have already computed substitutions for parents, we can use those directly.
441             while let Some(&param) = params.peek() {
442                 if let Some(&kind) = parent_substs.get(param.index as usize) {
443                     substs.push(kind);
444                     params.next();
445                 } else {
446                     break;
447                 }
448             }
449
450             // (Unless it's been handled in `parent_substs`) `Self` is handled first.
451             if has_self {
452                 if let Some(&param) = params.peek() {
453                     if param.index == 0 {
454                         if let GenericParamDefKind::Type { .. } = param.kind {
455                             substs.push(self_ty.map(|ty| ty.into())
456                                 .unwrap_or_else(|| inferred_kind(None, param, true)));
457                             params.next();
458                         }
459                     }
460                 }
461             }
462
463             // Check whether this segment takes generic arguments and the user has provided any.
464             let (generic_args, infer_types) = args_for_def_id(def_id);
465
466             let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
467                 .peekable();
468
469             loop {
470                 // We're going to iterate through the generic arguments that the user
471                 // provided, matching them with the generic parameters we expect.
472                 // Mismatches can occur as a result of elided lifetimes, or for malformed
473                 // input. We try to handle both sensibly.
474                 match (args.peek(), params.peek()) {
475                     (Some(&arg), Some(&param)) => {
476                         match (arg, &param.kind) {
477                             (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
478                             | (GenericArg::Type(_), GenericParamDefKind::Type { .. }) => {
479                                 substs.push(provided_kind(param, arg));
480                                 args.next();
481                                 params.next();
482                             }
483                             (GenericArg::Lifetime(_), GenericParamDefKind::Type { .. }) => {
484                                 // We expected a type argument, but got a lifetime
485                                 // argument. This is an error, but we need to handle it
486                                 // gracefully so we can report sensible errors. In this
487                                 // case, we're simply going to infer this argument.
488                                 args.next();
489                             }
490                             (GenericArg::Type(_), GenericParamDefKind::Lifetime) => {
491                                 // We expected a lifetime argument, but got a type
492                                 // argument. That means we're inferring the lifetimes.
493                                 substs.push(inferred_kind(None, param, infer_types));
494                                 params.next();
495                             }
496                         }
497                     }
498                     (Some(_), None) => {
499                         // We should never be able to reach this point with well-formed input.
500                         // Getting to this point means the user supplied more arguments than
501                         // there are parameters.
502                         args.next();
503                     }
504                     (None, Some(&param)) => {
505                         // If there are fewer arguments than parameters, it means
506                         // we're inferring the remaining arguments.
507                         match param.kind {
508                             GenericParamDefKind::Lifetime | GenericParamDefKind::Type { .. } => {
509                                 let kind = inferred_kind(Some(&substs), param, infer_types);
510                                 substs.push(kind);
511                             }
512                         }
513                         args.next();
514                         params.next();
515                     }
516                     (None, None) => break,
517                 }
518             }
519         }
520
521         tcx.intern_substs(&substs)
522     }
523
524     /// Given the type/region arguments provided to some path (along with
525     /// an implicit Self, if this is a trait reference) returns the complete
526     /// set of substitutions. This may involve applying defaulted type parameters.
527     ///
528     /// Note that the type listing given here is *exactly* what the user provided.
529     fn create_substs_for_ast_path(&self,
530         span: Span,
531         def_id: DefId,
532         generic_args: &hir::GenericArgs,
533         infer_types: bool,
534         self_ty: Option<Ty<'tcx>>)
535         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
536     {
537         // If the type is parameterized by this region, then replace this
538         // region with the current anon region binding (in other words,
539         // whatever & would get replaced with).
540         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
541                 generic_args={:?})",
542                def_id, self_ty, generic_args);
543
544         let tcx = self.tcx();
545         let generic_params = tcx.generics_of(def_id);
546
547         // If a self-type was declared, one should be provided.
548         assert_eq!(generic_params.has_self, self_ty.is_some());
549
550         let has_self = generic_params.has_self;
551         Self::check_generic_arg_count(
552             self.tcx(),
553             span,
554             &generic_params,
555             &generic_args,
556             GenericArgPosition::Type,
557             has_self,
558             infer_types,
559         );
560
561         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
562         let default_needs_object_self = |param: &ty::GenericParamDef| {
563             if let GenericParamDefKind::Type { has_default, .. } = param.kind {
564                 if is_object && has_default {
565                     if tcx.at(span).type_of(param.def_id).has_self_ty() {
566                         // There is no suitable inference default for a type parameter
567                         // that references self, in an object type.
568                         return true;
569                     }
570                 }
571             }
572
573             false
574         };
575
576         let substs = Self::create_substs_for_generic_args(
577             self.tcx(),
578             def_id,
579             &[][..],
580             self_ty.is_some(),
581             self_ty,
582             // Provide the generic args, and whether types should be inferred.
583             |_| (Some(generic_args), infer_types),
584             // Provide substitutions for parameters for which (valid) arguments have been provided.
585             |param, arg| {
586                 match (&param.kind, arg) {
587                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
588                         self.ast_region_to_region(&lt, Some(param)).into()
589                     }
590                     (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
591                         self.ast_ty_to_ty(&ty).into()
592                     }
593                     _ => unreachable!(),
594                 }
595             },
596             // Provide substitutions for parameters for which arguments are inferred.
597             |substs, param, infer_types| {
598                 match param.kind {
599                     GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
600                     GenericParamDefKind::Type { has_default, .. } => {
601                         if !infer_types && has_default {
602                             // No type parameter provided, but a default exists.
603
604                             // If we are converting an object type, then the
605                             // `Self` parameter is unknown. However, some of the
606                             // other type parameters may reference `Self` in their
607                             // defaults. This will lead to an ICE if we are not
608                             // careful!
609                             if default_needs_object_self(param) {
610                                 struct_span_err!(tcx.sess, span, E0393,
611                                                     "the type parameter `{}` must be explicitly \
612                                                      specified",
613                                                     param.name)
614                                     .span_label(span,
615                                                 format!("missing reference to `{}`", param.name))
616                                     .note(&format!("because of the default `Self` reference, \
617                                                     type parameters must be specified on object \
618                                                     types"))
619                                     .emit();
620                                 tcx.types.err.into()
621                             } else {
622                                 // This is a default type parameter.
623                                 self.normalize_ty(
624                                     span,
625                                     tcx.at(span).type_of(param.def_id)
626                                        .subst_spanned(tcx, substs.unwrap(), Some(span))
627                                 ).into()
628                             }
629                         } else if infer_types {
630                             // No type parameters were provided, we can infer all.
631                             if !default_needs_object_self(param) {
632                                 self.ty_infer_for_def(param, span).into()
633                             } else {
634                                 self.ty_infer(span).into()
635                             }
636                         } else {
637                             // We've already errored above about the mismatch.
638                             tcx.types.err.into()
639                         }
640                     }
641                 }
642             },
643         );
644
645         let assoc_bindings = generic_args.bindings.iter().map(|binding| {
646             ConvertedBinding {
647                 item_name: binding.ident,
648                 ty: self.ast_ty_to_ty(&binding.ty),
649                 span: binding.span,
650             }
651         }).collect();
652
653         debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
654                generic_params, self_ty, substs);
655
656         (substs, assoc_bindings)
657     }
658
659     /// Instantiates the path for the given trait reference, assuming that it's
660     /// bound to a valid trait type. Returns the def_id for the defining trait.
661     /// The type _cannot_ be a type other than a trait type.
662     ///
663     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
664     /// are disallowed. Otherwise, they are pushed onto the vector given.
665     pub fn instantiate_mono_trait_ref(&self,
666         trait_ref: &hir::TraitRef,
667         self_ty: Ty<'tcx>)
668         -> ty::TraitRef<'tcx>
669     {
670         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
671
672         let trait_def_id = self.trait_def_id(trait_ref);
673         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
674                                         trait_def_id,
675                                         self_ty,
676                                         trait_ref.path.segments.last().unwrap())
677     }
678
679     /// Get the DefId of the given trait ref. It _must_ actually be a trait.
680     fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
681         let path = &trait_ref.path;
682         match path.def {
683             Def::Trait(trait_def_id) => trait_def_id,
684             Def::TraitAlias(alias_def_id) => alias_def_id,
685             Def::Err => {
686                 FatalError.raise();
687             }
688             _ => unreachable!(),
689         }
690     }
691
692     /// The given `trait_ref` must actually be trait.
693     pub(super) fn instantiate_poly_trait_ref_inner(&self,
694         trait_ref: &hir::TraitRef,
695         self_ty: Ty<'tcx>,
696         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
697         speculative: bool)
698         -> ty::PolyTraitRef<'tcx>
699     {
700         let trait_def_id = self.trait_def_id(trait_ref);
701
702         debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
703
704         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
705
706         let (substs, assoc_bindings) =
707             self.create_substs_for_ast_trait_ref(trait_ref.path.span,
708                                                  trait_def_id,
709                                                  self_ty,
710                                                  trait_ref.path.segments.last().unwrap());
711         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
712
713         let mut dup_bindings = FxHashMap::default();
714         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
715             // specify type to assert that error was already reported in Err case:
716             let predicate: Result<_, ErrorReported> =
717                 self.ast_type_binding_to_poly_projection_predicate(
718                     trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
719             // ok to ignore Err() because ErrorReported (see above)
720             Some((predicate.ok()?, binding.span))
721         }));
722
723         debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
724                trait_ref, poly_projections, poly_trait_ref);
725         poly_trait_ref
726     }
727
728     pub fn instantiate_poly_trait_ref(&self,
729         poly_trait_ref: &hir::PolyTraitRef,
730         self_ty: Ty<'tcx>,
731         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
732         -> ty::PolyTraitRef<'tcx>
733     {
734         self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
735                                               poly_projections, false)
736     }
737
738     fn ast_path_to_mono_trait_ref(&self,
739                                   span: Span,
740                                   trait_def_id: DefId,
741                                   self_ty: Ty<'tcx>,
742                                   trait_segment: &hir::PathSegment)
743                                   -> ty::TraitRef<'tcx>
744     {
745         let (substs, assoc_bindings) =
746             self.create_substs_for_ast_trait_ref(span,
747                                                  trait_def_id,
748                                                  self_ty,
749                                                  trait_segment);
750         assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
751         ty::TraitRef::new(trait_def_id, substs)
752     }
753
754     fn create_substs_for_ast_trait_ref(&self,
755                                        span: Span,
756                                        trait_def_id: DefId,
757                                        self_ty: Ty<'tcx>,
758                                        trait_segment: &hir::PathSegment)
759                                        -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
760     {
761         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
762                trait_segment);
763
764         let trait_def = self.tcx().trait_def(trait_def_id);
765
766         if !self.tcx().features().unboxed_closures &&
767             trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
768             != trait_def.paren_sugar {
769             // For now, require that parenthetical notation be used only with `Fn()` etc.
770             let msg = if trait_def.paren_sugar {
771                 "the precise format of `Fn`-family traits' type parameters is subject to change. \
772                  Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
773             } else {
774                 "parenthetical notation is only stable when used with `Fn`-family traits"
775             };
776             emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
777                              span, GateIssue::Language, msg);
778         }
779
780         trait_segment.with_generic_args(|generic_args| {
781             self.create_substs_for_ast_path(span,
782                                             trait_def_id,
783                                             generic_args,
784                                             trait_segment.infer_types,
785                                             Some(self_ty))
786         })
787     }
788
789     fn trait_defines_associated_type_named(&self,
790                                            trait_def_id: DefId,
791                                            assoc_name: ast::Ident)
792                                            -> bool
793     {
794         self.tcx().associated_items(trait_def_id).any(|item| {
795             item.kind == ty::AssociatedKind::Type &&
796             self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
797         })
798     }
799
800     fn ast_type_binding_to_poly_projection_predicate(
801         &self,
802         ref_id: ast::NodeId,
803         trait_ref: ty::PolyTraitRef<'tcx>,
804         binding: &ConvertedBinding<'tcx>,
805         speculative: bool,
806         dup_bindings: &mut FxHashMap<DefId, Span>)
807         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
808     {
809         let tcx = self.tcx();
810
811         if !speculative {
812             // Given something like `U : SomeTrait<T=X>`, we want to produce a
813             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
814             // subtle in the event that `T` is defined in a supertrait of
815             // `SomeTrait`, because in that case we need to upcast.
816             //
817             // That is, consider this case:
818             //
819             // ```
820             // trait SubTrait : SuperTrait<int> { }
821             // trait SuperTrait<A> { type T; }
822             //
823             // ... B : SubTrait<T=foo> ...
824             // ```
825             //
826             // We want to produce `<B as SuperTrait<int>>::T == foo`.
827
828             // Find any late-bound regions declared in `ty` that are not
829             // declared in the trait-ref. These are not wellformed.
830             //
831             // Example:
832             //
833             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
834             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
835             let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
836             let late_bound_in_ty =
837                 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
838             debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
839             debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
840             for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
841                 let br_name = match *br {
842                     ty::BrNamed(_, name) => name,
843                     _ => {
844                         span_bug!(
845                             binding.span,
846                             "anonymous bound region {:?} in binding but not trait ref",
847                             br);
848                     }
849                 };
850                 struct_span_err!(tcx.sess,
851                                 binding.span,
852                                 E0582,
853                                 "binding for associated type `{}` references lifetime `{}`, \
854                                  which does not appear in the trait input types",
855                                 binding.item_name, br_name)
856                     .emit();
857             }
858         }
859
860         let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
861                                                                     binding.item_name) {
862             // Simple case: X is defined in the current trait.
863             Ok(trait_ref)
864         } else {
865             // Otherwise, we have to walk through the supertraits to find
866             // those that do.
867             let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
868                 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
869             });
870             self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
871                                           binding.item_name, binding.span)
872         }?;
873
874         let (assoc_ident, def_scope) =
875             tcx.adjust_ident(binding.item_name, candidate.def_id(), ref_id);
876         let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
877             i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
878         }).expect("missing associated type");
879
880         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
881             let msg = format!("associated type `{}` is private", binding.item_name);
882             tcx.sess.span_err(binding.span, &msg);
883         }
884         tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
885
886         if !speculative {
887             dup_bindings.entry(assoc_ty.def_id)
888                 .and_modify(|prev_span| {
889                     let mut err = self.tcx().struct_span_lint_node(
890                         ::rustc::lint::builtin::DUPLICATE_ASSOCIATED_TYPE_BINDINGS,
891                         ref_id,
892                         binding.span,
893                         &format!("associated type binding `{}` specified more than once",
894                                  binding.item_name)
895                     );
896                     err.span_label(binding.span, "used more than once");
897                     err.span_label(*prev_span, format!("first use of `{}`", binding.item_name));
898                     err.emit();
899                 })
900                 .or_insert(binding.span);
901         }
902
903         Ok(candidate.map_bound(|trait_ref| {
904             ty::ProjectionPredicate {
905                 projection_ty: ty::ProjectionTy::from_ref_and_name(
906                     tcx,
907                     trait_ref,
908                     binding.item_name,
909                 ),
910                 ty: binding.ty,
911             }
912         }))
913     }
914
915     fn ast_path_to_ty(&self,
916         span: Span,
917         did: DefId,
918         item_segment: &hir::PathSegment)
919         -> Ty<'tcx>
920     {
921         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
922         self.normalize_ty(
923             span,
924             self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
925         )
926     }
927
928     /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
929     /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
930     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
931                                 -> ty::ExistentialTraitRef<'tcx> {
932         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
933         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
934     }
935
936     fn conv_object_ty_poly_trait_ref(&self,
937         span: Span,
938         trait_bounds: &[hir::PolyTraitRef],
939         lifetime: &hir::Lifetime)
940         -> Ty<'tcx>
941     {
942         let tcx = self.tcx();
943
944         if trait_bounds.is_empty() {
945             span_err!(tcx.sess, span, E0224,
946                       "at least one non-builtin trait is required for an object type");
947             return tcx.types.err;
948         }
949
950         let mut projection_bounds = vec![];
951         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
952         let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
953                                                         dummy_self,
954                                                         &mut projection_bounds);
955
956         for trait_bound in trait_bounds[1..].iter() {
957             // Sanity check for non-principal trait bounds
958             self.instantiate_poly_trait_ref(trait_bound,
959                                             dummy_self,
960                                             &mut vec![]);
961         }
962
963         let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
964
965         if !trait_bounds.is_empty() {
966             let b = &trait_bounds[0];
967             let span = b.trait_ref.path.span;
968             struct_span_err!(self.tcx().sess, span, E0225,
969                 "only auto traits can be used as additional traits in a trait object")
970                 .span_label(span, "non-auto additional trait")
971                 .emit();
972         }
973
974         // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
975         let existential_principal = principal.map_bound(|trait_ref| {
976             self.trait_ref_to_existential(trait_ref)
977         });
978         let existential_projections = projection_bounds.iter().map(|(bound, _)| {
979             bound.map_bound(|b| {
980                 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
981                 ty::ExistentialProjection {
982                     ty: b.ty,
983                     item_def_id: b.projection_ty.item_def_id,
984                     substs: trait_ref.substs,
985                 }
986             })
987         });
988
989         // check that there are no gross object safety violations,
990         // most importantly, that the supertraits don't contain Self,
991         // to avoid ICE-s.
992         let object_safety_violations =
993             tcx.astconv_object_safety_violations(principal.def_id());
994         if !object_safety_violations.is_empty() {
995             tcx.report_object_safety_error(
996                 span, principal.def_id(), object_safety_violations)
997                .emit();
998             return tcx.types.err;
999         }
1000
1001         // use a btreeset to keep output in a more consistent order
1002         let mut associated_types = BTreeSet::default();
1003
1004         for tr in traits::supertraits(tcx, principal) {
1005             associated_types.extend(tcx.associated_items(tr.def_id())
1006                 .filter(|item| item.kind == ty::AssociatedKind::Type)
1007                 .map(|item| item.def_id));
1008         }
1009
1010         for (projection_bound, _) in &projection_bounds {
1011             associated_types.remove(&projection_bound.projection_def_id());
1012         }
1013
1014         for item_def_id in associated_types {
1015             let assoc_item = tcx.associated_item(item_def_id);
1016             let trait_def_id = assoc_item.container.id();
1017             struct_span_err!(tcx.sess, span, E0191, "the value of the associated type `{}` \
1018                                                      (from the trait `{}`) must be specified",
1019                                                     assoc_item.ident,
1020                                                     tcx.item_path_str(trait_def_id))
1021                 .span_label(span, format!("missing associated type `{}` value",
1022                                           assoc_item.ident))
1023                 .emit();
1024         }
1025
1026         // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1027         auto_traits.sort();
1028         auto_traits.dedup();
1029
1030         // skip_binder is okay, because the predicates are re-bound.
1031         let mut v =
1032             iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1033             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1034             .chain(existential_projections
1035                 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1036             .collect::<SmallVec<[_; 8]>>();
1037         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1038         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1039
1040         // Explicitly specified region bound. Use that.
1041         let region_bound = if !lifetime.is_elided() {
1042             self.ast_region_to_region(lifetime, None)
1043         } else {
1044             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1045                 let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
1046                 if tcx.named_region(hir_id).is_some() {
1047                     self.ast_region_to_region(lifetime, None)
1048                 } else {
1049                     self.re_infer(span, None).unwrap_or_else(|| {
1050                         span_err!(tcx.sess, span, E0228,
1051                                   "the lifetime bound for this object type cannot be deduced \
1052                                    from context; please supply an explicit bound");
1053                         tcx.types.re_static
1054                     })
1055                 }
1056             })
1057         };
1058
1059         debug!("region_bound: {:?}", region_bound);
1060
1061         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1062         debug!("trait_object_type: {:?}", ty);
1063         ty
1064     }
1065
1066     fn report_ambiguous_associated_type(&self,
1067                                         span: Span,
1068                                         type_str: &str,
1069                                         trait_str: &str,
1070                                         name: &str) {
1071         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1072             .span_label(span, "ambiguous associated type")
1073             .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1074                            type_str, trait_str, name))
1075             .emit();
1076
1077     }
1078
1079     // Search for a bound on a type parameter which includes the associated item
1080     // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1081     // This function will fail if there are no suitable bounds or there is
1082     // any ambiguity.
1083     fn find_bound_for_assoc_item(&self,
1084                                  ty_param_def_id: DefId,
1085                                  assoc_name: ast::Ident,
1086                                  span: Span)
1087                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1088     {
1089         let tcx = self.tcx();
1090
1091         let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
1092             .predicates.into_iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()).collect();
1093
1094         // Check that there is exactly one way to find an associated type with the
1095         // correct name.
1096         let suitable_bounds = traits::transitive_bounds(tcx, &bounds)
1097             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1098
1099         let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
1100         let param_name = tcx.hir.ty_param_name(param_node_id);
1101         self.one_bound_for_assoc_type(suitable_bounds,
1102                                       &param_name.as_str(),
1103                                       assoc_name,
1104                                       span)
1105     }
1106
1107
1108     // Checks that bounds contains exactly one element and reports appropriate
1109     // errors otherwise.
1110     fn one_bound_for_assoc_type<I>(&self,
1111                                    mut bounds: I,
1112                                    ty_param_name: &str,
1113                                    assoc_name: ast::Ident,
1114                                    span: Span)
1115         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1116         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1117     {
1118         let bound = match bounds.next() {
1119             Some(bound) => bound,
1120             None => {
1121                 struct_span_err!(self.tcx().sess, span, E0220,
1122                                  "associated type `{}` not found for `{}`",
1123                                  assoc_name,
1124                                  ty_param_name)
1125                   .span_label(span, format!("associated type `{}` not found", assoc_name))
1126                   .emit();
1127                 return Err(ErrorReported);
1128             }
1129         };
1130
1131         if let Some(bound2) = bounds.next() {
1132             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1133             let mut err = struct_span_err!(
1134                 self.tcx().sess, span, E0221,
1135                 "ambiguous associated type `{}` in bounds of `{}`",
1136                 assoc_name,
1137                 ty_param_name);
1138             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1139
1140             for bound in bounds {
1141                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1142                     item.kind == ty::AssociatedKind::Type &&
1143                         self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1144                 })
1145                 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
1146
1147                 if let Some(span) = bound_span {
1148                     err.span_label(span, format!("ambiguous `{}` from `{}`",
1149                                                  assoc_name,
1150                                                  bound));
1151                 } else {
1152                     span_note!(&mut err, span,
1153                                "associated type `{}` could derive from `{}`",
1154                                ty_param_name,
1155                                bound);
1156                 }
1157             }
1158             err.emit();
1159         }
1160
1161         return Ok(bound);
1162     }
1163
1164     // Create a type from a path to an associated type.
1165     // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1166     // and item_segment is the path segment for D. We return a type and a def for
1167     // the whole path.
1168     // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1169     // parameter or Self.
1170     pub fn associated_path_def_to_ty(&self,
1171                                      ref_id: ast::NodeId,
1172                                      span: Span,
1173                                      ty: Ty<'tcx>,
1174                                      ty_path_def: Def,
1175                                      item_segment: &hir::PathSegment)
1176                                      -> (Ty<'tcx>, Def)
1177     {
1178         let tcx = self.tcx();
1179         let assoc_name = item_segment.ident;
1180
1181         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1182
1183         self.prohibit_generics(slice::from_ref(item_segment));
1184
1185         // Find the type of the associated item, and the trait where the associated
1186         // item is declared.
1187         let bound = match (&ty.sty, ty_path_def) {
1188             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1189                 // `Self` in an impl of a trait - we have a concrete self type and a
1190                 // trait reference.
1191                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1192                     Some(trait_ref) => trait_ref,
1193                     None => {
1194                         // A cycle error occurred, most likely.
1195                         return (tcx.types.err, Def::Err);
1196                     }
1197                 };
1198
1199                 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1200                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1201
1202                 match self.one_bound_for_assoc_type(candidates, "Self", assoc_name, span) {
1203                     Ok(bound) => bound,
1204                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1205                 }
1206             }
1207             (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1208             (&ty::Param(_), Def::TyParam(param_did)) => {
1209                 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
1210                     Ok(bound) => bound,
1211                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1212                 }
1213             }
1214             _ => {
1215                 // Don't print TyErr to the user.
1216                 if !ty.references_error() {
1217                     self.report_ambiguous_associated_type(span,
1218                                                           &ty.to_string(),
1219                                                           "Trait",
1220                                                           &assoc_name.as_str());
1221                 }
1222                 return (tcx.types.err, Def::Err);
1223             }
1224         };
1225
1226         let trait_did = bound.def_id();
1227         let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_name, trait_did, ref_id);
1228         let item = tcx.associated_items(trait_did).find(|i| {
1229             Namespace::from(i.kind) == Namespace::Type &&
1230                 i.ident.modern() == assoc_ident
1231         })
1232         .expect("missing associated type");
1233
1234         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1235         let ty = self.normalize_ty(span, ty);
1236
1237         let def = Def::AssociatedTy(item.def_id);
1238         if !item.vis.is_accessible_from(def_scope, tcx) {
1239             let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
1240             tcx.sess.span_err(span, &msg);
1241         }
1242         tcx.check_stability(item.def_id, Some(ref_id), span);
1243
1244         (ty, def)
1245     }
1246
1247     fn qpath_to_ty(&self,
1248                    span: Span,
1249                    opt_self_ty: Option<Ty<'tcx>>,
1250                    item_def_id: DefId,
1251                    trait_segment: &hir::PathSegment,
1252                    item_segment: &hir::PathSegment)
1253                    -> Ty<'tcx>
1254     {
1255         let tcx = self.tcx();
1256         let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1257
1258         self.prohibit_generics(slice::from_ref(item_segment));
1259
1260         let self_ty = if let Some(ty) = opt_self_ty {
1261             ty
1262         } else {
1263             let path_str = tcx.item_path_str(trait_def_id);
1264             self.report_ambiguous_associated_type(span,
1265                                                   "Type",
1266                                                   &path_str,
1267                                                   &item_segment.ident.as_str());
1268             return tcx.types.err;
1269         };
1270
1271         debug!("qpath_to_ty: self_type={:?}", self_ty);
1272
1273         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1274                                                         trait_def_id,
1275                                                         self_ty,
1276                                                         trait_segment);
1277
1278         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1279
1280         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1281     }
1282
1283     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(&self, segments: T) {
1284         for segment in segments {
1285             segment.with_generic_args(|generic_args| {
1286                 let (mut err_for_lt, mut err_for_ty) = (false, false);
1287                 for arg in &generic_args.args {
1288                     let (mut span_err, span, kind) = match arg {
1289                         hir::GenericArg::Lifetime(lt) => {
1290                             if err_for_lt { continue }
1291                             err_for_lt = true;
1292                             (struct_span_err!(self.tcx().sess, lt.span, E0110,
1293                                               "lifetime parameters are not allowed on this type"),
1294                              lt.span,
1295                              "lifetime")
1296                         }
1297                         hir::GenericArg::Type(ty) => {
1298                             if err_for_ty { continue }
1299                             err_for_ty = true;
1300                             (struct_span_err!(self.tcx().sess, ty.span, E0109,
1301                                               "type parameters are not allowed on this type"),
1302                              ty.span,
1303                              "type")
1304                         }
1305                     };
1306                     span_err.span_label(span, format!("{} parameter not allowed", kind))
1307                             .emit();
1308                     if err_for_lt && err_for_ty {
1309                         break;
1310                     }
1311                 }
1312                 for binding in &generic_args.bindings {
1313                     Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1314                     break;
1315                 }
1316             })
1317         }
1318     }
1319
1320     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt, span: Span) {
1321         let mut err = struct_span_err!(tcx.sess, span, E0229,
1322                                        "associated type bindings are not allowed here");
1323         err.span_label(span, "associated type not allowed here").emit();
1324     }
1325
1326     // Check a type Path and convert it to a Ty.
1327     pub fn def_to_ty(&self,
1328                      opt_self_ty: Option<Ty<'tcx>>,
1329                      path: &hir::Path,
1330                      permit_variants: bool)
1331                      -> Ty<'tcx> {
1332         let tcx = self.tcx();
1333
1334         debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1335                path.def, opt_self_ty, path.segments);
1336
1337         let span = path.span;
1338         match path.def {
1339             Def::Existential(did) => {
1340                 // check for desugared impl trait
1341                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1342                 let item_segment = path.segments.split_last().unwrap();
1343                 self.prohibit_generics(item_segment.1);
1344                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1345                 self.normalize_ty(
1346                     span,
1347                     tcx.mk_opaque(did, substs),
1348                 )
1349             }
1350             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1351             Def::Union(did) | Def::ForeignTy(did) => {
1352                 assert_eq!(opt_self_ty, None);
1353                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1354                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1355             }
1356             Def::Variant(did) if permit_variants => {
1357                 // Convert "variant type" as if it were a real type.
1358                 // The resulting `Ty` is type of the variant's enum for now.
1359                 assert_eq!(opt_self_ty, None);
1360                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1361                 self.ast_path_to_ty(span,
1362                                     tcx.parent_def_id(did).unwrap(),
1363                                     path.segments.last().unwrap())
1364             }
1365             Def::TyParam(did) => {
1366                 assert_eq!(opt_self_ty, None);
1367                 self.prohibit_generics(&path.segments);
1368
1369                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1370                 let item_id = tcx.hir.get_parent_node(node_id);
1371                 let item_def_id = tcx.hir.local_def_id(item_id);
1372                 let generics = tcx.generics_of(item_def_id);
1373                 let index = generics.param_def_id_to_index[&tcx.hir.local_def_id(node_id)];
1374                 tcx.mk_ty_param(index, tcx.hir.name(node_id).as_interned_str())
1375             }
1376             Def::SelfTy(_, Some(def_id)) => {
1377                 // Self in impl (we know the concrete type).
1378
1379                 assert_eq!(opt_self_ty, None);
1380                 self.prohibit_generics(&path.segments);
1381
1382                 tcx.at(span).type_of(def_id)
1383             }
1384             Def::SelfTy(Some(_), None) => {
1385                 // Self in trait.
1386                 assert_eq!(opt_self_ty, None);
1387                 self.prohibit_generics(&path.segments);
1388                 tcx.mk_self_type()
1389             }
1390             Def::AssociatedTy(def_id) => {
1391                 self.prohibit_generics(&path.segments[..path.segments.len()-2]);
1392                 self.qpath_to_ty(span,
1393                                  opt_self_ty,
1394                                  def_id,
1395                                  &path.segments[path.segments.len()-2],
1396                                  path.segments.last().unwrap())
1397             }
1398             Def::PrimTy(prim_ty) => {
1399                 assert_eq!(opt_self_ty, None);
1400                 self.prohibit_generics(&path.segments);
1401                 match prim_ty {
1402                     hir::Bool => tcx.types.bool,
1403                     hir::Char => tcx.types.char,
1404                     hir::Int(it) => tcx.mk_mach_int(it),
1405                     hir::Uint(uit) => tcx.mk_mach_uint(uit),
1406                     hir::Float(ft) => tcx.mk_mach_float(ft),
1407                     hir::Str => tcx.mk_str()
1408                 }
1409             }
1410             Def::Err => {
1411                 self.set_tainted_by_errors();
1412                 return self.tcx().types.err;
1413             }
1414             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1415         }
1416     }
1417
1418     /// Parses the programmer's textual representation of a type into our
1419     /// internal notion of a type.
1420     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1421         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1422                ast_ty.id, ast_ty);
1423
1424         let tcx = self.tcx();
1425
1426         let result_ty = match ast_ty.node {
1427             hir::TyKind::Slice(ref ty) => {
1428                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1429             }
1430             hir::TyKind::Ptr(ref mt) => {
1431                 tcx.mk_ptr(ty::TypeAndMut {
1432                     ty: self.ast_ty_to_ty(&mt.ty),
1433                     mutbl: mt.mutbl
1434                 })
1435             }
1436             hir::TyKind::Rptr(ref region, ref mt) => {
1437                 let r = self.ast_region_to_region(region, None);
1438                 debug!("Ref r={:?}", r);
1439                 let t = self.ast_ty_to_ty(&mt.ty);
1440                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1441             }
1442             hir::TyKind::Never => {
1443                 tcx.types.never
1444             },
1445             hir::TyKind::Tup(ref fields) => {
1446                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1447             }
1448             hir::TyKind::BareFn(ref bf) => {
1449                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1450                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1451             }
1452             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1453                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1454             }
1455             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1456                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1457                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1458                     self.ast_ty_to_ty(qself)
1459                 });
1460                 self.def_to_ty(opt_self_ty, path, false)
1461             }
1462             hir::TyKind::Def(item_id, ref lifetimes) => {
1463                 let did = tcx.hir.local_def_id(item_id.id);
1464                 self.impl_trait_ty_to_ty(did, lifetimes)
1465             },
1466             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1467                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1468                 let ty = self.ast_ty_to_ty(qself);
1469
1470                 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1471                     path.def
1472                 } else {
1473                     Def::Err
1474                 };
1475                 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1476             }
1477             hir::TyKind::Array(ref ty, ref length) => {
1478                 let length_def_id = tcx.hir.local_def_id(length.id);
1479                 let substs = Substs::identity_for_item(tcx, length_def_id);
1480                 let length = ty::Const::unevaluated(tcx, length_def_id, substs, tcx.types.usize);
1481                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1482                 self.normalize_ty(ast_ty.span, array_ty)
1483             }
1484             hir::TyKind::Typeof(ref _e) => {
1485                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1486                                  "`typeof` is a reserved keyword but unimplemented")
1487                     .span_label(ast_ty.span, "reserved keyword")
1488                     .emit();
1489
1490                 tcx.types.err
1491             }
1492             hir::TyKind::Infer => {
1493                 // Infer also appears as the type of arguments or return
1494                 // values in a ExprKind::Closure, or as
1495                 // the type of local variables. Both of these cases are
1496                 // handled specially and will not descend into this routine.
1497                 self.ty_infer(ast_ty.span)
1498             }
1499             hir::TyKind::Err => {
1500                 tcx.types.err
1501             }
1502         };
1503
1504         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1505         result_ty
1506     }
1507
1508     pub fn impl_trait_ty_to_ty(
1509         &self,
1510         def_id: DefId,
1511         lifetimes: &[hir::GenericArg],
1512     ) -> Ty<'tcx> {
1513         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1514         let tcx = self.tcx();
1515
1516         let generics = tcx.generics_of(def_id);
1517
1518         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1519         let substs = Substs::for_item(tcx, def_id, |param, _| {
1520             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1521                 // Our own parameters are the resolved lifetimes.
1522                 match param.kind {
1523                     GenericParamDefKind::Lifetime => {
1524                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1525                             self.ast_region_to_region(lifetime, None).into()
1526                         } else {
1527                             bug!()
1528                         }
1529                     }
1530                     _ => bug!()
1531                 }
1532             } else {
1533                 // Replace all parent lifetimes with 'static.
1534                 match param.kind {
1535                     GenericParamDefKind::Lifetime => {
1536                         tcx.types.re_static.into()
1537                     }
1538                     _ => tcx.mk_param_from_def(param)
1539                 }
1540             }
1541         });
1542         debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1543
1544         let ty = tcx.mk_opaque(def_id, substs);
1545         debug!("impl_trait_ty_to_ty: {}", ty);
1546         ty
1547     }
1548
1549     pub fn ty_of_arg(&self,
1550                      ty: &hir::Ty,
1551                      expected_ty: Option<Ty<'tcx>>)
1552                      -> Ty<'tcx>
1553     {
1554         match ty.node {
1555             hir::TyKind::Infer if expected_ty.is_some() => {
1556                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1557                 expected_ty.unwrap()
1558             }
1559             _ => self.ast_ty_to_ty(ty),
1560         }
1561     }
1562
1563     pub fn ty_of_fn(&self,
1564                     unsafety: hir::Unsafety,
1565                     abi: abi::Abi,
1566                     decl: &hir::FnDecl)
1567                     -> ty::PolyFnSig<'tcx> {
1568         debug!("ty_of_fn");
1569
1570         let tcx = self.tcx();
1571         let input_tys: Vec<Ty> =
1572             decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1573
1574         let output_ty = match decl.output {
1575             hir::Return(ref output) => self.ast_ty_to_ty(output),
1576             hir::DefaultReturn(..) => tcx.mk_unit(),
1577         };
1578
1579         debug!("ty_of_fn: output_ty={:?}", output_ty);
1580
1581         let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1582             input_tys.into_iter(),
1583             output_ty,
1584             decl.variadic,
1585             unsafety,
1586             abi
1587         ));
1588
1589         // Find any late-bound regions declared in return type that do
1590         // not appear in the arguments. These are not well-formed.
1591         //
1592         // Example:
1593         //     for<'a> fn() -> &'a str <-- 'a is bad
1594         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1595         let inputs = bare_fn_ty.inputs();
1596         let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1597             &inputs.map_bound(|i| i.to_owned()));
1598         let output = bare_fn_ty.output();
1599         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1600         for br in late_bound_in_ret.difference(&late_bound_in_args) {
1601             let lifetime_name = match *br {
1602                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1603                 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1604             };
1605             let mut err = struct_span_err!(tcx.sess,
1606                                            decl.output.span(),
1607                                            E0581,
1608                                            "return type references {} \
1609                                             which is not constrained by the fn input types",
1610                                            lifetime_name);
1611             if let ty::BrAnon(_) = *br {
1612                 // The only way for an anonymous lifetime to wind up
1613                 // in the return type but **also** be unconstrained is
1614                 // if it only appears in "associated types" in the
1615                 // input. See #47511 for an example. In this case,
1616                 // though we can easily give a hint that ought to be
1617                 // relevant.
1618                 err.note("lifetimes appearing in an associated type \
1619                           are not considered constrained");
1620             }
1621             err.emit();
1622         }
1623
1624         bare_fn_ty
1625     }
1626
1627     /// Given the bounds on an object, determines what single region bound (if any) we can
1628     /// use to summarize this type. The basic idea is that we will use the bound the user
1629     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1630     /// for region bounds. It may be that we can derive no bound at all, in which case
1631     /// we return `None`.
1632     fn compute_object_lifetime_bound(&self,
1633         span: Span,
1634         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1635         -> Option<ty::Region<'tcx>> // if None, use the default
1636     {
1637         let tcx = self.tcx();
1638
1639         debug!("compute_opt_region_bound(existential_predicates={:?})",
1640                existential_predicates);
1641
1642         // No explicit region bound specified. Therefore, examine trait
1643         // bounds and see if we can derive region bounds from those.
1644         let derived_region_bounds =
1645             object_region_bounds(tcx, existential_predicates);
1646
1647         // If there are no derived region bounds, then report back that we
1648         // can find no region bound. The caller will use the default.
1649         if derived_region_bounds.is_empty() {
1650             return None;
1651         }
1652
1653         // If any of the derived region bounds are 'static, that is always
1654         // the best choice.
1655         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1656             return Some(tcx.types.re_static);
1657         }
1658
1659         // Determine whether there is exactly one unique region in the set
1660         // of derived region bounds. If so, use that. Otherwise, report an
1661         // error.
1662         let r = derived_region_bounds[0];
1663         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1664             span_err!(tcx.sess, span, E0227,
1665                       "ambiguous lifetime bound, explicit lifetime bound required");
1666         }
1667         return Some(r);
1668     }
1669 }
1670
1671 /// Divides a list of general trait bounds into two groups: auto traits (e.g. Sync and Send) and the
1672 /// remaining general trait bounds.
1673 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1674                                          trait_bounds: &'b [hir::PolyTraitRef])
1675     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1676 {
1677     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1678         // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1679         match bound.trait_ref.path.def {
1680             Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
1681                 true
1682             }
1683             _ => false
1684         }
1685     });
1686
1687     let auto_traits = auto_traits.into_iter().map(|tr| {
1688         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1689             trait_did
1690         } else {
1691             unreachable!()
1692         }
1693     }).collect::<Vec<_>>();
1694
1695     (auto_traits, trait_bounds)
1696 }
1697
1698 // A helper struct for conveniently grouping a set of bounds which we pass to
1699 // and return from functions in multiple places.
1700 #[derive(PartialEq, Eq, Clone, Debug)]
1701 pub struct Bounds<'tcx> {
1702     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
1703     pub implicitly_sized: Option<Span>,
1704     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
1705     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
1706 }
1707
1708 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1709     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1710                       -> Vec<(ty::Predicate<'tcx>, Span)>
1711     {
1712         // If it could be sized, and is, add the sized predicate
1713         let sized_predicate = self.implicitly_sized.and_then(|span| {
1714             tcx.lang_items().sized_trait().map(|sized| {
1715                 let trait_ref = ty::TraitRef {
1716                     def_id: sized,
1717                     substs: tcx.mk_substs_trait(param_ty, &[])
1718                 };
1719                 (trait_ref.to_predicate(), span)
1720             })
1721         });
1722
1723         sized_predicate.into_iter().chain(
1724             self.region_bounds.iter().map(|&(region_bound, span)| {
1725                 // account for the binder being introduced below; no need to shift `param_ty`
1726                 // because, at present at least, it can only refer to early-bound regions
1727                 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1728                 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
1729                 (ty::Binder::dummy(outlives).to_predicate(), span)
1730             }).chain(
1731                 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
1732                     (bound_trait_ref.to_predicate(), span)
1733                 })
1734             ).chain(
1735                 self.projection_bounds.iter().map(|&(projection, span)| {
1736                     (projection.to_predicate(), span)
1737                 })
1738             )
1739         ).collect()
1740     }
1741 }