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;
32 use rustc::ty::subst::{Kind, Subst, Substs};
34 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
35 use rustc::ty::wf::object_region_bounds;
36 use rustc_back::slice;
37 use require_c_abi_if_variadic;
38 use util::common::{ErrorReported, FN_OUTPUT_NAME};
39 use util::nodemap::{NodeMap, FxHashSet};
41 use std::cell::RefCell;
43 use syntax::{abi, ast};
44 use syntax::feature_gate::{GateIssue, emit_feature_err};
45 use syntax::symbol::{Symbol, keywords};
48 pub trait AstConv<'gcx, 'tcx> {
49 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
51 /// A cache used for the result of `ast_ty_to_ty_cache`
52 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
54 /// Returns the generic type and lifetime parameters for an item.
55 fn get_generics(&self, span: Span, id: DefId)
56 -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
58 /// Identify the type for an item, like a type alias, fn, or struct.
59 fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported>;
61 /// Returns the `TraitDef` for a given trait. This allows you to
62 /// figure out the set of type parameters defined on the trait.
63 fn get_trait_def(&self, span: Span, id: DefId)
64 -> Result<&'tcx ty::TraitDef, ErrorReported>;
66 /// Ensure that the super-predicates for the trait with the given
67 /// id are available and also for the transitive set of
69 fn ensure_super_predicates(&self, span: Span, id: DefId)
70 -> Result<(), ErrorReported>;
72 /// Returns the set of bounds in scope for the type parameter with
74 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
75 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
77 /// Return an (optional) substitution to convert bound type parameters that
78 /// are in scope into free ones. This function should only return Some
80 /// See ParameterEnvironment::free_substs for more information.
81 fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
83 /// What lifetime should we use when a lifetime is omitted (and not elided)?
84 fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
85 -> Option<&'tcx ty::Region>;
87 /// What type should we use when a type is omitted?
88 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
90 /// Same as ty_infer, but with a known type parameter definition.
91 fn ty_infer_for_def(&self,
92 _def: &ty::TypeParameterDef<'tcx>,
93 _substs: &[Kind<'tcx>],
94 span: Span) -> Ty<'tcx> {
98 /// Projecting an associated type from a (potentially)
99 /// higher-ranked trait reference is more complicated, because of
100 /// the possibility of late-bound regions appearing in the
101 /// associated type binding. This is not legal in function
102 /// signatures for that reason. In a function body, we can always
103 /// handle it because we can use inference variables to remove the
104 /// late-bound regions.
105 fn projected_ty_from_poly_trait_ref(&self,
107 poly_trait_ref: ty::PolyTraitRef<'tcx>,
108 item_name: ast::Name)
111 /// Project an associated type from a non-higher-ranked trait reference.
112 /// This is fairly straightforward and can be accommodated in any context.
113 fn projected_ty(&self,
115 _trait_ref: ty::TraitRef<'tcx>,
116 _item_name: ast::Name)
119 /// Invoked when we encounter an error from some prior pass
120 /// (e.g. resolve) that is translated into a ty-error. This is
121 /// used to help suppress derived errors typeck might otherwise
123 fn set_tainted_by_errors(&self);
126 struct ConvertedBinding<'tcx> {
127 item_name: ast::Name,
132 /// Dummy type used for the `Self` of a `TraitRef` created for converting
133 /// a trait object, and which gets removed in `ExistentialTraitRef`.
134 /// This type must not appear anywhere in other converted types.
135 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
137 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
138 pub fn ast_region_to_region(&self,
139 lifetime: &hir::Lifetime,
140 def: Option<&ty::RegionParameterDef>)
143 let tcx = self.tcx();
144 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
145 Some(&rl::Region::Static) => {
146 tcx.mk_region(ty::ReStatic)
149 Some(&rl::Region::LateBound(debruijn, id)) => {
150 let name = tcx.hir.name(id);
151 tcx.mk_region(ty::ReLateBound(debruijn,
152 ty::BrNamed(tcx.hir.local_def_id(id), name)))
155 Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
156 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
159 Some(&rl::Region::EarlyBound(index, id)) => {
160 let name = tcx.hir.name(id);
161 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
167 Some(&rl::Region::Free(scope, id)) => {
168 let name = tcx.hir.name(id);
169 tcx.mk_region(ty::ReFree(ty::FreeRegion {
170 scope: scope.to_code_extent(&tcx.region_maps),
171 bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name)
174 // (*) -- not late-bound, won't change
178 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
182 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
189 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
190 /// returns an appropriate set of substitutions for this particular reference to `I`.
191 pub fn ast_path_substs_for_ty(&self,
194 item_segment: &hir::PathSegment)
195 -> &'tcx Substs<'tcx>
197 let tcx = self.tcx();
199 match item_segment.parameters {
200 hir::AngleBracketedParameters(_) => {}
201 hir::ParenthesizedParameters(..) => {
202 struct_span_err!(tcx.sess, span, E0214,
203 "parenthesized parameters may only be used with a trait")
204 .span_label(span, &format!("only traits may use parentheses"))
207 return Substs::for_item(tcx, def_id, |_, _| {
208 tcx.mk_region(ty::ReStatic)
215 let (substs, assoc_bindings) =
216 self.create_substs_for_ast_path(span,
218 &item_segment.parameters,
221 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
226 /// Given the type/region arguments provided to some path (along with
227 /// an implicit Self, if this is a trait reference) returns the complete
228 /// set of substitutions. This may involve applying defaulted type parameters.
230 /// Note that the type listing given here is *exactly* what the user provided.
231 fn create_substs_for_ast_path(&self,
234 parameters: &hir::PathParameters,
235 self_ty: Option<Ty<'tcx>>)
236 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
238 let tcx = self.tcx();
240 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
242 def_id, self_ty, parameters);
244 let (lifetimes, num_types_provided, infer_types) = match *parameters {
245 hir::AngleBracketedParameters(ref data) => {
246 (&data.lifetimes[..], data.types.len(), data.infer_types)
248 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
251 // If the type is parameterized by this region, then replace this
252 // region with the current anon region binding (in other words,
253 // whatever & would get replaced with).
254 let decl_generics = match self.get_generics(span, def_id) {
255 Ok(generics) => generics,
256 Err(ErrorReported) => {
257 // No convenient way to recover from a cycle here. Just bail. Sorry!
258 self.tcx().sess.abort_if_errors();
259 bug!("ErrorReported returned, but no errors reports?")
262 let expected_num_region_params = decl_generics.regions.len();
263 let supplied_num_region_params = lifetimes.len();
264 if expected_num_region_params != supplied_num_region_params {
265 report_lifetime_number_error(tcx, span,
266 supplied_num_region_params,
267 expected_num_region_params);
270 // If a self-type was declared, one should be provided.
271 assert_eq!(decl_generics.has_self, self_ty.is_some());
273 // Check the number of type parameters supplied by the user.
274 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
275 if !infer_types || num_types_provided > ty_param_defs.len() {
276 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
279 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
280 let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
281 if let Some(ref default) = p.default {
282 if is_object && default.has_self_ty() {
283 // There is no suitable inference default for a type parameter
284 // that references self, in an object type.
292 let mut output_assoc_binding = None;
293 let substs = Substs::for_item(tcx, def_id, |def, _| {
294 let i = def.index as usize - self_ty.is_some() as usize;
295 if let Some(lifetime) = lifetimes.get(i) {
296 self.ast_region_to_region(lifetime, Some(def))
298 tcx.mk_region(ty::ReStatic)
301 let i = def.index as usize;
303 // Handle Self first, so we can adjust the index to match the AST.
304 if let (0, Some(ty)) = (i, self_ty) {
308 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
309 if i < num_types_provided {
310 // A provided type parameter.
312 hir::AngleBracketedParameters(ref data) => {
313 self.ast_ty_to_ty(&data.types[i])
315 hir::ParenthesizedParameters(ref data) => {
317 let (ty, assoc) = self.convert_parenthesized_parameters(data);
318 output_assoc_binding = Some(assoc);
322 } else if infer_types {
323 // No type parameters were provided, we can infer all.
324 let ty_var = if !default_needs_object_self(def) {
325 self.ty_infer_for_def(def, substs, span)
330 } else if let Some(default) = def.default {
331 // No type parameter provided, but a default exists.
333 // If we are converting an object type, then the
334 // `Self` parameter is unknown. However, some of the
335 // other type parameters may reference `Self` in their
336 // defaults. This will lead to an ICE if we are not
338 if default_needs_object_self(def) {
339 struct_span_err!(tcx.sess, span, E0393,
340 "the type parameter `{}` must be explicitly specified",
342 .span_label(span, &format!("missing reference to `{}`", def.name))
343 .note(&format!("because of the default `Self` reference, \
344 type parameters must be specified on object types"))
348 // This is a default type parameter.
349 default.subst_spanned(tcx, substs, Some(span))
352 // We've already errored above about the mismatch.
357 let assoc_bindings = match *parameters {
358 hir::AngleBracketedParameters(ref data) => {
359 data.bindings.iter().map(|b| {
362 ty: self.ast_ty_to_ty(&b.ty),
367 hir::ParenthesizedParameters(ref data) => {
368 vec![output_assoc_binding.unwrap_or_else(|| {
369 // This is an error condition, but we should
370 // get the associated type binding anyway.
371 self.convert_parenthesized_parameters(data).1
376 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
377 decl_generics, self_ty, substs);
379 (substs, assoc_bindings)
382 fn convert_parenthesized_parameters(&self,
383 data: &hir::ParenthesizedParameterData)
384 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
386 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
387 self.ast_ty_to_ty(a_t)
390 let (output, output_span) = match data.output {
391 Some(ref output_ty) => {
392 (self.ast_ty_to_ty(output_ty), output_ty.span)
395 (self.tcx().mk_nil(), data.span)
399 let output_binding = ConvertedBinding {
400 item_name: Symbol::intern(FN_OUTPUT_NAME),
405 (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
408 /// Instantiates the path for the given trait reference, assuming that it's
409 /// bound to a valid trait type. Returns the def_id for the defining trait.
410 /// Fails if the type is a type other than a trait type.
412 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
413 /// are disallowed. Otherwise, they are pushed onto the vector given.
414 pub fn instantiate_mono_trait_ref(&self,
415 trait_ref: &hir::TraitRef,
417 -> ty::TraitRef<'tcx>
419 let trait_def_id = self.trait_def_id(trait_ref);
420 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
423 trait_ref.path.segments.last().unwrap())
426 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
427 let path = &trait_ref.path;
429 Def::Trait(trait_def_id) => trait_def_id,
431 self.tcx().sess.fatal("cannot continue compilation due to previous error");
434 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
435 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
440 pub fn instantiate_poly_trait_ref(&self,
441 ast_trait_ref: &hir::PolyTraitRef,
443 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
444 -> ty::PolyTraitRef<'tcx>
446 let trait_ref = &ast_trait_ref.trait_ref;
447 let trait_def_id = self.trait_def_id(trait_ref);
449 debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
451 let (substs, assoc_bindings) =
452 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
455 trait_ref.path.segments.last().unwrap());
456 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
458 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
459 // specify type to assert that error was already reported in Err case:
460 let predicate: Result<_, ErrorReported> =
461 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
464 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
467 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
468 trait_ref, poly_projections, poly_trait_ref);
472 fn ast_path_to_mono_trait_ref(&self,
476 trait_segment: &hir::PathSegment)
477 -> ty::TraitRef<'tcx>
479 let (substs, assoc_bindings) =
480 self.create_substs_for_ast_trait_ref(span,
484 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
485 ty::TraitRef::new(trait_def_id, substs)
488 fn create_substs_for_ast_trait_ref(&self,
492 trait_segment: &hir::PathSegment)
493 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
495 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
498 let trait_def = match self.get_trait_def(span, trait_def_id) {
499 Ok(trait_def) => trait_def,
500 Err(ErrorReported) => {
501 // No convenient way to recover from a cycle here. Just bail. Sorry!
502 self.tcx().sess.abort_if_errors();
503 bug!("ErrorReported returned, but no errors reports?")
507 match trait_segment.parameters {
508 hir::AngleBracketedParameters(_) => {
509 // For now, require that parenthetical notation be used
510 // only with `Fn()` etc.
511 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
512 emit_feature_err(&self.tcx().sess.parse_sess,
513 "unboxed_closures", span, GateIssue::Language,
515 the precise format of `Fn`-family traits' \
516 type parameters is subject to change. \
517 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
520 hir::ParenthesizedParameters(_) => {
521 // For now, require that parenthetical notation be used
522 // only with `Fn()` etc.
523 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
524 emit_feature_err(&self.tcx().sess.parse_sess,
525 "unboxed_closures", span, GateIssue::Language,
527 parenthetical notation is only stable when used with `Fn`-family traits");
532 self.create_substs_for_ast_path(span,
534 &trait_segment.parameters,
538 fn trait_defines_associated_type_named(&self,
540 assoc_name: ast::Name)
543 self.tcx().associated_items(trait_def_id).any(|item| {
544 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
548 fn ast_type_binding_to_poly_projection_predicate(
550 _path_id: ast::NodeId,
551 trait_ref: ty::PolyTraitRef<'tcx>,
552 binding: &ConvertedBinding<'tcx>)
553 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
555 let tcx = self.tcx();
557 // Given something like `U : SomeTrait<T=X>`, we want to produce a
558 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
559 // subtle in the event that `T` is defined in a supertrait of
560 // `SomeTrait`, because in that case we need to upcast.
562 // That is, consider this case:
565 // trait SubTrait : SuperTrait<int> { }
566 // trait SuperTrait<A> { type T; }
568 // ... B : SubTrait<T=foo> ...
571 // We want to produce `<B as SuperTrait<int>>::T == foo`.
573 // Find any late-bound regions declared in `ty` that are not
574 // declared in the trait-ref. These are not wellformed.
578 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
579 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
580 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
581 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
582 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
583 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
584 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
585 let br_name = match *br {
586 ty::BrNamed(_, name) => name,
590 "anonymous bound region {:?} in binding but not trait ref",
594 struct_span_err!(tcx.sess,
597 "binding for associated type `{}` references lifetime `{}`, \
598 which does not appear in the trait input types",
599 binding.item_name, br_name)
603 // Simple case: X is defined in the current trait.
604 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
605 return Ok(trait_ref.map_bound(|trait_ref| {
606 ty::ProjectionPredicate {
607 projection_ty: ty::ProjectionTy {
608 trait_ref: trait_ref,
609 item_name: binding.item_name,
616 // Otherwise, we have to walk through the supertraits to find
618 self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
621 traits::supertraits(tcx, trait_ref.clone())
622 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
624 let candidate = self.one_bound_for_assoc_type(candidates,
625 &trait_ref.to_string(),
626 &binding.item_name.as_str(),
629 Ok(candidate.map_bound(|trait_ref| {
630 ty::ProjectionPredicate {
631 projection_ty: ty::ProjectionTy {
632 trait_ref: trait_ref,
633 item_name: binding.item_name,
640 fn ast_path_to_ty(&self,
643 item_segment: &hir::PathSegment)
646 let tcx = self.tcx();
647 let decl_ty = match self.get_item_type(span, did) {
649 Err(ErrorReported) => {
650 return tcx.types.err;
654 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
655 decl_ty.subst(self.tcx(), substs)
658 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
659 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
660 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
661 -> ty::ExistentialTraitRef<'tcx> {
662 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
663 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
666 fn conv_object_ty_poly_trait_ref(&self,
668 trait_bounds: &[hir::PolyTraitRef],
669 lifetime: &hir::Lifetime)
672 let tcx = self.tcx();
674 if trait_bounds.is_empty() {
675 span_err!(tcx.sess, span, E0224,
676 "at least one non-builtin trait is required for an object type");
677 return tcx.types.err;
680 let mut projection_bounds = vec![];
681 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
682 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
684 &mut projection_bounds);
686 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
688 if !trait_bounds.is_empty() {
689 let b = &trait_bounds[0];
690 let span = b.trait_ref.path.span;
691 struct_span_err!(self.tcx().sess, span, E0225,
692 "only Send/Sync traits can be used as additional traits in a trait object")
693 .span_label(span, &format!("non-Send/Sync additional trait"))
697 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
698 let existential_principal = principal.map_bound(|trait_ref| {
699 self.trait_ref_to_existential(trait_ref)
701 let existential_projections = projection_bounds.iter().map(|bound| {
702 bound.map_bound(|b| {
703 let p = b.projection_ty;
704 ty::ExistentialProjection {
705 trait_ref: self.trait_ref_to_existential(p.trait_ref),
706 item_name: p.item_name,
712 // ensure the super predicates and stop if we encountered an error
713 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
714 return tcx.types.err;
717 // check that there are no gross object safety violations,
718 // most importantly, that the supertraits don't contain Self,
720 let object_safety_violations =
721 tcx.astconv_object_safety_violations(principal.def_id());
722 if !object_safety_violations.is_empty() {
723 tcx.report_object_safety_error(
724 span, principal.def_id(), object_safety_violations)
726 return tcx.types.err;
729 let mut associated_types = FxHashSet::default();
730 for tr in traits::supertraits(tcx, principal) {
731 associated_types.extend(tcx.associated_items(tr.def_id())
732 .filter(|item| item.kind == ty::AssociatedKind::Type)
733 .map(|item| (tr.def_id(), item.name)));
736 for projection_bound in &projection_bounds {
737 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
738 projection_bound.0.projection_ty.item_name);
739 associated_types.remove(&pair);
742 for (trait_def_id, name) in associated_types {
743 struct_span_err!(tcx.sess, span, E0191,
744 "the value of the associated type `{}` (from the trait `{}`) must be specified",
746 tcx.item_path_str(trait_def_id))
747 .span_label(span, &format!(
748 "missing associated type `{}` value", name))
753 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
754 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
755 .chain(existential_projections
756 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
757 .collect::<AccumulateVec<[_; 8]>>();
758 v.sort_by(|a, b| a.cmp(tcx, b));
759 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
762 // Explicitly specified region bound. Use that.
763 let region_bound = if !lifetime.is_elided() {
764 self.ast_region_to_region(lifetime, None)
766 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
767 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
768 self.ast_region_to_region(lifetime, None)
770 self.re_infer(span, None).unwrap_or_else(|| {
771 span_err!(tcx.sess, span, E0228,
772 "the lifetime bound for this object type cannot be deduced \
773 from context; please supply an explicit bound");
774 tcx.mk_region(ty::ReStatic)
780 debug!("region_bound: {:?}", region_bound);
782 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
783 debug!("trait_object_type: {:?}", ty);
787 fn report_ambiguous_associated_type(&self,
792 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
793 .span_label(span, &format!("ambiguous associated type"))
794 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
795 type_str, trait_str, name))
800 // Search for a bound on a type parameter which includes the associated item
801 // given by assoc_name. ty_param_node_id is the node id for the type parameter
802 // (which might be `Self`, but only if it is the `Self` of a trait, not an
803 // impl). This function will fail if there are no suitable bounds or there is
805 fn find_bound_for_assoc_item(&self,
806 ty_param_node_id: ast::NodeId,
807 ty_param_name: ast::Name,
808 assoc_name: ast::Name,
810 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
812 let tcx = self.tcx();
814 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
816 Err(ErrorReported) => {
817 return Err(ErrorReported);
821 // Ensure the super predicates and stop if we encountered an error.
822 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
823 return Err(ErrorReported);
826 // Check that there is exactly one way to find an associated type with the
828 let suitable_bounds =
829 traits::transitive_bounds(tcx, &bounds)
830 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
832 self.one_bound_for_assoc_type(suitable_bounds,
833 &ty_param_name.as_str(),
834 &assoc_name.as_str(),
839 // Checks that bounds contains exactly one element and reports appropriate
841 fn one_bound_for_assoc_type<I>(&self,
846 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
847 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
849 let bound = match bounds.next() {
850 Some(bound) => bound,
852 struct_span_err!(self.tcx().sess, span, E0220,
853 "associated type `{}` not found for `{}`",
856 .span_label(span, &format!("associated type `{}` not found", assoc_name))
858 return Err(ErrorReported);
862 if let Some(bound2) = bounds.next() {
863 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
864 let mut err = struct_span_err!(
865 self.tcx().sess, span, E0221,
866 "ambiguous associated type `{}` in bounds of `{}`",
869 err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
871 for bound in bounds {
872 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
873 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
875 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
877 if let Some(span) = bound_span {
878 err.span_label(span, &format!("ambiguous `{}` from `{}`",
882 span_note!(&mut err, span,
883 "associated type `{}` could derive from `{}`",
894 // Create a type from a path to an associated type.
895 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
896 // and item_segment is the path segment for D. We return a type and a def for
898 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
899 // parameter or Self.
900 pub fn associated_path_def_to_ty(&self,
905 item_segment: &hir::PathSegment)
908 let tcx = self.tcx();
909 let assoc_name = item_segment.name;
911 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
913 tcx.prohibit_type_params(slice::ref_slice(item_segment));
915 // Find the type of the associated item, and the trait where the associated
917 let bound = match (&ty.sty, ty_path_def) {
918 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
919 // `Self` in an impl of a trait - we have a concrete self type and a
921 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
922 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
923 trait_ref.subst(tcx, free_substs)
928 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
929 return (tcx.types.err, Def::Err);
933 traits::supertraits(tcx, ty::Binder(trait_ref))
934 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
937 match self.one_bound_for_assoc_type(candidates,
939 &assoc_name.as_str(),
942 Err(ErrorReported) => return (tcx.types.err, Def::Err),
945 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
946 let trait_node_id = tcx.hir.as_local_node_id(trait_did).unwrap();
947 match self.find_bound_for_assoc_item(trait_node_id,
948 keywords::SelfType.name(),
952 Err(ErrorReported) => return (tcx.types.err, Def::Err),
955 (&ty::TyParam(_), Def::TyParam(param_did)) => {
956 let param_node_id = tcx.hir.as_local_node_id(param_did).unwrap();
957 let param_name = tcx.type_parameter_def(param_node_id).name;
958 match self.find_bound_for_assoc_item(param_node_id,
963 Err(ErrorReported) => return (tcx.types.err, Def::Err),
967 // Don't print TyErr to the user.
968 if !ty.references_error() {
969 self.report_ambiguous_associated_type(span,
972 &assoc_name.as_str());
974 return (tcx.types.err, Def::Err);
978 let trait_did = bound.0.def_id;
979 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
981 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
982 let def_id = item.expect("missing associated type").def_id;
983 tcx.check_stability(def_id, ref_id, span);
984 (ty, Def::AssociatedTy(def_id))
987 fn qpath_to_ty(&self,
989 opt_self_ty: Option<Ty<'tcx>>,
991 trait_segment: &hir::PathSegment,
992 item_segment: &hir::PathSegment)
995 let tcx = self.tcx();
997 tcx.prohibit_type_params(slice::ref_slice(item_segment));
999 let self_ty = if let Some(ty) = opt_self_ty {
1002 let path_str = tcx.item_path_str(trait_def_id);
1003 self.report_ambiguous_associated_type(span,
1006 &item_segment.name.as_str());
1007 return tcx.types.err;
1010 debug!("qpath_to_ty: self_type={:?}", self_ty);
1012 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1017 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1019 self.projected_ty(span, trait_ref, item_segment.name)
1022 // Check a type Path and convert it to a Ty.
1023 pub fn def_to_ty(&self,
1024 opt_self_ty: Option<Ty<'tcx>>,
1026 permit_variants: bool)
1028 let tcx = self.tcx();
1030 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1031 path.def, opt_self_ty, path.segments);
1033 let span = path.span;
1035 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1036 assert_eq!(opt_self_ty, None);
1037 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1038 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1040 Def::Variant(did) if permit_variants => {
1041 // Convert "variant type" as if it were a real type.
1042 // The resulting `Ty` is type of the variant's enum for now.
1043 assert_eq!(opt_self_ty, None);
1044 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1045 self.ast_path_to_ty(span,
1046 tcx.parent_def_id(did).unwrap(),
1047 path.segments.last().unwrap())
1049 Def::TyParam(did) => {
1050 assert_eq!(opt_self_ty, None);
1051 tcx.prohibit_type_params(&path.segments);
1053 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1054 let param = tcx.ty_param_defs.borrow().get(&node_id)
1055 .map(ty::ParamTy::for_def);
1056 if let Some(p) = param {
1059 // Only while computing defaults of earlier type
1060 // parameters can a type parameter be missing its def.
1061 struct_span_err!(tcx.sess, span, E0128,
1062 "type parameters with a default cannot use \
1063 forward declared identifiers")
1064 .span_label(span, &format!("defaulted type parameters \
1065 cannot be forward declared"))
1070 Def::SelfTy(_, Some(def_id)) => {
1071 // Self in impl (we know the concrete type).
1073 assert_eq!(opt_self_ty, None);
1074 tcx.prohibit_type_params(&path.segments);
1076 // FIXME: Self type is not always computed when we are here because type parameter
1077 // bounds may affect Self type and have to be converted before it.
1078 let ty = if def_id.is_local() {
1079 tcx.item_types.borrow().get(&def_id).cloned()
1081 Some(tcx.item_type(def_id))
1083 if let Some(ty) = ty {
1084 if let Some(free_substs) = self.get_free_substs() {
1085 ty.subst(tcx, free_substs)
1090 tcx.sess.span_err(span, "`Self` type is used before it's determined");
1094 Def::SelfTy(Some(_), None) => {
1096 assert_eq!(opt_self_ty, None);
1097 tcx.prohibit_type_params(&path.segments);
1100 Def::AssociatedTy(def_id) => {
1101 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1102 let trait_did = tcx.parent_def_id(def_id).unwrap();
1103 self.qpath_to_ty(span,
1106 &path.segments[path.segments.len()-2],
1107 path.segments.last().unwrap())
1109 Def::PrimTy(prim_ty) => {
1110 assert_eq!(opt_self_ty, None);
1111 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1114 self.set_tainted_by_errors();
1115 return self.tcx().types.err;
1117 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1121 /// Parses the programmer's textual representation of a type into our
1122 /// internal notion of a type.
1123 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1124 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1127 let tcx = self.tcx();
1129 let cache = self.ast_ty_to_ty_cache();
1130 if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1134 let result_ty = match ast_ty.node {
1135 hir::TySlice(ref ty) => {
1136 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1138 hir::TyPtr(ref mt) => {
1139 tcx.mk_ptr(ty::TypeAndMut {
1140 ty: self.ast_ty_to_ty(&mt.ty),
1144 hir::TyRptr(ref region, ref mt) => {
1145 let r = self.ast_region_to_region(region, None);
1146 debug!("TyRef r={:?}", r);
1147 let t = self.ast_ty_to_ty(&mt.ty);
1148 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1153 hir::TyTup(ref fields) => {
1154 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1156 hir::TyBareFn(ref bf) => {
1157 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1158 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1160 // Find any late-bound regions declared in return type that do
1161 // not appear in the arguments. These are not wellformed.
1165 // for<'a> fn() -> &'a str <-- 'a is bad
1166 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1168 // Note that we do this check **here** and not in
1169 // `ty_of_bare_fn` because the latter is also used to make
1170 // the types for fn items, and we do not want to issue a
1171 // warning then. (Once we fix #32330, the regions we are
1172 // checking for here would be considered early bound
1174 let inputs = bare_fn_ty.sig.inputs();
1175 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1176 &inputs.map_bound(|i| i.to_owned()));
1177 let output = bare_fn_ty.sig.output();
1178 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1179 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1180 let br_name = match *br {
1181 ty::BrNamed(_, name) => name,
1184 bf.decl.output.span(),
1185 "anonymous bound region {:?} in return but not args",
1189 struct_span_err!(tcx.sess,
1192 "return type references lifetime `{}`, \
1193 which does not appear in the fn input types",
1197 tcx.mk_fn_ptr(bare_fn_ty)
1199 hir::TyTraitObject(ref bounds, ref lifetime) => {
1200 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1202 hir::TyImplTrait(ref bounds) => {
1203 use collect::{compute_bounds, SizedByDefault};
1205 // Figure out if we can allow an `impl Trait` here, by walking up
1206 // to a `fn` or inherent `impl` method, going only through `Ty`
1207 // or `TraitRef` nodes (as nothing else should be in types) and
1208 // ensuring that we reach the `fn`/method signature's return type.
1209 let mut node_id = ast_ty.id;
1210 let fn_decl = loop {
1211 let parent = tcx.hir.get_parent_node(node_id);
1212 match tcx.hir.get(parent) {
1213 hir::map::NodeItem(&hir::Item {
1214 node: hir::ItemFn(ref fn_decl, ..), ..
1215 }) => break Some(fn_decl),
1217 hir::map::NodeImplItem(&hir::ImplItem {
1218 node: hir::ImplItemKind::Method(ref sig, _), ..
1220 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1221 hir::ItemImpl(.., None, _, _) => {
1222 break Some(&sig.decl)
1228 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1234 let allow = fn_decl.map_or(false, |fd| {
1236 hir::DefaultReturn(_) => false,
1237 hir::Return(ref ty) => ty.id == node_id
1241 // Create the anonymized type.
1243 let def_id = tcx.hir.local_def_id(ast_ty.id);
1244 if let Err(ErrorReported) = self.get_generics(ast_ty.span, def_id) {
1245 return tcx.types.err;
1247 let substs = Substs::identity_for_item(tcx, def_id);
1248 let ty = tcx.mk_anon(tcx.hir.local_def_id(ast_ty.id), substs);
1250 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1251 let bounds = compute_bounds(self, ty, bounds,
1252 SizedByDefault::Yes,
1254 let predicates = bounds.predicates(tcx, ty);
1255 let predicates = tcx.lift_to_global(&predicates).unwrap();
1256 tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1258 predicates: predicates
1263 span_err!(tcx.sess, ast_ty.span, E0562,
1264 "`impl Trait` not allowed outside of function \
1265 and inherent method return types");
1269 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1270 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1271 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1272 self.ast_ty_to_ty(qself)
1274 self.def_to_ty(opt_self_ty, path, false)
1276 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1277 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1278 let ty = self.ast_ty_to_ty(qself);
1280 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1285 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1287 hir::TyArray(ref ty, length) => {
1288 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1289 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1291 self.tcx().types.err
1294 hir::TyTypeof(ref _e) => {
1295 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1296 "`typeof` is a reserved keyword but unimplemented")
1297 .span_label(ast_ty.span, &format!("reserved keyword"))
1303 // TyInfer also appears as the type of arguments or return
1304 // values in a ExprClosure, or as
1305 // the type of local variables. Both of these cases are
1306 // handled specially and will not descend into this routine.
1307 self.ty_infer(ast_ty.span)
1311 cache.borrow_mut().insert(ast_ty.id, result_ty);
1316 pub fn ty_of_arg(&self,
1318 expected_ty: Option<Ty<'tcx>>)
1322 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1323 hir::TyInfer => self.ty_infer(ty.span),
1324 _ => self.ast_ty_to_ty(ty),
1328 pub fn ty_of_fn(&self,
1329 unsafety: hir::Unsafety,
1332 -> &'tcx ty::BareFnTy<'tcx> {
1335 let input_tys: Vec<Ty> =
1336 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1338 let output_ty = match decl.output {
1339 hir::Return(ref output) => self.ast_ty_to_ty(output),
1340 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1343 debug!("ty_of_fn: output_ty={:?}", output_ty);
1345 self.tcx().mk_bare_fn(ty::BareFnTy {
1348 sig: ty::Binder(self.tcx().mk_fn_sig(
1349 input_tys.into_iter(),
1356 pub fn ty_of_closure(&self,
1357 unsafety: hir::Unsafety,
1360 expected_sig: Option<ty::FnSig<'tcx>>)
1361 -> ty::ClosureTy<'tcx>
1363 debug!("ty_of_closure(expected_sig={:?})",
1366 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1367 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1368 // no guarantee that the correct number of expected args
1370 if i < e.inputs().len() {
1376 self.ty_of_arg(a, expected_arg_ty)
1379 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1381 let is_infer = match decl.output {
1382 hir::Return(ref output) if output.node == hir::TyInfer => true,
1383 hir::DefaultReturn(..) => true,
1387 let output_ty = match decl.output {
1388 _ if is_infer && expected_ret_ty.is_some() =>
1389 expected_ret_ty.unwrap(),
1390 _ if is_infer => self.ty_infer(decl.output.span()),
1391 hir::Return(ref output) =>
1392 self.ast_ty_to_ty(&output),
1393 hir::DefaultReturn(..) => bug!(),
1396 debug!("ty_of_closure: output_ty={:?}", output_ty);
1401 sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1405 /// Given the bounds on an object, determines what single region bound (if any) we can
1406 /// use to summarize this type. The basic idea is that we will use the bound the user
1407 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1408 /// for region bounds. It may be that we can derive no bound at all, in which case
1409 /// we return `None`.
1410 fn compute_object_lifetime_bound(&self,
1412 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1413 -> Option<&'tcx ty::Region> // if None, use the default
1415 let tcx = self.tcx();
1417 debug!("compute_opt_region_bound(existential_predicates={:?})",
1418 existential_predicates);
1420 if let Some(principal) = existential_predicates.principal() {
1421 if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1422 return Some(tcx.mk_region(ty::ReStatic));
1426 // No explicit region bound specified. Therefore, examine trait
1427 // bounds and see if we can derive region bounds from those.
1428 let derived_region_bounds =
1429 object_region_bounds(tcx, existential_predicates);
1431 // If there are no derived region bounds, then report back that we
1432 // can find no region bound. The caller will use the default.
1433 if derived_region_bounds.is_empty() {
1437 // If any of the derived region bounds are 'static, that is always
1439 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1440 return Some(tcx.mk_region(ty::ReStatic));
1443 // Determine whether there is exactly one unique region in the set
1444 // of derived region bounds. If so, use that. Otherwise, report an
1446 let r = derived_region_bounds[0];
1447 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1448 span_err!(tcx.sess, span, E0227,
1449 "ambiguous lifetime bound, explicit lifetime bound required");
1455 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1456 /// remaining general trait bounds.
1457 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1458 trait_bounds: &'b [hir::PolyTraitRef])
1459 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1461 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1462 match bound.trait_ref.path.def {
1463 Def::Trait(trait_did) => {
1464 // Checks whether `trait_did` refers to one of the builtin
1465 // traits, like `Send`, and adds it to `auto_traits` if so.
1466 if Some(trait_did) == tcx.lang_items.send_trait() ||
1467 Some(trait_did) == tcx.lang_items.sync_trait() {
1468 let segments = &bound.trait_ref.path.segments;
1469 let parameters = &segments[segments.len() - 1].parameters;
1470 if !parameters.types().is_empty() {
1471 check_type_argument_count(tcx, bound.trait_ref.path.span,
1472 parameters.types().len(), &[]);
1474 if !parameters.lifetimes().is_empty() {
1475 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1476 parameters.lifetimes().len(), 0);
1487 let auto_traits = auto_traits.into_iter().map(|tr| {
1488 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1493 }).collect::<Vec<_>>();
1495 (auto_traits, trait_bounds)
1498 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1499 ty_param_defs: &[ty::TypeParameterDef]) {
1500 let accepted = ty_param_defs.len();
1501 let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1502 if supplied < required {
1503 let expected = if required < accepted {
1508 let arguments_plural = if required == 1 { "" } else { "s" };
1510 struct_span_err!(tcx.sess, span, E0243,
1511 "wrong number of type arguments: {} {}, found {}",
1512 expected, required, supplied)
1514 &format!("{} {} type argument{}",
1519 } else if supplied > accepted {
1520 let expected = if required < accepted {
1521 format!("expected at most {}", accepted)
1523 format!("expected {}", accepted)
1525 let arguments_plural = if accepted == 1 { "" } else { "s" };
1527 struct_span_err!(tcx.sess, span, E0244,
1528 "wrong number of type arguments: {}, found {}",
1532 &format!("{} type argument{}",
1533 if accepted == 0 { "expected no" } else { &expected },
1540 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1541 let label = if number < expected {
1543 format!("expected {} lifetime parameter", expected)
1545 format!("expected {} lifetime parameters", expected)
1548 let additional = number - expected;
1549 if additional == 1 {
1550 "unexpected lifetime parameter".to_string()
1552 format!("{} unexpected lifetime parameters", additional)
1555 struct_span_err!(tcx.sess, span, E0107,
1556 "wrong number of lifetime parameters: expected {}, found {}",
1558 .span_label(span, &label)
1562 // A helper struct for conveniently grouping a set of bounds which we pass to
1563 // and return from functions in multiple places.
1564 #[derive(PartialEq, Eq, Clone, Debug)]
1565 pub struct Bounds<'tcx> {
1566 pub region_bounds: Vec<&'tcx ty::Region>,
1567 pub implicitly_sized: bool,
1568 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1569 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1572 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1573 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1574 -> Vec<ty::Predicate<'tcx>>
1576 let mut vec = Vec::new();
1578 // If it could be sized, and is, add the sized predicate
1579 if self.implicitly_sized {
1580 if let Some(sized) = tcx.lang_items.sized_trait() {
1581 let trait_ref = ty::TraitRef {
1583 substs: tcx.mk_substs_trait(param_ty, &[])
1585 vec.push(trait_ref.to_predicate());
1589 for ®ion_bound in &self.region_bounds {
1590 // account for the binder being introduced below; no need to shift `param_ty`
1591 // because, at present at least, it can only refer to early-bound regions
1592 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1593 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1596 for bound_trait_ref in &self.trait_bounds {
1597 vec.push(bound_trait_ref.to_predicate());
1600 for projection in &self.projection_bounds {
1601 vec.push(projection.to_predicate());
1608 pub enum ExplicitSelf<'tcx> {
1610 ByReference(&'tcx ty::Region, hir::Mutability),
1614 impl<'tcx> ExplicitSelf<'tcx> {
1615 /// We wish to (for now) categorize an explicit self
1616 /// declaration like `self: SomeType` into either `self`,
1617 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1618 /// by some simple pattern matching. A more precise check
1619 /// is done later in `check_method_self_type()`.
1624 /// impl Foo for &T {
1625 /// // Legal declarations:
1626 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1627 /// fn method2(self: &T); // ExplicitSelf::ByValue
1628 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1630 /// // Invalid cases will be caught later by `check_method_self_type`:
1631 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1635 /// To do the check we just count the number of "modifiers"
1636 /// on each type and compare them. If they are the same or
1637 /// the impl has more, we call it "by value". Otherwise, we
1638 /// look at the outermost modifier on the method decl and
1639 /// call it by-ref, by-box as appropriate. For method1, for
1640 /// example, the impl type has one modifier, but the method
1641 /// type has two, so we end up with
1642 /// ExplicitSelf::ByReference.
1643 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1644 self_arg_ty: Ty<'tcx>)
1645 -> ExplicitSelf<'tcx> {
1646 fn count_modifiers(ty: Ty) -> usize {
1648 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1649 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1654 let impl_modifiers = count_modifiers(untransformed_self_ty);
1655 let method_modifiers = count_modifiers(self_arg_ty);
1657 if impl_modifiers >= method_modifiers {
1658 ExplicitSelf::ByValue
1660 match self_arg_ty.sty {
1661 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1662 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1663 _ => ExplicitSelf::ByValue,