astconv.rs 58.0 KB
Newer Older
V
Virgile Andreani 已提交
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

S
Steve Klabnik 已提交
11 12
//! Conversion from AST representation of types to the ty.rs
//! representation.  The main routine here is `ast_ty_to_ty()`: each use
13
//! is parameterized by an instance of `AstConv`.
14

15
use rustc::middle::const_val::ConstVal;
16
use rustc_data_structures::accumulate_vec::AccumulateVec;
17
use hir;
18
use hir::def::Def;
19
use hir::def_id::DefId;
20
use middle::resolve_lifetime as rl;
21
use namespace::Namespace;
22
use rustc::ty::subst::{Kind, Subst, Substs};
23
use rustc::traits;
T
Taylor Cramer 已提交
24
use rustc::ty::{self, RegionKind, Ty, TyCtxt, ToPredicate, TypeFoldable};
25
use rustc::ty::wf::object_region_bounds;
26
use std::slice;
27
use require_c_abi_if_variadic;
28
use util::common::ErrorReported;
29
use util::nodemap::FxHashSet;
30

31
use std::iter;
N
Niko Matsakis 已提交
32
use syntax::{abi, ast};
33
use syntax::feature_gate::{GateIssue, emit_feature_err};
34
use syntax_pos::Span;
35

36 37
pub trait AstConv<'gcx, 'tcx> {
    fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
38

39 40
    /// Returns the set of bounds in scope for the type parameter with
    /// the given id.
41
    fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
42
                                 -> ty::GenericPredicates<'tcx>;
43

44 45
    /// What lifetime should we use when a lifetime is omitted (and not elided)?
    fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
N
Niko Matsakis 已提交
46
                -> Option<ty::Region<'tcx>>;
47

48
    /// What type should we use when a type is omitted?
49 50 51 52
    fn ty_infer(&self, span: Span) -> Ty<'tcx>;

    /// Same as ty_infer, but with a known type parameter definition.
    fn ty_infer_for_def(&self,
53
                        _def: &ty::TypeParameterDef,
54
                        _substs: &[Kind<'tcx>],
55 56 57
                        span: Span) -> Ty<'tcx> {
        self.ty_infer(span)
    }
58

59 60 61 62 63 64 65 66 67
    /// Projecting an associated type from a (potentially)
    /// higher-ranked trait reference is more complicated, because of
    /// the possibility of late-bound regions appearing in the
    /// associated type binding. This is not legal in function
    /// signatures for that reason. In a function body, we can always
    /// handle it because we can use inference variables to remove the
    /// late-bound regions.
    fn projected_ty_from_poly_trait_ref(&self,
                                        span: Span,
68 69
                                        item_def_id: DefId,
                                        poly_trait_ref: ty::PolyTraitRef<'tcx>)
70
                                        -> Ty<'tcx>;
71

72 73
    /// Normalize an associated type coming from the user.
    fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
74 75 76 77 78 79

    /// Invoked when we encounter an error from some prior pass
    /// (e.g. resolve) that is translated into a ty-error. This is
    /// used to help suppress derived errors typeck might otherwise
    /// report.
    fn set_tainted_by_errors(&self);
80 81

    fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
82 83
}

84 85 86 87 88 89
struct ConvertedBinding<'tcx> {
    item_name: ast::Name,
    ty: Ty<'tcx>,
    span: Span,
}

90 91 92 93 94
/// Dummy type used for the `Self` of a `TraitRef` created for converting
/// a trait object, and which gets removed in `ExistentialTraitRef`.
/// This type must not appear anywhere in other converted types.
const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));

95
impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
96 97
    pub fn ast_region_to_region(&self,
        lifetime: &hir::Lifetime,
98
        def: Option<&ty::RegionParameterDef>)
N
Niko Matsakis 已提交
99
        -> ty::Region<'tcx>
100
    {
101
        let tcx = self.tcx();
102 103 104 105
        let lifetime_name = |def_id| {
            tcx.hir.name(tcx.hir.as_local_node_id(def_id).unwrap())
        };

106 107 108
        let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
        let r = match tcx.named_region(hir_id) {
            Some(rl::Region::Static) => {
109
                tcx.types.re_static
110
            }
111

112
            Some(rl::Region::LateBound(debruijn, id, _)) => {
113
                let name = lifetime_name(id);
114
                tcx.mk_region(ty::ReLateBound(debruijn,
115
                    ty::BrNamed(id, name)))
116 117
            }

118
            Some(rl::Region::LateBoundAnon(debruijn, index)) => {
119
                tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
120
            }
121

122
            Some(rl::Region::EarlyBound(index, id, _)) => {
123
                let name = lifetime_name(id);
124
                tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
125
                    def_id: id,
126 127
                    index,
                    name,
128
                }))
129
            }
130

131
            Some(rl::Region::Free(scope, id)) => {
132
                let name = lifetime_name(id);
133
                tcx.mk_region(ty::ReFree(ty::FreeRegion {
134
                    scope,
135
                    bound_region: ty::BrNamed(id, name)
136
                }))
137 138

                    // (*) -- not late-bound, won't change
139
            }
140

141
            None => {
142 143 144 145 146 147 148 149 150 151 152 153
                self.re_infer(lifetime.span, def)
                    .unwrap_or_else(|| {
                        // This indicates an illegal lifetime
                        // elision. `resolve_lifetime` should have
                        // reported an error in this case -- but if
                        // not, let's error out.
                        tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");

                        // Supply some dummy value. We don't have an
                        // `re_error`, annoyingly, so use `'static`.
                        tcx.types.re_static
                    })
154
            }
155
        };
156

157 158
        debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
                lifetime,
159
                r);
160

161
        r
162
    }
163

164 165 166 167
    /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
    /// returns an appropriate set of substitutions for this particular reference to `I`.
    pub fn ast_path_substs_for_ty(&self,
        span: Span,
168
        def_id: DefId,
169
        item_segment: &hir::PathSegment)
170
        -> &'tcx Substs<'tcx>
171
    {
172

173
        let (substs, assoc_bindings) =
174 175 176 177 178 179 180 181
            item_segment.with_parameters(|parameters| {
                self.create_substs_for_ast_path(
                    span,
                    def_id,
                    parameters,
                    item_segment.infer_types,
                    None)
            });
182

183
        assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
184

185
        substs
186
    }
