1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Conversion from AST representation of types to the ty.rs
12 //! representation. The main routine here is `ast_ty_to_ty()`: each use
13 //! is parameterized by an instance of `AstConv`.
15 //! The parameterization of `ast_ty_to_ty()` is because it behaves
16 //! somewhat differently during the collect and check phases,
17 //! particularly with respect to looking up the types of top-level
18 //! items. In the collect phase, the crate context is used as the
19 //! `AstConv` instance; in this phase, the `get_item_type()`
20 //! function triggers a recursive call to `type_of_item()`
21 //! (note that `ast_ty_to_ty()` will detect recursive types and report
22 //! an error). In the check phase, when the FnCtxt is used as the
23 //! `AstConv`, `get_item_type()` just looks up the item type in
24 //! `tcx.types` (using `TyCtxt::item_type`).
26 use rustc_const_eval::eval_length;
27 use rustc_data_structures::accumulate_vec::AccumulateVec;
30 use hir::def_id::DefId;
31 use middle::resolve_lifetime as rl;
33 use rustc::ty::subst::{Kind, Subst, Substs};
35 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
36 use rustc::ty::wf::object_region_bounds;
37 use rustc_back::slice;
38 use require_c_abi_if_variadic;
39 use util::common::{ErrorReported, FN_OUTPUT_NAME};
40 use util::nodemap::{NodeMap, FxHashSet};
42 use std::cell::RefCell;
44 use syntax::{abi, ast};
45 use syntax::feature_gate::{GateIssue, emit_feature_err};
46 use syntax::symbol::{Symbol, keywords};
49 pub trait AstConv<'gcx, 'tcx> {
50 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
52 /// A cache used for the result of `ast_ty_to_ty_cache`
53 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
55 /// Returns the generic type and lifetime parameters for an item.
56 fn get_generics(&self, span: Span, id: DefId)
57 -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
59 /// Identify the type for an item, like a type alias, fn, or struct.
60 fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported>;
62 /// Returns the `TraitDef` for a given trait. This allows you to
63 /// figure out the set of type parameters defined on the trait.
64 fn get_trait_def(&self, span: Span, id: DefId)
65 -> Result<&'tcx ty::TraitDef, ErrorReported>;
67 /// Ensure that the super-predicates for the trait with the given
68 /// id are available and also for the transitive set of
70 fn ensure_super_predicates(&self, span: Span, id: DefId)
71 -> Result<(), ErrorReported>;
73 /// Returns the set of bounds in scope for the type parameter with
75 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
76 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
78 /// Return an (optional) substitution to convert bound type parameters that
79 /// are in scope into free ones. This function should only return Some
81 /// See ParameterEnvironment::free_substs for more information.
82 fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
84 /// What lifetime should we use when a lifetime is omitted (and not elided)?
85 fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
86 -> Option<&'tcx ty::Region>;
88 /// What type should we use when a type is omitted?
89 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
91 /// Same as ty_infer, but with a known type parameter definition.
92 fn ty_infer_for_def(&self,
93 _def: &ty::TypeParameterDef<'tcx>,
94 _substs: &[Kind<'tcx>],
95 span: Span) -> Ty<'tcx> {
99 /// Projecting an associated type from a (potentially)
100 /// higher-ranked trait reference is more complicated, because of
101 /// the possibility of late-bound regions appearing in the
102 /// associated type binding. This is not legal in function
103 /// signatures for that reason. In a function body, we can always
104 /// handle it because we can use inference variables to remove the
105 /// late-bound regions.
106 fn projected_ty_from_poly_trait_ref(&self,
108 poly_trait_ref: ty::PolyTraitRef<'tcx>,
109 item_name: ast::Name)
112 /// Project an associated type from a non-higher-ranked trait reference.
113 /// This is fairly straightforward and can be accommodated in any context.
114 fn projected_ty(&self,
116 _trait_ref: ty::TraitRef<'tcx>,
117 _item_name: ast::Name)
120 /// Invoked when we encounter an error from some prior pass
121 /// (e.g. resolve) that is translated into a ty-error. This is
122 /// used to help suppress derived errors typeck might otherwise
124 fn set_tainted_by_errors(&self);
127 struct ConvertedBinding<'tcx> {
128 item_name: ast::Name,
133 /// Dummy type used for the `Self` of a `TraitRef` created for converting
134 /// a trait object, and which gets removed in `ExistentialTraitRef`.
135 /// This type must not appear anywhere in other converted types.
136 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
138 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
139 pub fn ast_region_to_region(&self,
140 lifetime: &hir::Lifetime,
141 def: Option<&ty::RegionParameterDef>)
144 let tcx = self.tcx();
145 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
146 Some(&rl::Region::Static) => {
147 tcx.mk_region(ty::ReStatic)
150 Some(&rl::Region::LateBound(debruijn, id)) => {
151 // If this region is declared on a function, it will have
152 // an entry in `late_bound`, but if it comes from
153 // `for<'a>` in some type or something, it won't
154 // necessarily have one. In that case though, we won't be
155 // changed from late to early bound, so we can just
157 let issue_32330 = tcx.named_region_map
161 .unwrap_or(ty::Issue32330::WontChange);
162 let name = tcx.hir.name(id);
163 tcx.mk_region(ty::ReLateBound(debruijn,
164 ty::BrNamed(tcx.hir.local_def_id(id), name, issue_32330)))
167 Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
168 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
171 Some(&rl::Region::EarlyBound(index, id)) => {
172 let name = tcx.hir.name(id);
173 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
179 Some(&rl::Region::Free(scope, id)) => {
180 // As in Region::LateBound above, could be missing for some late-bound
181 // regions, but also for early-bound regions.
182 let issue_32330 = tcx.named_region_map
186 .unwrap_or(ty::Issue32330::WontChange);
187 let name = tcx.hir.name(id);
188 tcx.mk_region(ty::ReFree(ty::FreeRegion {
189 scope: scope.to_code_extent(&tcx.region_maps),
190 bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name, issue_32330)
193 // (*) -- not late-bound, won't change
197 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
201 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
208 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
209 /// returns an appropriate set of substitutions for this particular reference to `I`.
210 pub fn ast_path_substs_for_ty(&self,
213 item_segment: &hir::PathSegment)
214 -> &'tcx Substs<'tcx>
216 let tcx = self.tcx();
218 match item_segment.parameters {
219 hir::AngleBracketedParameters(_) => {}
220 hir::ParenthesizedParameters(..) => {
221 struct_span_err!(tcx.sess, span, E0214,
222 "parenthesized parameters may only be used with a trait")
223 .span_label(span, &format!("only traits may use parentheses"))
226 return Substs::for_item(tcx, def_id, |_, _| {
227 tcx.mk_region(ty::ReStatic)
234 let (substs, assoc_bindings) =
235 self.create_substs_for_ast_path(span,
237 &item_segment.parameters,
240 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
245 /// Given the type/region arguments provided to some path (along with
246 /// an implicit Self, if this is a trait reference) returns the complete
247 /// set of substitutions. This may involve applying defaulted type parameters.
249 /// Note that the type listing given here is *exactly* what the user provided.
250 fn create_substs_for_ast_path(&self,
253 parameters: &hir::PathParameters,
254 self_ty: Option<Ty<'tcx>>)
255 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
257 let tcx = self.tcx();
259 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
261 def_id, self_ty, parameters);
263 let (lifetimes, num_types_provided, infer_types) = match *parameters {
264 hir::AngleBracketedParameters(ref data) => {
265 (&data.lifetimes[..], data.types.len(), data.infer_types)
267 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
270 // If the type is parameterized by this region, then replace this
271 // region with the current anon region binding (in other words,
272 // whatever & would get replaced with).
273 let decl_generics = match self.get_generics(span, def_id) {
274 Ok(generics) => generics,
275 Err(ErrorReported) => {
276 // No convenient way to recover from a cycle here. Just bail. Sorry!
277 self.tcx().sess.abort_if_errors();
278 bug!("ErrorReported returned, but no errors reports?")
281 let expected_num_region_params = decl_generics.regions.len();
282 let supplied_num_region_params = lifetimes.len();
283 if expected_num_region_params != supplied_num_region_params {
284 report_lifetime_number_error(tcx, span,
285 supplied_num_region_params,
286 expected_num_region_params);
289 // If a self-type was declared, one should be provided.
290 assert_eq!(decl_generics.has_self, self_ty.is_some());
292 // Check the number of type parameters supplied by the user.
293 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
294 if !infer_types || num_types_provided > ty_param_defs.len() {
295 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
298 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
299 let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
300 if let Some(ref default) = p.default {
301 if is_object && default.has_self_ty() {
302 // There is no suitable inference default for a type parameter
303 // that references self, in an object type.
311 let mut output_assoc_binding = None;
312 let substs = Substs::for_item(tcx, def_id, |def, _| {
313 let i = def.index as usize - self_ty.is_some() as usize;
314 if let Some(lifetime) = lifetimes.get(i) {
315 self.ast_region_to_region(lifetime, Some(def))
317 tcx.mk_region(ty::ReStatic)
320 let i = def.index as usize;
322 // Handle Self first, so we can adjust the index to match the AST.
323 if let (0, Some(ty)) = (i, self_ty) {
327 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
328 if i < num_types_provided {
329 // A provided type parameter.
331 hir::AngleBracketedParameters(ref data) => {
332 self.ast_ty_to_ty(&data.types[i])
334 hir::ParenthesizedParameters(ref data) => {
336 let (ty, assoc) = self.convert_parenthesized_parameters(data);
337 output_assoc_binding = Some(assoc);
341 } else if infer_types {
342 // No type parameters were provided, we can infer all.
343 let ty_var = if !default_needs_object_self(def) {
344 self.ty_infer_for_def(def, substs, span)
349 } else if let Some(default) = def.default {
350 // No type parameter provided, but a default exists.
352 // If we are converting an object type, then the
353 // `Self` parameter is unknown. However, some of the
354 // other type parameters may reference `Self` in their
355 // defaults. This will lead to an ICE if we are not
357 if default_needs_object_self(def) {
358 struct_span_err!(tcx.sess, span, E0393,
359 "the type parameter `{}` must be explicitly specified",
361 .span_label(span, &format!("missing reference to `{}`", def.name))
362 .note(&format!("because of the default `Self` reference, \
363 type parameters must be specified on object types"))
367 // This is a default type parameter.
368 default.subst_spanned(tcx, substs, Some(span))
371 // We've already errored above about the mismatch.
376 let assoc_bindings = match *parameters {
377 hir::AngleBracketedParameters(ref data) => {
378 data.bindings.iter().map(|b| {
381 ty: self.ast_ty_to_ty(&b.ty),
386 hir::ParenthesizedParameters(ref data) => {
387 vec![output_assoc_binding.unwrap_or_else(|| {
388 // This is an error condition, but we should
389 // get the associated type binding anyway.
390 self.convert_parenthesized_parameters(data).1
395 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
396 decl_generics, self_ty, substs);
398 (substs, assoc_bindings)
401 fn convert_parenthesized_parameters(&self,
402 data: &hir::ParenthesizedParameterData)
403 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
405 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
406 self.ast_ty_to_ty(a_t)
409 let (output, output_span) = match data.output {
410 Some(ref output_ty) => {
411 (self.ast_ty_to_ty(output_ty), output_ty.span)
414 (self.tcx().mk_nil(), data.span)
418 let output_binding = ConvertedBinding {
419 item_name: Symbol::intern(FN_OUTPUT_NAME),
424 (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
427 /// Instantiates the path for the given trait reference, assuming that it's
428 /// bound to a valid trait type. Returns the def_id for the defining trait.
429 /// Fails if the type is a type other than a trait type.
431 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
432 /// are disallowed. Otherwise, they are pushed onto the vector given.
433 pub fn instantiate_mono_trait_ref(&self,
434 trait_ref: &hir::TraitRef,
436 -> ty::TraitRef<'tcx>
438 let trait_def_id = self.trait_def_id(trait_ref);
439 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
442 trait_ref.path.segments.last().unwrap())
445 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
446 let path = &trait_ref.path;
448 Def::Trait(trait_def_id) => trait_def_id,
450 self.tcx().sess.fatal("cannot continue compilation due to previous error");
453 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
454 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
459 pub fn instantiate_poly_trait_ref(&self,
460 ast_trait_ref: &hir::PolyTraitRef,
462 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
463 -> ty::PolyTraitRef<'tcx>
465 let trait_ref = &ast_trait_ref.trait_ref;
466 let trait_def_id = self.trait_def_id(trait_ref);
468 debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
470 let (substs, assoc_bindings) =
471 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
474 trait_ref.path.segments.last().unwrap());
475 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
477 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
478 // specify type to assert that error was already reported in Err case:
479 let predicate: Result<_, ErrorReported> =
480 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
483 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
486 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
487 trait_ref, poly_projections, poly_trait_ref);
491 fn ast_path_to_mono_trait_ref(&self,
495 trait_segment: &hir::PathSegment)
496 -> ty::TraitRef<'tcx>
498 let (substs, assoc_bindings) =
499 self.create_substs_for_ast_trait_ref(span,
503 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
504 ty::TraitRef::new(trait_def_id, substs)
507 fn create_substs_for_ast_trait_ref(&self,
511 trait_segment: &hir::PathSegment)
512 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
514 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
517 let trait_def = match self.get_trait_def(span, trait_def_id) {
518 Ok(trait_def) => trait_def,
519 Err(ErrorReported) => {
520 // No convenient way to recover from a cycle here. Just bail. Sorry!
521 self.tcx().sess.abort_if_errors();
522 bug!("ErrorReported returned, but no errors reports?")
526 match trait_segment.parameters {
527 hir::AngleBracketedParameters(_) => {
528 // For now, require that parenthetical notation be used
529 // only with `Fn()` etc.
530 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
531 emit_feature_err(&self.tcx().sess.parse_sess,
532 "unboxed_closures", span, GateIssue::Language,
534 the precise format of `Fn`-family traits' \
535 type parameters is subject to change. \
536 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
539 hir::ParenthesizedParameters(_) => {
540 // For now, require that parenthetical notation be used
541 // only with `Fn()` etc.
542 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
543 emit_feature_err(&self.tcx().sess.parse_sess,
544 "unboxed_closures", span, GateIssue::Language,
546 parenthetical notation is only stable when used with `Fn`-family traits");
551 self.create_substs_for_ast_path(span,
553 &trait_segment.parameters,
557 fn trait_defines_associated_type_named(&self,
559 assoc_name: ast::Name)
562 self.tcx().associated_items(trait_def_id).any(|item| {
563 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
567 fn ast_type_binding_to_poly_projection_predicate(
569 path_id: ast::NodeId,
570 trait_ref: ty::PolyTraitRef<'tcx>,
571 binding: &ConvertedBinding<'tcx>)
572 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
574 let tcx = self.tcx();
576 // Given something like `U : SomeTrait<T=X>`, we want to produce a
577 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
578 // subtle in the event that `T` is defined in a supertrait of
579 // `SomeTrait`, because in that case we need to upcast.
581 // That is, consider this case:
584 // trait SubTrait : SuperTrait<int> { }
585 // trait SuperTrait<A> { type T; }
587 // ... B : SubTrait<T=foo> ...
590 // We want to produce `<B as SuperTrait<int>>::T == foo`.
592 // Find any late-bound regions declared in `ty` that are not
593 // declared in the trait-ref. These are not wellformed.
597 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
598 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
599 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
600 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
601 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
602 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
603 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
604 let br_name = match *br {
605 ty::BrNamed(_, name, _) => name,
609 "anonymous bound region {:?} in binding but not trait ref",
614 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
617 format!("binding for associated type `{}` references lifetime `{}`, \
618 which does not appear in the trait input types",
619 binding.item_name, br_name));
622 // Simple case: X is defined in the current trait.
623 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
624 return Ok(trait_ref.map_bound(|trait_ref| {
625 ty::ProjectionPredicate {
626 projection_ty: ty::ProjectionTy {
627 trait_ref: trait_ref,
628 item_name: binding.item_name,
635 // Otherwise, we have to walk through the supertraits to find
637 self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
640 traits::supertraits(tcx, trait_ref.clone())
641 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
643 let candidate = self.one_bound_for_assoc_type(candidates,
644 &trait_ref.to_string(),
645 &binding.item_name.as_str(),
648 Ok(candidate.map_bound(|trait_ref| {
649 ty::ProjectionPredicate {
650 projection_ty: ty::ProjectionTy {
651 trait_ref: trait_ref,
652 item_name: binding.item_name,
659 fn ast_path_to_ty(&self,
662 item_segment: &hir::PathSegment)
665 let tcx = self.tcx();
666 let decl_ty = match self.get_item_type(span, did) {
668 Err(ErrorReported) => {
669 return tcx.types.err;
673 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
674 decl_ty.subst(self.tcx(), substs)
677 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
678 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
679 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
680 -> ty::ExistentialTraitRef<'tcx> {
681 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
682 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
685 fn conv_object_ty_poly_trait_ref(&self,
687 trait_bounds: &[hir::PolyTraitRef],
688 lifetime: &hir::Lifetime)
691 let tcx = self.tcx();
693 if trait_bounds.is_empty() {
694 span_err!(tcx.sess, span, E0224,
695 "at least one non-builtin trait is required for an object type");
696 return tcx.types.err;
699 let mut projection_bounds = vec![];
700 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
701 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
703 &mut projection_bounds);
705 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
707 if !trait_bounds.is_empty() {
708 let b = &trait_bounds[0];
709 let span = b.trait_ref.path.span;
710 struct_span_err!(self.tcx().sess, span, E0225,
711 "only Send/Sync traits can be used as additional traits in a trait object")
712 .span_label(span, &format!("non-Send/Sync additional trait"))
716 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
717 let existential_principal = principal.map_bound(|trait_ref| {
718 self.trait_ref_to_existential(trait_ref)
720 let existential_projections = projection_bounds.iter().map(|bound| {
721 bound.map_bound(|b| {
722 let p = b.projection_ty;
723 ty::ExistentialProjection {
724 trait_ref: self.trait_ref_to_existential(p.trait_ref),
725 item_name: p.item_name,
731 // ensure the super predicates and stop if we encountered an error
732 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
733 return tcx.types.err;
736 // check that there are no gross object safety violations,
737 // most importantly, that the supertraits don't contain Self,
739 let object_safety_violations =
740 tcx.astconv_object_safety_violations(principal.def_id());
741 if !object_safety_violations.is_empty() {
742 tcx.report_object_safety_error(
743 span, principal.def_id(), object_safety_violations)
745 return tcx.types.err;
748 let mut associated_types = FxHashSet::default();
749 for tr in traits::supertraits(tcx, principal) {
750 associated_types.extend(tcx.associated_items(tr.def_id())
751 .filter(|item| item.kind == ty::AssociatedKind::Type)
752 .map(|item| (tr.def_id(), item.name)));
755 for projection_bound in &projection_bounds {
756 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
757 projection_bound.0.projection_ty.item_name);
758 associated_types.remove(&pair);
761 for (trait_def_id, name) in associated_types {
762 struct_span_err!(tcx.sess, span, E0191,
763 "the value of the associated type `{}` (from the trait `{}`) must be specified",
765 tcx.item_path_str(trait_def_id))
766 .span_label(span, &format!(
767 "missing associated type `{}` value", name))
772 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
773 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
774 .chain(existential_projections
775 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
776 .collect::<AccumulateVec<[_; 8]>>();
777 v.sort_by(|a, b| a.cmp(tcx, b));
778 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
781 // Explicitly specified region bound. Use that.
782 let region_bound = if !lifetime.is_elided() {
783 self.ast_region_to_region(lifetime, None)
785 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
786 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
787 self.ast_region_to_region(lifetime, None)
789 self.re_infer(span, None).unwrap_or_else(|| {
790 span_err!(tcx.sess, span, E0228,
791 "the lifetime bound for this object type cannot be deduced \
792 from context; please supply an explicit bound");
793 tcx.mk_region(ty::ReStatic)
799 debug!("region_bound: {:?}", region_bound);
801 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
802 debug!("trait_object_type: {:?}", ty);
806 fn report_ambiguous_associated_type(&self,
811 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
812 .span_label(span, &format!("ambiguous associated type"))
813 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
814 type_str, trait_str, name))
819 // Search for a bound on a type parameter which includes the associated item
820 // given by assoc_name. ty_param_node_id is the node id for the type parameter
821 // (which might be `Self`, but only if it is the `Self` of a trait, not an
822 // impl). This function will fail if there are no suitable bounds or there is
824 fn find_bound_for_assoc_item(&self,
825 ty_param_node_id: ast::NodeId,
826 ty_param_name: ast::Name,
827 assoc_name: ast::Name,
829 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
831 let tcx = self.tcx();
833 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
835 Err(ErrorReported) => {
836 return Err(ErrorReported);
840 // Ensure the super predicates and stop if we encountered an error.
841 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
842 return Err(ErrorReported);
845 // Check that there is exactly one way to find an associated type with the
847 let suitable_bounds =
848 traits::transitive_bounds(tcx, &bounds)
849 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
851 self.one_bound_for_assoc_type(suitable_bounds,
852 &ty_param_name.as_str(),
853 &assoc_name.as_str(),
858 // Checks that bounds contains exactly one element and reports appropriate
860 fn one_bound_for_assoc_type<I>(&self,
865 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
866 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
868 let bound = match bounds.next() {
869 Some(bound) => bound,
871 struct_span_err!(self.tcx().sess, span, E0220,
872 "associated type `{}` not found for `{}`",
875 .span_label(span, &format!("associated type `{}` not found", assoc_name))
877 return Err(ErrorReported);
881 if let Some(bound2) = bounds.next() {
882 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
883 let mut err = struct_span_err!(
884 self.tcx().sess, span, E0221,
885 "ambiguous associated type `{}` in bounds of `{}`",
888 err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
890 for bound in bounds {
891 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
892 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
894 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
896 if let Some(span) = bound_span {
897 err.span_label(span, &format!("ambiguous `{}` from `{}`",
901 span_note!(&mut err, span,
902 "associated type `{}` could derive from `{}`",
913 // Create a type from a path to an associated type.
914 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
915 // and item_segment is the path segment for D. We return a type and a def for
917 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
918 // parameter or Self.
919 pub fn associated_path_def_to_ty(&self,
924 item_segment: &hir::PathSegment)
927 let tcx = self.tcx();
928 let assoc_name = item_segment.name;
930 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
932 tcx.prohibit_type_params(slice::ref_slice(item_segment));
934 // Find the type of the associated item, and the trait where the associated
936 let bound = match (&ty.sty, ty_path_def) {
937 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
938 // `Self` in an impl of a trait - we have a concrete self type and a
940 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
941 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
942 trait_ref.subst(tcx, free_substs)
947 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
948 return (tcx.types.err, Def::Err);
952 traits::supertraits(tcx, ty::Binder(trait_ref))
953 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
956 match self.one_bound_for_assoc_type(candidates,
958 &assoc_name.as_str(),
961 Err(ErrorReported) => return (tcx.types.err, Def::Err),
964 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
965 let trait_node_id = tcx.hir.as_local_node_id(trait_did).unwrap();
966 match self.find_bound_for_assoc_item(trait_node_id,
967 keywords::SelfType.name(),
971 Err(ErrorReported) => return (tcx.types.err, Def::Err),
974 (&ty::TyParam(_), Def::TyParam(param_did)) => {
975 let param_node_id = tcx.hir.as_local_node_id(param_did).unwrap();
976 let param_name = tcx.type_parameter_def(param_node_id).name;
977 match self.find_bound_for_assoc_item(param_node_id,
982 Err(ErrorReported) => return (tcx.types.err, Def::Err),
986 // Don't print TyErr to the user.
987 if !ty.references_error() {
988 self.report_ambiguous_associated_type(span,
991 &assoc_name.as_str());
993 return (tcx.types.err, Def::Err);
997 let trait_did = bound.0.def_id;
998 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1000 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1001 let def_id = item.expect("missing associated type").def_id;
1002 tcx.check_stability(def_id, ref_id, span);
1003 (ty, Def::AssociatedTy(def_id))
1006 fn qpath_to_ty(&self,
1008 opt_self_ty: Option<Ty<'tcx>>,
1009 trait_def_id: DefId,
1010 trait_segment: &hir::PathSegment,
1011 item_segment: &hir::PathSegment)
1014 let tcx = self.tcx();
1016 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1018 let self_ty = if let Some(ty) = opt_self_ty {
1021 let path_str = tcx.item_path_str(trait_def_id);
1022 self.report_ambiguous_associated_type(span,
1025 &item_segment.name.as_str());
1026 return tcx.types.err;
1029 debug!("qpath_to_ty: self_type={:?}", self_ty);
1031 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1036 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1038 self.projected_ty(span, trait_ref, item_segment.name)
1041 // Check a type Path and convert it to a Ty.
1042 pub fn def_to_ty(&self,
1043 opt_self_ty: Option<Ty<'tcx>>,
1045 permit_variants: bool)
1047 let tcx = self.tcx();
1049 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1050 path.def, opt_self_ty, path.segments);
1052 let span = path.span;
1054 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1055 assert_eq!(opt_self_ty, None);
1056 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1057 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1059 Def::Variant(did) if permit_variants => {
1060 // Convert "variant type" as if it were a real type.
1061 // The resulting `Ty` is type of the variant's enum for now.
1062 assert_eq!(opt_self_ty, None);
1063 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1064 self.ast_path_to_ty(span,
1065 tcx.parent_def_id(did).unwrap(),
1066 path.segments.last().unwrap())
1068 Def::TyParam(did) => {
1069 assert_eq!(opt_self_ty, None);
1070 tcx.prohibit_type_params(&path.segments);
1072 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1073 let param = tcx.ty_param_defs.borrow().get(&node_id)
1074 .map(ty::ParamTy::for_def);
1075 if let Some(p) = param {
1078 // Only while computing defaults of earlier type
1079 // parameters can a type parameter be missing its def.
1080 struct_span_err!(tcx.sess, span, E0128,
1081 "type parameters with a default cannot use \
1082 forward declared identifiers")
1083 .span_label(span, &format!("defaulted type parameters \
1084 cannot be forward declared"))
1089 Def::SelfTy(_, Some(def_id)) => {
1090 // Self in impl (we know the concrete type).
1092 assert_eq!(opt_self_ty, None);
1093 tcx.prohibit_type_params(&path.segments);
1095 // FIXME: Self type is not always computed when we are here because type parameter
1096 // bounds may affect Self type and have to be converted before it.
1097 let ty = if def_id.is_local() {
1098 tcx.item_types.borrow().get(&def_id).cloned()
1100 Some(tcx.item_type(def_id))
1102 if let Some(ty) = ty {
1103 if let Some(free_substs) = self.get_free_substs() {
1104 ty.subst(tcx, free_substs)
1109 tcx.sess.span_err(span, "`Self` type is used before it's determined");
1113 Def::SelfTy(Some(_), None) => {
1115 assert_eq!(opt_self_ty, None);
1116 tcx.prohibit_type_params(&path.segments);
1119 Def::AssociatedTy(def_id) => {
1120 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1121 let trait_did = tcx.parent_def_id(def_id).unwrap();
1122 self.qpath_to_ty(span,
1125 &path.segments[path.segments.len()-2],
1126 path.segments.last().unwrap())
1128 Def::PrimTy(prim_ty) => {
1129 assert_eq!(opt_self_ty, None);
1130 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1133 self.set_tainted_by_errors();
1134 return self.tcx().types.err;
1136 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1140 /// Parses the programmer's textual representation of a type into our
1141 /// internal notion of a type.
1142 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1143 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1146 let tcx = self.tcx();
1148 let cache = self.ast_ty_to_ty_cache();
1149 if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1153 let result_ty = match ast_ty.node {
1154 hir::TySlice(ref ty) => {
1155 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1157 hir::TyPtr(ref mt) => {
1158 tcx.mk_ptr(ty::TypeAndMut {
1159 ty: self.ast_ty_to_ty(&mt.ty),
1163 hir::TyRptr(ref region, ref mt) => {
1164 let r = self.ast_region_to_region(region, None);
1165 debug!("TyRef r={:?}", r);
1166 let t = self.ast_ty_to_ty(&mt.ty);
1167 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1172 hir::TyTup(ref fields) => {
1173 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1175 hir::TyBareFn(ref bf) => {
1176 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1177 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1179 // Find any late-bound regions declared in return type that do
1180 // not appear in the arguments. These are not wellformed.
1184 // for<'a> fn() -> &'a str <-- 'a is bad
1185 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1187 // Note that we do this check **here** and not in
1188 // `ty_of_bare_fn` because the latter is also used to make
1189 // the types for fn items, and we do not want to issue a
1190 // warning then. (Once we fix #32330, the regions we are
1191 // checking for here would be considered early bound
1193 let inputs = bare_fn_ty.sig.inputs();
1194 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1195 &inputs.map_bound(|i| i.to_owned()));
1196 let output = bare_fn_ty.sig.output();
1197 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1198 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1199 let br_name = match *br {
1200 ty::BrNamed(_, name, _) => name,
1203 bf.decl.output.span(),
1204 "anonymous bound region {:?} in return but not args",
1209 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1212 format!("return type references lifetime `{}`, \
1213 which does not appear in the trait input types",
1216 tcx.mk_fn_ptr(bare_fn_ty)
1218 hir::TyTraitObject(ref bounds, ref lifetime) => {
1219 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1221 hir::TyImplTrait(ref bounds) => {
1222 use collect::{compute_bounds, SizedByDefault};
1224 // Figure out if we can allow an `impl Trait` here, by walking up
1225 // to a `fn` or inherent `impl` method, going only through `Ty`
1226 // or `TraitRef` nodes (as nothing else should be in types) and
1227 // ensuring that we reach the `fn`/method signature's return type.
1228 let mut node_id = ast_ty.id;
1229 let fn_decl = loop {
1230 let parent = tcx.hir.get_parent_node(node_id);
1231 match tcx.hir.get(parent) {
1232 hir::map::NodeItem(&hir::Item {
1233 node: hir::ItemFn(ref fn_decl, ..), ..
1234 }) => break Some(fn_decl),
1236 hir::map::NodeImplItem(&hir::ImplItem {
1237 node: hir::ImplItemKind::Method(ref sig, _), ..
1239 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1240 hir::ItemImpl(.., None, _, _) => {
1241 break Some(&sig.decl)
1247 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1253 let allow = fn_decl.map_or(false, |fd| {
1255 hir::DefaultReturn(_) => false,
1256 hir::Return(ref ty) => ty.id == node_id
1260 // Create the anonymized type.
1262 let def_id = tcx.hir.local_def_id(ast_ty.id);
1263 if let Err(ErrorReported) = self.get_generics(ast_ty.span, def_id) {
1264 return tcx.types.err;
1266 let substs = Substs::identity_for_item(tcx, def_id);
1267 let ty = tcx.mk_anon(tcx.hir.local_def_id(ast_ty.id), substs);
1269 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1270 let bounds = compute_bounds(self, ty, bounds,
1271 SizedByDefault::Yes,
1273 let predicates = bounds.predicates(tcx, ty);
1274 let predicates = tcx.lift_to_global(&predicates).unwrap();
1275 tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1277 predicates: predicates
1282 span_err!(tcx.sess, ast_ty.span, E0562,
1283 "`impl Trait` not allowed outside of function \
1284 and inherent method return types");
1288 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1289 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1290 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1291 self.ast_ty_to_ty(qself)
1293 self.def_to_ty(opt_self_ty, path, false)
1295 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1296 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1297 let ty = self.ast_ty_to_ty(qself);
1299 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1304 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1306 hir::TyArray(ref ty, length) => {
1307 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1308 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1310 self.tcx().types.err
1313 hir::TyTypeof(ref _e) => {
1314 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1315 "`typeof` is a reserved keyword but unimplemented")
1316 .span_label(ast_ty.span, &format!("reserved keyword"))
1322 // TyInfer also appears as the type of arguments or return
1323 // values in a ExprClosure, or as
1324 // the type of local variables. Both of these cases are
1325 // handled specially and will not descend into this routine.
1326 self.ty_infer(ast_ty.span)
1330 cache.borrow_mut().insert(ast_ty.id, result_ty);
1335 pub fn ty_of_arg(&self,
1337 expected_ty: Option<Ty<'tcx>>)
1341 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1342 hir::TyInfer => self.ty_infer(ty.span),
1343 _ => self.ast_ty_to_ty(ty),
1347 pub fn ty_of_fn(&self,
1348 unsafety: hir::Unsafety,
1351 -> &'tcx ty::BareFnTy<'tcx> {
1354 let input_tys: Vec<Ty> =
1355 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1357 let output_ty = match decl.output {
1358 hir::Return(ref output) => self.ast_ty_to_ty(output),
1359 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1362 debug!("ty_of_fn: output_ty={:?}", output_ty);
1364 self.tcx().mk_bare_fn(ty::BareFnTy {
1367 sig: ty::Binder(self.tcx().mk_fn_sig(
1368 input_tys.into_iter(),
1375 pub fn ty_of_closure(&self,
1376 unsafety: hir::Unsafety,
1379 expected_sig: Option<ty::FnSig<'tcx>>)
1380 -> ty::ClosureTy<'tcx>
1382 debug!("ty_of_closure(expected_sig={:?})",
1385 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1386 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1387 // no guarantee that the correct number of expected args
1389 if i < e.inputs().len() {
1395 self.ty_of_arg(a, expected_arg_ty)
1398 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1400 let is_infer = match decl.output {
1401 hir::Return(ref output) if output.node == hir::TyInfer => true,
1402 hir::DefaultReturn(..) => true,
1406 let output_ty = match decl.output {
1407 _ if is_infer && expected_ret_ty.is_some() =>
1408 expected_ret_ty.unwrap(),
1409 _ if is_infer => self.ty_infer(decl.output.span()),
1410 hir::Return(ref output) =>
1411 self.ast_ty_to_ty(&output),
1412 hir::DefaultReturn(..) => bug!(),
1415 debug!("ty_of_closure: output_ty={:?}", output_ty);
1420 sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1424 /// Given the bounds on an object, determines what single region bound (if any) we can
1425 /// use to summarize this type. The basic idea is that we will use the bound the user
1426 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1427 /// for region bounds. It may be that we can derive no bound at all, in which case
1428 /// we return `None`.
1429 fn compute_object_lifetime_bound(&self,
1431 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1432 -> Option<&'tcx ty::Region> // if None, use the default
1434 let tcx = self.tcx();
1436 debug!("compute_opt_region_bound(existential_predicates={:?})",
1437 existential_predicates);
1439 if let Some(principal) = existential_predicates.principal() {
1440 if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1441 return Some(tcx.mk_region(ty::ReStatic));
1445 // No explicit region bound specified. Therefore, examine trait
1446 // bounds and see if we can derive region bounds from those.
1447 let derived_region_bounds =
1448 object_region_bounds(tcx, existential_predicates);
1450 // If there are no derived region bounds, then report back that we
1451 // can find no region bound. The caller will use the default.
1452 if derived_region_bounds.is_empty() {
1456 // If any of the derived region bounds are 'static, that is always
1458 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1459 return Some(tcx.mk_region(ty::ReStatic));
1462 // Determine whether there is exactly one unique region in the set
1463 // of derived region bounds. If so, use that. Otherwise, report an
1465 let r = derived_region_bounds[0];
1466 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1467 span_err!(tcx.sess, span, E0227,
1468 "ambiguous lifetime bound, explicit lifetime bound required");
1474 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1475 /// remaining general trait bounds.
1476 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1477 trait_bounds: &'b [hir::PolyTraitRef])
1478 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1480 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1481 match bound.trait_ref.path.def {
1482 Def::Trait(trait_did) => {
1483 // Checks whether `trait_did` refers to one of the builtin
1484 // traits, like `Send`, and adds it to `auto_traits` if so.
1485 if Some(trait_did) == tcx.lang_items.send_trait() ||
1486 Some(trait_did) == tcx.lang_items.sync_trait() {
1487 let segments = &bound.trait_ref.path.segments;
1488 let parameters = &segments[segments.len() - 1].parameters;
1489 if !parameters.types().is_empty() {
1490 check_type_argument_count(tcx, bound.trait_ref.path.span,
1491 parameters.types().len(), &[]);
1493 if !parameters.lifetimes().is_empty() {
1494 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1495 parameters.lifetimes().len(), 0);
1506 let auto_traits = auto_traits.into_iter().map(|tr| {
1507 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1512 }).collect::<Vec<_>>();
1514 (auto_traits, trait_bounds)
1517 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1518 ty_param_defs: &[ty::TypeParameterDef]) {
1519 let accepted = ty_param_defs.len();
1520 let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1521 if supplied < required {
1522 let expected = if required < accepted {
1527 let arguments_plural = if required == 1 { "" } else { "s" };
1529 struct_span_err!(tcx.sess, span, E0243,
1530 "wrong number of type arguments: {} {}, found {}",
1531 expected, required, supplied)
1533 &format!("{} {} type argument{}",
1538 } else if supplied > accepted {
1539 let expected = if required < accepted {
1540 format!("expected at most {}", accepted)
1542 format!("expected {}", accepted)
1544 let arguments_plural = if accepted == 1 { "" } else { "s" };
1546 struct_span_err!(tcx.sess, span, E0244,
1547 "wrong number of type arguments: {}, found {}",
1551 &format!("{} type argument{}",
1552 if accepted == 0 { "expected no" } else { &expected },
1559 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1560 let label = if number < expected {
1562 format!("expected {} lifetime parameter", expected)
1564 format!("expected {} lifetime parameters", expected)
1567 let additional = number - expected;
1568 if additional == 1 {
1569 "unexpected lifetime parameter".to_string()
1571 format!("{} unexpected lifetime parameters", additional)
1574 struct_span_err!(tcx.sess, span, E0107,
1575 "wrong number of lifetime parameters: expected {}, found {}",
1577 .span_label(span, &label)
1581 // A helper struct for conveniently grouping a set of bounds which we pass to
1582 // and return from functions in multiple places.
1583 #[derive(PartialEq, Eq, Clone, Debug)]
1584 pub struct Bounds<'tcx> {
1585 pub region_bounds: Vec<&'tcx ty::Region>,
1586 pub implicitly_sized: bool,
1587 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1588 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1591 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1592 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1593 -> Vec<ty::Predicate<'tcx>>
1595 let mut vec = Vec::new();
1597 // If it could be sized, and is, add the sized predicate
1598 if self.implicitly_sized {
1599 if let Some(sized) = tcx.lang_items.sized_trait() {
1600 let trait_ref = ty::TraitRef {
1602 substs: tcx.mk_substs_trait(param_ty, &[])
1604 vec.push(trait_ref.to_predicate());
1608 for ®ion_bound in &self.region_bounds {
1609 // account for the binder being introduced below; no need to shift `param_ty`
1610 // because, at present at least, it can only refer to early-bound regions
1611 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1612 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1615 for bound_trait_ref in &self.trait_bounds {
1616 vec.push(bound_trait_ref.to_predicate());
1619 for projection in &self.projection_bounds {
1620 vec.push(projection.to_predicate());
1627 pub enum ExplicitSelf<'tcx> {
1629 ByReference(&'tcx ty::Region, hir::Mutability),
1633 impl<'tcx> ExplicitSelf<'tcx> {
1634 /// We wish to (for now) categorize an explicit self
1635 /// declaration like `self: SomeType` into either `self`,
1636 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1637 /// by some simple pattern matching. A more precise check
1638 /// is done later in `check_method_self_type()`.
1643 /// impl Foo for &T {
1644 /// // Legal declarations:
1645 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1646 /// fn method2(self: &T); // ExplicitSelf::ByValue
1647 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1649 /// // Invalid cases will be caught later by `check_method_self_type`:
1650 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1654 /// To do the check we just count the number of "modifiers"
1655 /// on each type and compare them. If they are the same or
1656 /// the impl has more, we call it "by value". Otherwise, we
1657 /// look at the outermost modifier on the method decl and
1658 /// call it by-ref, by-box as appropriate. For method1, for
1659 /// example, the impl type has one modifier, but the method
1660 /// type has two, so we end up with
1661 /// ExplicitSelf::ByReference.
1662 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1663 self_arg_ty: Ty<'tcx>)
1664 -> ExplicitSelf<'tcx> {
1665 fn count_modifiers(ty: Ty) -> usize {
1667 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1668 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1673 let impl_modifiers = count_modifiers(untransformed_self_ty);
1674 let method_modifiers = count_modifiers(self_arg_ty);
1676 if impl_modifiers >= method_modifiers {
1677 ExplicitSelf::ByValue
1679 match self_arg_ty.sty {
1680 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1681 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1682 _ => ExplicitSelf::ByValue,