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