187

188 189 190 191 192 193
    /// Given the type/region arguments provided to some path (along with
    /// an implicit Self, if this is a trait reference) returns the complete
    /// set of substitutions. This may involve applying defaulted type parameters.
    ///
    /// Note that the type listing given here is *exactly* what the user provided.
    fn create_substs_for_ast_path(&self,
194
        span: Span,
195
        def_id: DefId,
196
        parameters: &hir::PathParameters,
197
        infer_types: bool,
198 199
        self_ty: Option<Ty<'tcx>>)
        -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
200 201 202
    {
        let tcx = self.tcx();

203
        debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
204
               parameters={:?})",
205
               def_id, self_ty, parameters);
206

207 208 209
        // If the type is parameterized by this region, then replace this
        // region with the current anon region binding (in other words,
        // whatever & would get replaced with).
210
        let decl_generics = tcx.generics_of(def_id);
211
        let num_types_provided = parameters.types.len();
212
        let expected_num_region_params = decl_generics.regions.len();
213
        let supplied_num_region_params = parameters.lifetimes.len();
214
        if expected_num_region_params != supplied_num_region_params {
215 216 217
            report_lifetime_number_error(tcx, span,
                                         supplied_num_region_params,
                                         expected_num_region_params);
218 219
        }

220
        // If a self-type was declared, one should be provided.
221
        assert_eq!(decl_generics.has_self, self_ty.is_some());
222

223
        // Check the number of type parameters supplied by the user.
224
        let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
225
        if !infer_types || num_types_provided > ty_param_defs.len() {
226
            check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
227
        }
228

229
        let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
230 231
        let default_needs_object_self = |p: &ty::TypeParameterDef| {
            if is_object && p.has_default {
232
                if tcx.at(span).type_of(p.def_id).has_self_ty() {
233 234 235 236 237
                    // There is no suitable inference default for a type parameter
                    // that references self, in an object type.
                    return true;
                }
            }
238

239 240 241
            false
        };

242
        let substs = Substs::for_item(tcx, def_id, |def, _| {
243
            let i = def.index as usize - self_ty.is_some() as usize;
244
            if let Some(lifetime) = parameters.lifetimes.get(i) {
245 246
                self.ast_region_to_region(lifetime, Some(def))
            } else {
247
                tcx.types.re_static
248
            }
249 250
        }, |def, substs| {
            let i = def.index as usize;
251 252 253 254 255 256

            // Handle Self first, so we can adjust the index to match the AST.
            if let (0, Some(ty)) = (i, self_ty) {
                return ty;
            }

257
            let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
258
            if i < num_types_provided {
259
                // A provided type parameter.
260
                self.ast_ty_to_ty(&parameters.types[i])
261
            } else if infer_types {
262 263 264 265 266 267 268
                // No type parameters were provided, we can infer all.
                let ty_var = if !default_needs_object_self(def) {
                    self.ty_infer_for_def(def, substs, span)
                } else {
                    self.ty_infer(span)
                };
                ty_var
269
            } else if def.has_default {
270
                // No type parameter provided, but a default exists.
271

272 273 274 275 276
                // If we are converting an object type, then the
                // `Self` parameter is unknown. However, some of the
                // other type parameters may reference `Self` in their
                // defaults. This will lead to an ICE if we are not
                // careful!
277
                if default_needs_object_self(def) {
Z
zjhmale 已提交
278 279 280
                    struct_span_err!(tcx.sess, span, E0393,
                                     "the type parameter `{}` must be explicitly specified",
                                     def.name)
281
                        .span_label(span, format!("missing reference to `{}`", def.name))
Z
zjhmale 已提交
282 283 284
                        .note(&format!("because of the default `Self` reference, \
                                        type parameters must be specified on object types"))
                        .emit();
285
                    tcx.types.err
286 287
                } else {
                    // This is a default type parameter.
288 289
                    self.normalize_ty(
                        span,
290
                        tcx.at(span).type_of(def.def_id)
291 292
                            .subst_spanned(tcx, substs, Some(span))
                    )
293
                }
294
            } else {
295 296
                // We've already errored above about the mismatch.
                tcx.types.err
S
Sean Bowe 已提交
297
            }
298
        });
S
Sean Bowe 已提交
299

300 301 302 303 304
        let assoc_bindings = parameters.bindings.iter().map(|binding| {
            ConvertedBinding {
                item_name: binding.name,
                ty: self.ast_ty_to_ty(&binding.ty),
                span: binding.span,
305
            }
306
        }).collect();
S
Sean Bowe 已提交
307

308 309
        debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
               decl_generics, self_ty, substs);
S
Sean Bowe 已提交
310

311
        (substs, assoc_bindings)
312
    }
313

314 315 316 317 318 319 320 321
    /// Instantiates the path for the given trait reference, assuming that it's
    /// bound to a valid trait type. Returns the def_id for the defining trait.
    /// Fails if the type is a type other than a trait type.
    ///
    /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
    /// are disallowed. Otherwise, they are pushed onto the vector given.
    pub fn instantiate_mono_trait_ref(&self,
        trait_ref: &hir::TraitRef,
322
        self_ty: Ty<'tcx>)
323 324
        -> ty::TraitRef<'tcx>
    {
325 326
        self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);

327
        let trait_def_id = self.trait_def_id(trait_ref);
328
        self.ast_path_to_mono_trait_ref(trait_ref.path.span,
329 330 331 332
                                        trait_def_id,
                                        self_ty,
                                        trait_ref.path.segments.last().unwrap())
    }
333

334 335
    fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
        let path = &trait_ref.path;
336
        match path.def {
337
            Def::Trait(trait_def_id) => trait_def_id,
A
Alex Burka 已提交
338
            Def::TraitAlias(alias_def_id) => alias_def_id,
339 340 341 342 343
            Def::Err => {
                self.tcx().sess.fatal("cannot continue compilation due to previous error");
            }
            _ => {
                span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
344
                            self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
345
            }
N
Niko Matsakis 已提交
346 347 348
        }
    }

349 350
    pub(super) fn instantiate_poly_trait_ref_inner(&self,
        trait_ref: &hir::TraitRef,
351
        self_ty: Ty<'tcx>,
352 353
        poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>,
        speculative: bool)
