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