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