354
        -> ty::PolyTraitRef<'tcx>
355
    {
356 357 358
        let trait_def_id = self.trait_def_id(trait_ref);

        debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
359

360 361
        self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);

362
        let (substs, assoc_bindings) =
363
            self.create_substs_for_ast_trait_ref(trait_ref.path.span,
364 365
                                                 trait_def_id,
                                                 self_ty,
366
                                                 trait_ref.path.segments.last().unwrap());
367 368
        let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));

369 370 371
        poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
            // specify type to assert that error was already reported in Err case:
            let predicate: Result<_, ErrorReported> =
372
                self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id, poly_trait_ref,
373
                                                                   binding, speculative);
374 375
            predicate.ok() // ok to ignore Err() because ErrorReported (see above)
        }));
376

377 378
        debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
               trait_ref, poly_projections, poly_trait_ref);
379
        poly_trait_ref
380 381
    }

382 383 384 385 386 387 388 389 390 391
    pub fn instantiate_poly_trait_ref(&self,
        poly_trait_ref: &hir::PolyTraitRef,
        self_ty: Ty<'tcx>,
        poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
        -> ty::PolyTraitRef<'tcx>
    {
        self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
                                              poly_projections, false)
    }

392 393 394
    fn ast_path_to_mono_trait_ref(&self,
                                  span: Span,
                                  trait_def_id: DefId,
395
                                  self_ty: Ty<'tcx>,
396 397 398 399
                                  trait_segment: &hir::PathSegment)
                                  -> ty::TraitRef<'tcx>
    {
        let (substs, assoc_bindings) =
400
            self.create_substs_for_ast_trait_ref(span,
401 402 403
                                                 trait_def_id,
                                                 self_ty,
                                                 trait_segment);
404
        assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
405 406
        ty::TraitRef::new(trait_def_id, substs)
    }
407

408 409 410
    fn create_substs_for_ast_trait_ref(&self,
                                       span: Span,
                                       trait_def_id: DefId,
411
                                       self_ty: Ty<'tcx>,
412 413 414 415 416 417
                                       trait_segment: &hir::PathSegment)
                                       -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
    {
        debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
               trait_segment);

418
        let trait_def = self.tcx().trait_def(trait_def_id);
419

420
        if !self.tcx().sess.features.borrow().unboxed_closures &&
421
           trait_segment.with_parameters(|p| p.parenthesized) != trait_def.paren_sugar {
422 423 424 425 426 427 428 429 430
            // For now, require that parenthetical notation be used only with `Fn()` etc.
            let msg = if trait_def.paren_sugar {
                "the precise format of `Fn`-family traits' type parameters is subject to change. \
                 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
            } else {
                "parenthetical notation is only stable when used with `Fn`-family traits"
            };
            emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
                             span, GateIssue::Language, msg);
431
        }
432

433 434 435 436 437 438 439
        trait_segment.with_parameters(|parameters| {
            self.create_substs_for_ast_path(span,
                                            trait_def_id,
                                            parameters,
                                            trait_segment.infer_types,
                                            Some(self_ty))
        })
440
    }
441

442 443 444 445 446 447
    fn trait_defines_associated_type_named(&self,
                                           trait_def_id: DefId,
                                           assoc_name: ast::Name)
                                           -> bool
    {
        self.tcx().associated_items(trait_def_id).any(|item| {
448 449
            item.kind == ty::AssociatedKind::Type &&
            self.tcx().hygienic_eq(assoc_name, item.name, trait_def_id)
450 451 452
        })
    }

453 454
    fn ast_type_binding_to_poly_projection_predicate(
        &self,
455
        ref_id: ast::NodeId,
456
        trait_ref: ty::PolyTraitRef<'tcx>,
457 458
        binding: &ConvertedBinding<'tcx>,
        speculative: bool)
459 460 461 462
        -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
    {
        let tcx = self.tcx();

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
        if !speculative {
            // Given something like `U : SomeTrait<T=X>`, we want to produce a
            // predicate like `<U as SomeTrait>::T = X`. This is somewhat
            // subtle in the event that `T` is defined in a supertrait of
            // `SomeTrait`, because in that case we need to upcast.
            //
            // That is, consider this case:
            //
            // ```
            // trait SubTrait : SuperTrait<int> { }
            // trait SuperTrait<A> { type T; }
            //
            // ... B : SubTrait<T=foo> ...
            // ```
            //
            // We want to produce `<B as SuperTrait<int>>::T == foo`.

            // Find any late-bound regions declared in `ty` that are not
            // declared in the trait-ref. These are not wellformed.
            //
            // Example:
            //
            //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
            //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
            let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
            let late_bound_in_ty =
                tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
            debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
            debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
            for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
                let br_name = match *br {
                    ty::BrNamed(_, name) => name,
                    _ => {
                        span_bug!(
                            binding.span,
                            "anonymous bound region {:?} in binding but not trait ref",
                            br);
                    }
                };
                struct_span_err!(tcx.sess,
                                binding.span,
                                E0582,
                                "binding for associated type `{}` references lifetime `{}`, \
                                which does not appear in the trait input types",
                                binding.item_name, br_name)
                    .emit();
            }
510 511
        }

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
                                                                    binding.item_name) {
            // Simple case: X is defined in the current trait.
            Ok(trait_ref)
        } else {
            // Otherwise, we have to walk through the supertraits to find
            // those that do.
            let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
                self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
            });
            self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
                                          binding.item_name, binding.span)
        }?;

        let (assoc_ident, def_scope) = tcx.adjust(binding.item_name, candidate.def_id(), ref_id);
        let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
            i.kind == ty::AssociatedKind::Type && i.name.to_ident() == assoc_ident
        }).expect("missing associated type");

        if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
            let msg = format!("associated type `{}` is private", binding.item_name);
            tcx.sess.span_err(binding.span, &msg);
534
        }
535
        tcx.check_stability(assoc_ty.def_id, ref_id, binding.span);
536

537 538
        Ok(candidate.map_bound(|trait_ref| {
            ty::ProjectionPredicate {
539 540 541 542 543
                projection_ty: ty::ProjectionTy::from_ref_and_name(
                    tcx,
                    trait_ref,
                    binding.item_name,
                ),
544 545
                ty: binding.ty,
            }
546
        }))
547 548
    }

549 550 551 552 553 554
    fn ast_path_to_ty(&self,
        span: Span,
        did: DefId,
        item_segment: &hir::PathSegment)
        -> Ty<'tcx>
    {
555
        let substs = self.ast_path_substs_for_ty(span, did, item_segment);
556 557
        self.normalize_ty(
            span,
558
            self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
559
        )
560 561
    }

562 563 564 565 566 567
    /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
    /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
    fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
                                -> ty::ExistentialTraitRef<'tcx> {
        assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
        ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
568
    }
569

570 571 572 573 574 575
    fn conv_object_ty_poly_trait_ref(&self,
        span: Span,
        trait_bounds: &[hir::PolyTraitRef],
        lifetime: &hir::Lifetime)
        -> Ty<'tcx>
    {
576
        let tcx = self.tcx();
577

578 579 580 581 582 583
        if trait_bounds.is_empty() {
            span_err!(tcx.sess, span, E0224,
                      "at least one non-builtin trait is required for an object type");
            return tcx.types.err;
        }

584 585
        let mut projection_bounds = vec![];
        let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
586
        let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
587 588 589
                                                        dummy_self,
                                                        &mut projection_bounds);

590 591 592 593 594 595 596
        for trait_bound in trait_bounds[1..].iter() {
            // Sanity check for non-principal trait bounds
            self.instantiate_poly_trait_ref(trait_bound,
                                            dummy_self,
                                            &mut vec![]);
        }

597
        let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
598

599 600 601 602
        if !trait_bounds.is_empty() {
            let b = &trait_bounds[0];
            let span = b.trait_ref.path.span;
            struct_span_err!(self.tcx().sess, span, E0225,
603 604
                "only auto traits can be used as additional traits in a trait object")
                .span_label(span, "non-auto additional trait")
605 606 607 608 609 610 611 612 613
                .emit();
        }

        // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
        let existential_principal = principal.map_bound(|trait_ref| {
            self.trait_ref_to_existential(trait_ref)
        });
        let existential_projections = projection_bounds.iter().map(|bound| {
            bound.map_bound(|b| {
614
                let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
615
                ty::ExistentialProjection {
616 617 618
                    ty: b.ty,
                    item_def_id: b.projection_ty.item_def_id,
                    substs: trait_ref.substs,
619 620
                }
            })
621
        });
622

623 624 625 626 627 628 629
        // check that there are no gross object safety violations,
        // most importantly, that the supertraits don't contain Self,
        // to avoid ICE-s.
        let object_safety_violations =
            tcx.astconv_object_safety_violations(principal.def_id());
        if !object_safety_violations.is_empty() {
            tcx.report_object_safety_error(
630 631
                span, principal.def_id(), object_safety_violations)
                .emit();
632 633
            return tcx.types.err;
        }
634

635
        let mut associated_types = FxHashSet::default();
636
        for tr in traits::supertraits(tcx, principal) {
637 638
            associated_types.extend(tcx.associated_items(tr.def_id())
                .filter(|item| item.kind == ty::AssociatedKind::Type)
639
                .map(|item| item.def_id));
640
        }
641

642
        for projection_bound in &projection_bounds {
643
            associated_types.remove(&projection_bound.0.projection_ty.item_def_id);
644 645
        }

646 647 648
        for item_def_id in associated_types {
            let assoc_item = tcx.associated_item(item_def_id);
            let trait_def_id = assoc_item.container.id();
649
            struct_span_err!(tcx.sess, span, E0191,
650
                "the value of the associated type `{}` (from the trait `{}`) must be specified",
651
                        assoc_item.name,
652
                        tcx.item_path_str(trait_def_id))
653
                        .span_label(span, format!(
654
                            "missing associated type `{}` value", assoc_item.name))
655
                        .emit();
656
        }
657

658 659 660 661 662 663 664 665 666 667
        let mut v =
            iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
            .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
            .chain(existential_projections
                   .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
            .collect::<AccumulateVec<[_; 8]>>();
        v.sort_by(|a, b| a.cmp(tcx, b));
        let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));


668 669 670 671 672
        // Explicitly specified region bound. Use that.
        let region_bound = if !lifetime.is_elided() {
            self.ast_region_to_region(lifetime, None)
        } else {
            self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
673 674
                let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
                if tcx.named_region(hir_id).is_some() {
675 676 677 678
                    self.ast_region_to_region(lifetime, None)
                } else {
                    self.re_infer(span, None).unwrap_or_else(|| {
                        span_err!(tcx.sess, span, E0228,
679 680
                                  "the lifetime bound for this object type cannot be deduced \
                                   from context; please supply an explicit bound");
681
                        tcx.types.re_static
682 683
                    })
                }
684
            })
685 686 687 688 689
        };

        debug!("region_bound: {:?}", region_bound);

        let ty = tcx.mk_dynamic(existential_predicates, region_bound);
690 691
        debug!("trait_object_type: {:?}", ty);
        ty
692 693
    }

694 695 696 697 698
    fn report_ambiguous_associated_type(&self,
                                        span: Span,
                                        type_str: &str,
                                        trait_str: &str,
                                        name: &str) {
K
Keith Yeung 已提交
699
        struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
700
            .span_label(span, "ambiguous associated type")
K
Keith Yeung 已提交
701 702 703 704
            .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
                  type_str, trait_str, name))
            .emit();

705
    }
706

707
    // Search for a bound on a type parameter which includes the associated item
708 709
    // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
    // This function will fail if there are no suitable bounds or there is
710 711
    // any ambiguity.
    fn find_bound_for_assoc_item(&self,
712
                                 ty_param_def_id: DefId,
713 714 715 716 717
                                 assoc_name: ast::Name,
                                 span: Span)
                                 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
    {
        let tcx = self.tcx();
718

719
        let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
720
            .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
721

722 723
        // Check that there is exactly one way to find an associated type with the
        // correct name.
724
        let suitable_bounds =
725
            traits::transitive_bounds(tcx, &bounds)
726
            .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
727

728 729
        let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
        let param_name = tcx.hir.ty_param_name(param_node_id);
730
        self.one_bound_for_assoc_type(suitable_bounds,
731
                                      &param_name.as_str(),
732
                                      assoc_name,
733
                                      span)
734
    }
735

736

737 738
    // Checks that bounds contains exactly one element and reports appropriate
    // errors otherwise.
739 740
    fn one_bound_for_assoc_type<I>(&self,
                                mut bounds: I,
741
                                ty_param_name: &str,
742
                                assoc_name: ast::Name,
743 744
                                span: Span)
        -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
745
        where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
746
    {
747 748 749 750 751 752 753
        let bound = match bounds.next() {
            Some(bound) => bound,
            None => {
                struct_span_err!(self.tcx().sess, span, E0220,
                          "associated type `{}` not found for `{}`",
                          assoc_name,
                          ty_param_name)
754
                  .span_label(span, format!("associated type `{}` not found", assoc_name))
755 756 757 758
                  .emit();
                return Err(ErrorReported);
            }
        };
M
Mikhail Modin 已提交
759

760 761
        if let Some(bound2) = bounds.next() {
            let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
762 763 764 765 766
            let mut err = struct_span_err!(
                self.tcx().sess, span, E0221,
                "ambiguous associated type `{}` in bounds of `{}`",
                assoc_name,
                ty_param_name);
767
            err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
768

769 770
            for bound in bounds {
                let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
771 772
                    item.kind == ty::AssociatedKind::Type &&
                    self.tcx().hygienic_eq(assoc_name, item.name, bound.def_id())
773
                })
774
                .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
775 776

                if let Some(span) = bound_span {
777
                    err.span_label(span, format!("ambiguous `{}` from `{}`",
M
Mikhail Modin 已提交
778
                                                  assoc_name,
779
                                                  bound));
M
Mikhail Modin 已提交
780 781 782 783
                } else {
                    span_note!(&mut err, span,
                               "associated type `{}` could derive from `{}`",
                               ty_param_name,
784
                               bound);
M
Mikhail Modin 已提交
785
                }
786 787
            }
            err.emit();
788 789
        }

790
        return Ok(bound);
791
    }
792

793 794 795 796 797 798
    // Create a type from a path to an associated type.
    // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
    // and item_segment is the path segment for D. We return a type and a def for
    // the whole path.
    // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
    // parameter or Self.
799
    pub fn associated_path_def_to_ty(&self,
800
                                     ref_id: ast::NodeId,
801 802 803 804 805
                                     span: Span,
                                     ty: Ty<'tcx>,
                                     ty_path_def: Def,
                                     item_segment: &hir::PathSegment)
                                     -> (Ty<'tcx>, Def)
806 807
    {
        let tcx = self.tcx();
V
Vadim Petrochenkov 已提交
808
        let assoc_name = item_segment.name;
809 810 811

        debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);

812
        self.prohibit_type_params(slice::from_ref(item_segment));
813 814 815 816

        // Find the type of the associated item, and the trait where the associated
        // item is declared.
        let bound = match (&ty.sty, ty_path_def) {
817
            (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
818 819
                // `Self` in an impl of a trait - we have a concrete self type and a
                // trait reference.
820 821 822 823 824 825
                let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
                    Some(trait_ref) => trait_ref,
                    None => {
                        // A cycle error occurred, most likely.
                        return (tcx.types.err, Def::Err);
                    }
826
                };
827

828
                let candidates =
829 830
                    traits::supertraits(tcx, ty::Binder(trait_ref))
                    .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
831
                                                                         assoc_name));
832

833
                match self.one_bound_for_assoc_type(candidates, "Self", assoc_name, span) {
834
                    Ok(bound) => bound,
835
                    Err(ErrorReported) => return (tcx.types.err, Def::Err),
836
                }
837
            }
838
            (&ty::TyParam(_), Def::SelfTy(Some(param_did), None)) |
839
            (&ty::TyParam(_), Def::TyParam(param_did)) => {
840
                match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
841
                    Ok(bound) => bound,
842
                    Err(ErrorReported) => return (tcx.types.err, Def::Err),
843
                }
844
            }
845
            _ => {
846 847 848 849 850 851 852
                // Don't print TyErr to the user.
                if !ty.references_error() {
                    self.report_ambiguous_associated_type(span,
                                                          &ty.to_string(),
                                                          "Trait",
                                                          &assoc_name.as_str());
                }
853
                return (tcx.types.err, Def::Err);
854
            }
855
        };
856

857
        let trait_did = bound.0.def_id;
858
        let (assoc_ident, def_scope) = tcx.adjust(assoc_name, trait_did, ref_id);
859 860 861 862 863
        let item = tcx.associated_items(trait_did).find(|i| {
            Namespace::from(i.kind) == Namespace::Type &&
            i.name.to_ident() == assoc_ident
        })
        .expect("missing associated type");
864 865 866 867

        let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
        let ty = self.normalize_ty(span, ty);

868
        let def = Def::AssociatedTy(item.def_id);
J
Jeffrey Seyfried 已提交
869
        if !item.vis.is_accessible_from(def_scope, tcx) {
870 871 872 873 874 875
            let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
            tcx.sess.span_err(span, &msg);
        }
        tcx.check_stability(item.def_id, ref_id, span);

        (ty, def)
876
    }
877

878 879 880
    fn qpath_to_ty(&self,
                   span: Span,
                   opt_self_ty: Option<Ty<'tcx>>,
881
                   item_def_id: DefId,
882 883 884 885 886
                   trait_segment: &hir::PathSegment,
                   item_segment: &hir::PathSegment)
                   -> Ty<'tcx>
    {
        let tcx = self.tcx();
887
        let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
888

889
        self.prohibit_type_params(slice::from_ref(item_segment));
890

891 892 893 894 895 896 897
        let self_ty = if let Some(ty) = opt_self_ty {
            ty
        } else {
            let path_str = tcx.item_path_str(trait_def_id);
            self.report_ambiguous_associated_type(span,
                                                  "Type",
                                                  &path_str,
V
Vadim Petrochenkov 已提交
898
                                                  &item_segment.name.as_str());
899 900
            return tcx.types.err;
        };
901

902
        debug!("qpath_to_ty: self_type={:?}", self_ty);
903

904
        let trait_ref = self.ast_path_to_mono_trait_ref(span,
905
                                                        trait_def_id,
906
                                                        self_ty,
907
                                                        trait_segment);
908

909
        debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
910

911
        self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
912
    }
913

914 915
    pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
        for segment in segments {
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
            segment.with_parameters(|parameters| {
                for typ in &parameters.types {
                    struct_span_err!(self.tcx().sess, typ.span, E0109,
                                     "type parameters are not allowed on this type")
                        .span_label(typ.span, "type parameter not allowed")
                        .emit();
                    break;
                }
                for lifetime in &parameters.lifetimes {
                    struct_span_err!(self.tcx().sess, lifetime.span, E0110,
                                     "lifetime parameters are not allowed on this type")
                        .span_label(lifetime.span,
                                    "lifetime parameter not allowed on this type")
                        .emit();
                    break;
                }
                for binding in &parameters.bindings {
                    self.prohibit_projection(binding.span);
                    break;
                }
            })
937 938 939 940 941 942
        }
    }

    pub fn prohibit_projection(&self, span: Span) {
        let mut err = struct_span_err!(self.tcx().sess, span, E0229,
                                       "associated type bindings are not allowed here");
C
Charlie Somerville 已提交
943
        err.span_label(span, "associated type not allowed here").emit();
944 945
    }

946
    // Check a type Path and convert it to a Ty.
947 948
    pub fn def_to_ty(&self,
                     opt_self_ty: Option<Ty<'tcx>>,
949
                     path: &hir::Path,
950 951
                     permit_variants: bool)
                     -> Ty<'tcx> {
952 953
        let tcx = self.tcx();

954
        debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
955
               path.def, opt_self_ty, path.segments);
956

957 958
        let span = path.span;
        match path.def {
P
Paul Lietar 已提交
959 960
            Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
            Def::Union(did) | Def::TyForeign(did) => {
961
                assert_eq!(opt_self_ty, None);
962
                self.prohibit_type_params(path.segments.split_last().unwrap().1);
963
                self.ast_path_to_ty(span, did, path.segments.last().unwrap())
964
            }
V
Vadim Petrochenkov 已提交
965 966 967
            Def::Variant(did) if permit_variants => {
                // Convert "variant type" as if it were a real type.
                // The resulting `Ty` is type of the variant's enum for now.
968
                assert_eq!(opt_self_ty, None);
969
                self.prohibit_type_params(path.segments.split_last().unwrap().1);
970
                self.ast_path_to_ty(span,
V
Vadim Petrochenkov 已提交
971
                                    tcx.parent_def_id(did).unwrap(),
972
                                    path.segments.last().unwrap())
V
Vadim Petrochenkov 已提交
973
            }
974
            Def::TyParam(did) => {
975
                assert_eq!(opt_self_ty, None);
976
                self.prohibit_type_params(&path.segments);
977

978
                let node_id = tcx.hir.as_local_node_id(did).unwrap();
979 980
                let item_id = tcx.hir.get_parent_node(node_id);
                let item_def_id = tcx.hir.local_def_id(item_id);
981
                let generics = tcx.generics_of(item_def_id);
982
                let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id)];
983
                tcx.mk_param(index, tcx.hir.name(node_id))
984
            }
985
            Def::SelfTy(_, Some(def_id)) => {
986
                // Self in impl (we know the concrete type).
987

988
                assert_eq!(opt_self_ty, None);
989
                self.prohibit_type_params(&path.segments);
990

991
                tcx.at(span).type_of(def_id)
992 993 994
            }
            Def::SelfTy(Some(_), None) => {
                // Self in trait.
995
                assert_eq!(opt_self_ty, None);
996
                self.prohibit_type_params(&path.segments);
997 998
                tcx.mk_self_type()
            }
999
            Def::AssociatedTy(def_id) => {
1000
                self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1001
                self.qpath_to_ty(span,
1002
                                 opt_self_ty,
1003
                                 def_id,
1004 1005
                                 &path.segments[path.segments.len()-2],
                                 path.segments.last().unwrap())
1006 1007
            }
            Def::PrimTy(prim_ty) => {
1008
                assert_eq!(opt_self_ty, None);
1009 1010 1011 1012 1013 1014 1015 1016 1017
                self.prohibit_type_params(&path.segments);
                match prim_ty {
                    hir::TyBool => tcx.types.bool,
                    hir::TyChar => tcx.types.char,
                    hir::TyInt(it) => tcx.mk_mach_int(it),
                    hir::TyUint(uit) => tcx.mk_mach_uint(uit),
                    hir::TyFloat(ft) => tcx.mk_mach_float(ft),
                    hir::TyStr => tcx.mk_str()
                }
1018 1019 1020 1021 1022
            }
            Def::Err => {
                self.set_tainted_by_errors();
                return self.tcx().types.err;
            }
1023
            _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1024
        }
1025
    }
1026

1027 1028
    /// Parses the programmer's textual representation of a type into our
    /// internal notion of a type.
1029
    pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1030 1031
        debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
               ast_ty.id, ast_ty);
1032

1033
        let tcx = self.tcx();
1034

1035
        let result_ty = match ast_ty.node {
1036
            hir::TySlice(ref ty) => {
1037
                tcx.mk_slice(self.ast_ty_to_ty(&ty))
1038
            }
1039 1040
            hir::TyPtr(ref mt) => {
                tcx.mk_ptr(ty::TypeAndMut {
1041
                    ty: self.ast_ty_to_ty(&mt.ty),
1042 1043 1044 1045
                    mutbl: mt.mutbl
                })
            }
            hir::TyRptr(ref region, ref mt) => {
1046
                let r = self.ast_region_to_region(region, None);
1047
                debug!("TyRef r={:?}", r);
1048
                let t = self.ast_ty_to_ty(&mt.ty);
1049
                tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1050
            }
A
Andrew Cann 已提交
1051 1052
            hir::TyNever => {
                tcx.types.never
1053
            },
1054
            hir::TyTup(ref fields) => {
A
Andrew Cann 已提交
1055
                tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1056 1057 1058
            }
            hir::TyBareFn(ref bf) => {
                require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1059
                tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1060
            }
1061
            hir::TyTraitObject(ref bounds, ref lifetime) => {
1062
                self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1063
            }
T
Taylor Cramer 已提交
1064
            hir::TyImplTraitExistential(_, ref lifetimes) => {
1065
                let def_id = tcx.hir.local_def_id(ast_ty.id);
T
Taylor Cramer 已提交
1066
                self.impl_trait_ty_to_ty(def_id, lifetimes)
1067
            }
1068
            hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1069
                debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1070
                let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1071
                    self.ast_ty_to_ty(qself)
1072
                });
1073
                self.def_to_ty(opt_self_ty, path, false)
1074 1075 1076
            }
            hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
                debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1077
                let ty = self.ast_ty_to_ty(qself);
1078

1079 1080 1081 1082 1083
                let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
                    path.def
                } else {
                    Def::Err
                };
1084
                self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1085
            }
1086
            hir::TyArray(ref ty, length) => {
1087 1088 1089 1090 1091 1092 1093 1094
                let length_def_id = tcx.hir.body_owner_def_id(length);
                let substs = Substs::identity_for_item(tcx, length_def_id);
                let length = tcx.mk_const(ty::Const {
                    val: ConstVal::Unevaluated(length_def_id, substs),
                    ty: tcx.types.usize
                });
                let array_ty = tcx.mk_ty(ty::TyArray(self.ast_ty_to_ty(&ty), length));
                self.normalize_ty(ast_ty.span, array_ty)
1095
            }
1096
            hir::TyTypeof(ref _e) => {
G
Gavin Baker 已提交
1097 1098
                struct_span_err!(tcx.sess, ast_ty.span, E0516,
                                 "`typeof` is a reserved keyword but unimplemented")
1099
                    .span_label(ast_ty.span, "reserved keyword")
G
Gavin Baker 已提交
1100 1101
                    .emit();

1102 1103 1104 1105 1106 1107 1108
                tcx.types.err
            }
            hir::TyInfer => {
                // TyInfer also appears as the type of arguments or return
                // values in a ExprClosure, or as
                // the type of local variables. Both of these cases are
                // handled specially and will not descend into this routine.
1109
                self.ty_infer(ast_ty.span)
1110
            }
1111 1112 1113
            hir::TyErr => {
                tcx.types.err
            }
1114 1115
        };

1116
        self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1117
        result_ty
1118
    }
1119

T
Taylor Cramer 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    pub fn impl_trait_ty_to_ty(&self, def_id: DefId, lifetimes: &[hir::Lifetime]) -> Ty<'tcx> {
        debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
        let tcx = self.tcx();
        let generics = tcx.generics_of(def_id);

        // Fill in the substs of the parent generics
        debug!("impl_trait_ty_to_ty: generics={:?}", generics);
        let mut substs = Vec::with_capacity(generics.count());
        if let Some(parent_id) = generics.parent {
            let parent_generics = tcx.generics_of(parent_id);
            Substs::fill_item(
                &mut substs, tcx, parent_generics,
                &mut |def, _| tcx.mk_region(
                    ty::ReEarlyBound(def.to_early_bound_region_data())),
                &mut |def, _| tcx.mk_param_from_def(def)
            );

            // Replace all lifetimes with 'static
            for subst in &mut substs {
                if let Some(_) = subst.as_region() {
                    *subst = Kind::from(&RegionKind::ReStatic);
                }
            }
            debug!("impl_trait_ty_to_ty: substs from parent = {:?}", substs);
        }
        assert_eq!(substs.len(), generics.parent_count());

        // Fill in our own generics with the resolved lifetimes
        assert_eq!(lifetimes.len(), generics.own_count());
        substs.extend(lifetimes.iter().map(|lt|
            Kind::from(self.ast_region_to_region(lt, None))));

        debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);

        tcx.mk_anon(def_id, tcx.intern_substs(&substs))
    }

1157
    pub fn ty_of_arg(&self,
1158
                     ty: &hir::Ty,
1159 1160 1161
                     expected_ty: Option<Ty<'tcx>>)
                     -> Ty<'tcx>
    {
1162
        match ty.node {
1163 1164 1165 1166
            hir::TyInfer if expected_ty.is_some() => {
                self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
                expected_ty.unwrap()
            }
1167
            _ => self.ast_ty_to_ty(ty),
1168
        }
1169
    }
1170

1171 1172 1173
    pub fn ty_of_fn(&self,
                    unsafety: hir::Unsafety,
                    abi: abi::Abi,
1174
                    decl: &hir::FnDecl)
1175
                    -> ty::PolyFnSig<'tcx> {
1176
        debug!("ty_of_fn");
1177

1178
        let tcx = self.tcx();
1179
        let input_tys: Vec<Ty> =
1180
            decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1181

1182
        let output_ty = match decl.output {
1183
            hir::Return(ref output) => self.ast_ty_to_ty(output),
1184
            hir::DefaultReturn(..) => tcx.mk_nil(),
1185
        };
1186

1187
        debug!("ty_of_fn: output_ty={:?}", output_ty);
1188

1189
        let bare_fn_ty = ty::Binder(tcx.mk_fn_sig(
1190 1191 1192 1193 1194
            input_tys.into_iter(),
            output_ty,
            decl.variadic,
            unsafety,
            abi
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        ));

        // Find any late-bound regions declared in return type that do
        // not appear in the arguments. These are not wellformed.
        //
        // Example:
        //     for<'a> fn() -> &'a str <-- 'a is bad
        //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
        let inputs = bare_fn_ty.inputs();
        let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
            &inputs.map_bound(|i| i.to_owned()));
        let output = bare_fn_ty.output();
        let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
        for br in late_bound_in_ret.difference(&late_bound_in_args) {
1209 1210 1211
            let lifetime_name = match *br {
                ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
                ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => format!("an anonymous lifetime"),
1212
            };
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
            let mut err = struct_span_err!(tcx.sess,
                                           decl.output.span(),
                                           E0581,
                                           "return type references {} \
                                            which is not constrained by the fn input types",
                                           lifetime_name);
            if let ty::BrAnon(_) = *br {
                // The only way for an anonymous lifetime to wind up
                // in the return type but **also** be unconstrained is
                // if it only appears in "associated types" in the
                // input. See #47511 for an example. In this case,
                // though we can easily give a hint that ought to be
                // relevant.
                err.note("lifetimes appearing in an associated type \
                          are not considered constrained");
            }
            err.emit();
1230 1231 1232
        }

        bare_fn_ty
1233
    }
1234

1235 1236 1237 1238 1239 1240 1241
    /// Given the bounds on an object, determines what single region bound (if any) we can
    /// use to summarize this type. The basic idea is that we will use the bound the user
    /// provided, if they provided one, and otherwise search the supertypes of trait bounds
    /// for region bounds. It may be that we can derive no bound at all, in which case
    /// we return `None`.
    fn compute_object_lifetime_bound(&self,
        span: Span,
1242
        existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
N
Niko Matsakis 已提交
1243
        -> Option<ty::Region<'tcx>> // if None, use the default
1244 1245
    {
        let tcx = self.tcx();
1246

1247
        debug!("compute_opt_region_bound(existential_predicates={:?})",
1248
               existential_predicates);
1249

1250 1251 1252
        // No explicit region bound specified. Therefore, examine trait
        // bounds and see if we can derive region bounds from those.
        let derived_region_bounds =
1253
            object_region_bounds(tcx, existential_predicates);
1254

1255 1256 1257 1258 1259
        // If there are no derived region bounds, then report back that we
        // can find no region bound. The caller will use the default.
        if derived_region_bounds.is_empty() {
            return None;
        }
1260

1261 1262
        // If any of the derived region bounds are 'static, that is always
        // the best choice.
1263
        if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1264
            return Some(tcx.types.re_static);
1265
        }
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275
        // Determine whether there is exactly one unique region in the set
        // of derived region bounds. If so, use that. Otherwise, report an
        // error.
        let r = derived_region_bounds[0];
        if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
            span_err!(tcx.sess, span, E0227,
                      "ambiguous lifetime bound, explicit lifetime bound required");
        }
        return Some(r);
1276
    }
1277
}
1278

1279 1280 1281
/// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
/// remaining general trait bounds.
fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1282
                                         trait_bounds: &'b [hir::PolyTraitRef])
1283 1284
    -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
{
1285
    let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1286
        // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1287
        match bound.trait_ref.path.def {
1288 1289
            Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
                true
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
            }
            _ => false
        }
    });

    let auto_traits = auto_traits.into_iter().map(|tr| {
        if let Def::Trait(trait_did) = tr.trait_ref.path.def {
            trait_did
        } else {
            unreachable!()
        }
    }).collect::<Vec<_>>();

    (auto_traits, trait_bounds)
}

1306
fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1307 1308
                             ty_param_defs: &[ty::TypeParameterDef]) {
    let accepted = ty_param_defs.len();
1309
    let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1310 1311 1312 1313 1314 1315
    if supplied < required {
        let expected = if required < accepted {
            "expected at least"
        } else {
            "expected"
        };
1316
        let arguments_plural = if required == 1 { "" } else { "s" };
1317 1318 1319 1320 1321

        struct_span_err!(tcx.sess, span, E0243,
                "wrong number of type arguments: {} {}, found {}",
                expected, required, supplied)
            .span_label(span,
1322
                format!("{} {} type argument{}",
1323 1324 1325
                    expected,
                    required,
                    arguments_plural))
1326
            .emit();
1327
    } else if supplied > accepted {
1328
        let expected = if required < accepted {
1329
            format!("expected at most {}", accepted)
1330
        } else {
1331
            format!("expected {}", accepted)
1332
        };
1333
        let arguments_plural = if accepted == 1 { "" } else { "s" };
1334

1335 1336 1337
        struct_span_err!(tcx.sess, span, E0244,
                "wrong number of type arguments: {}, found {}",
                expected, supplied)
1338 1339
            .span_label(
                span,
1340
                format!("{} type argument{}",
1341 1342
                    if accepted == 0 { "expected no" } else { &expected },
                    arguments_plural)
1343 1344
            )
            .emit();
1345 1346 1347
    }
}

1348
fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
O
Omer Sheikh 已提交
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    let label = if number < expected {
        if expected == 1 {
            format!("expected {} lifetime parameter", expected)
        } else {
            format!("expected {} lifetime parameters", expected)
        }
    } else {
        let additional = number - expected;
        if additional == 1 {
            "unexpected lifetime parameter".to_string()
        } else {
            format!("{} unexpected lifetime parameters", additional)
        }
    };
    struct_span_err!(tcx.sess, span, E0107,
                     "wrong number of lifetime parameters: expected {}, found {}",
                     expected, number)
1366
        .span_label(span, label)
O
Omer Sheikh 已提交
1367
        .emit();
1368
}
1369 1370 1371 1372 1373

// A helper struct for conveniently grouping a set of bounds which we pass to
// and return from functions in multiple places.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Bounds<'tcx> {
N
Niko Matsakis 已提交
1374
    pub region_bounds: Vec<ty::Region<'tcx>>,
1375
    pub implicitly_sized: bool,
1376 1377 1378 1379
    pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
    pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
}

1380
impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1381 1382 1383 1384
    pub fn predicates(&self,
                      tcx: TyCtxt<'a, 'gcx, 'tcx>,
                      param_ty: Ty<'tcx>,
                      default_impl_check: ty::DefaultImplCheck)
1385
                      -> Vec<ty::Predicate<'tcx>>
1386 1387 1388
    {
        let mut vec = Vec::new();

1389 1390
        // If it could be sized, and is, add the sized predicate
        if self.implicitly_sized {
1391
            if let Some(sized) = tcx.lang_items().sized_trait() {
1392 1393 1394 1395 1396 1397
                let trait_ref = ty::TraitRef {
                    def_id: sized,
                    substs: tcx.mk_substs_trait(param_ty, &[])
                };
                vec.push(trait_ref.to_predicate());
            }
1398 1399 1400 1401 1402
        }

        for &region_bound in &self.region_bounds {
            // account for the binder being introduced below; no need to shift `param_ty`
            // because, at present at least, it can only refer to early-bound regions
1403
            let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1404
            vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1405 1406 1407
        }

        for bound_trait_ref in &self.trait_bounds {
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
            vec.push(
                if bound_trait_ref.skip_binder().def_id !=
                   tcx.lang_items().sized_trait().unwrap() {
                    bound_trait_ref.to_predicate()
                                   .change_default_impl_check(default_impl_check)
                                   .unwrap_or(bound_trait_ref.to_predicate())
                } else {
                    bound_trait_ref.to_predicate()
                }
            );
1418 1419 1420
        }

        for projection in &self.projection_bounds {
1421
            vec.push(projection.to_predicate());
1422 1423 1424 1425 1426
        }

        vec
    }
}