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 use rustc::middle::const_val::eval_length;
16 use rustc_data_structures::accumulate_vec::AccumulateVec;
19 use hir::def_id::DefId;
20 use middle::resolve_lifetime as rl;
21 use rustc::ty::subst::{Kind, Subst, Substs};
23 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
24 use rustc::ty::wf::object_region_bounds;
25 use rustc::lint::builtin::PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES;
26 use rustc_back::slice;
27 use require_c_abi_if_variadic;
28 use util::common::{ErrorReported, FN_OUTPUT_NAME};
29 use util::nodemap::FxHashSet;
32 use syntax::{abi, ast};
33 use syntax::feature_gate::{GateIssue, emit_feature_err};
34 use syntax::symbol::Symbol;
37 pub trait AstConv<'gcx, 'tcx> {
38 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
40 /// Returns the set of bounds in scope for the type parameter with
42 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
43 -> ty::GenericPredicates<'tcx>;
45 /// What lifetime should we use when a lifetime is omitted (and not elided)?
46 fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
47 -> Option<ty::Region<'tcx>>;
49 /// What type should we use when a type is omitted?
50 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
52 /// Same as ty_infer, but with a known type parameter definition.
53 fn ty_infer_for_def(&self,
54 _def: &ty::TypeParameterDef,
55 _substs: &[Kind<'tcx>],
56 span: Span) -> Ty<'tcx> {
60 /// Projecting an associated type from a (potentially)
61 /// higher-ranked trait reference is more complicated, because of
62 /// the possibility of late-bound regions appearing in the
63 /// associated type binding. This is not legal in function
64 /// signatures for that reason. In a function body, we can always
65 /// handle it because we can use inference variables to remove the
66 /// late-bound regions.
67 fn projected_ty_from_poly_trait_ref(&self,
70 poly_trait_ref: ty::PolyTraitRef<'tcx>)
73 /// Normalize an associated type coming from the user.
74 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
76 /// Invoked when we encounter an error from some prior pass
77 /// (e.g. resolve) that is translated into a ty-error. This is
78 /// used to help suppress derived errors typeck might otherwise
80 fn set_tainted_by_errors(&self);
83 struct ConvertedBinding<'tcx> {
89 /// Dummy type used for the `Self` of a `TraitRef` created for converting
90 /// a trait object, and which gets removed in `ExistentialTraitRef`.
91 /// This type must not appear anywhere in other converted types.
92 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
94 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
95 pub fn ast_region_to_region(&self,
96 lifetime: &hir::Lifetime,
97 def: Option<&ty::RegionParameterDef>)
100 let tcx = self.tcx();
101 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
102 Some(&rl::Region::Static) => {
106 Some(&rl::Region::LateBound(debruijn, id)) => {
107 let name = tcx.hir.name(id);
108 tcx.mk_region(ty::ReLateBound(debruijn,
109 ty::BrNamed(tcx.hir.local_def_id(id), name)))
112 Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
113 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
116 Some(&rl::Region::EarlyBound(index, id)) => {
117 let name = tcx.hir.name(id);
118 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
119 def_id: tcx.hir.local_def_id(id),
125 Some(&rl::Region::Free(scope, id)) => {
126 let name = tcx.hir.name(id);
127 tcx.mk_region(ty::ReFree(ty::FreeRegion {
129 bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name)
132 // (*) -- not late-bound, won't change
136 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
140 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
147 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
148 /// returns an appropriate set of substitutions for this particular reference to `I`.
149 pub fn ast_path_substs_for_ty(&self,
152 item_segment: &hir::PathSegment)
153 -> &'tcx Substs<'tcx>
155 let tcx = self.tcx();
157 match item_segment.parameters {
158 hir::AngleBracketedParameters(_) => {}
159 hir::ParenthesizedParameters(..) => {
160 self.prohibit_parenthesized_params(item_segment, true);
162 return Substs::for_item(tcx, def_id, |_, _| {
170 let (substs, assoc_bindings) =
171 self.create_substs_for_ast_path(span,
173 &item_segment.parameters,
176 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
181 /// Given the type/region arguments provided to some path (along with
182 /// an implicit Self, if this is a trait reference) returns the complete
183 /// set of substitutions. This may involve applying defaulted type parameters.
185 /// Note that the type listing given here is *exactly* what the user provided.
186 fn create_substs_for_ast_path(&self,
189 parameters: &hir::PathParameters,
190 self_ty: Option<Ty<'tcx>>)
191 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
193 let tcx = self.tcx();
195 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
197 def_id, self_ty, parameters);
199 let (lifetimes, num_types_provided, infer_types) = match *parameters {
200 hir::AngleBracketedParameters(ref data) => {
201 (&data.lifetimes[..], data.types.len(), data.infer_types)
203 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
206 // If the type is parameterized by this region, then replace this
207 // region with the current anon region binding (in other words,
208 // whatever & would get replaced with).
209 let decl_generics = tcx.generics_of(def_id);
210 let expected_num_region_params = decl_generics.regions.len();
211 let supplied_num_region_params = lifetimes.len();
212 if expected_num_region_params != supplied_num_region_params {
213 report_lifetime_number_error(tcx, span,
214 supplied_num_region_params,
215 expected_num_region_params);
218 // If a self-type was declared, one should be provided.
219 assert_eq!(decl_generics.has_self, self_ty.is_some());
221 // Check the number of type parameters supplied by the user.
222 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
223 if !infer_types || num_types_provided > ty_param_defs.len() {
224 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
227 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
228 let default_needs_object_self = |p: &ty::TypeParameterDef| {
229 if is_object && p.has_default {
230 if tcx.at(span).type_of(p.def_id).has_self_ty() {
231 // There is no suitable inference default for a type parameter
232 // that references self, in an object type.
240 let mut output_assoc_binding = None;
241 let substs = Substs::for_item(tcx, def_id, |def, _| {
242 let i = def.index as usize - self_ty.is_some() as usize;
243 if let Some(lifetime) = lifetimes.get(i) {
244 self.ast_region_to_region(lifetime, Some(def))
249 let i = def.index as usize;
251 // Handle Self first, so we can adjust the index to match the AST.
252 if let (0, Some(ty)) = (i, self_ty) {
256 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
257 if i < num_types_provided {
258 // A provided type parameter.
260 hir::AngleBracketedParameters(ref data) => {
261 self.ast_ty_to_ty(&data.types[i])
263 hir::ParenthesizedParameters(ref data) => {
265 let (ty, assoc) = self.convert_parenthesized_parameters(data);
266 output_assoc_binding = Some(assoc);
270 } else if infer_types {
271 // No type parameters were provided, we can infer all.
272 let ty_var = if !default_needs_object_self(def) {
273 self.ty_infer_for_def(def, substs, span)
278 } else if def.has_default {
279 // No type parameter provided, but a default exists.
281 // If we are converting an object type, then the
282 // `Self` parameter is unknown. However, some of the
283 // other type parameters may reference `Self` in their
284 // defaults. This will lead to an ICE if we are not
286 if default_needs_object_self(def) {
287 struct_span_err!(tcx.sess, span, E0393,
288 "the type parameter `{}` must be explicitly specified",
290 .span_label(span, format!("missing reference to `{}`", def.name))
291 .note(&format!("because of the default `Self` reference, \
292 type parameters must be specified on object types"))
296 // This is a default type parameter.
299 tcx.at(span).type_of(def.def_id)
300 .subst_spanned(tcx, substs, Some(span))
304 // We've already errored above about the mismatch.
309 let assoc_bindings = match *parameters {
310 hir::AngleBracketedParameters(ref data) => {
311 data.bindings.iter().map(|b| {
314 ty: self.ast_ty_to_ty(&b.ty),
319 hir::ParenthesizedParameters(ref data) => {
320 vec![output_assoc_binding.unwrap_or_else(|| {
321 // This is an error condition, but we should
322 // get the associated type binding anyway.
323 self.convert_parenthesized_parameters(data).1
328 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
329 decl_generics, self_ty, substs);
331 (substs, assoc_bindings)
334 fn convert_parenthesized_parameters(&self,
335 data: &hir::ParenthesizedParameterData)
336 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
338 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
339 self.ast_ty_to_ty(a_t)
342 let (output, output_span) = match data.output {
343 Some(ref output_ty) => {
344 (self.ast_ty_to_ty(output_ty), output_ty.span)
347 (self.tcx().mk_nil(), data.span)
351 let output_binding = ConvertedBinding {
352 item_name: Symbol::intern(FN_OUTPUT_NAME),
357 (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
360 /// Instantiates the path for the given trait reference, assuming that it's
361 /// bound to a valid trait type. Returns the def_id for the defining trait.
362 /// Fails if the type is a type other than a trait type.
364 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
365 /// are disallowed. Otherwise, they are pushed onto the vector given.
366 pub fn instantiate_mono_trait_ref(&self,
367 trait_ref: &hir::TraitRef,
369 -> ty::TraitRef<'tcx>
371 self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
373 let trait_def_id = self.trait_def_id(trait_ref);
374 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
377 trait_ref.path.segments.last().unwrap())
380 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
381 let path = &trait_ref.path;
383 Def::Trait(trait_def_id) => trait_def_id,
385 self.tcx().sess.fatal("cannot continue compilation due to previous error");
388 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
389 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
394 pub fn instantiate_poly_trait_ref(&self,
395 ast_trait_ref: &hir::PolyTraitRef,
397 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
398 -> ty::PolyTraitRef<'tcx>
400 let trait_ref = &ast_trait_ref.trait_ref;
401 let trait_def_id = self.trait_def_id(trait_ref);
403 debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
405 self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
407 let (substs, assoc_bindings) =
408 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
411 trait_ref.path.segments.last().unwrap());
412 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
414 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
415 // specify type to assert that error was already reported in Err case:
416 let predicate: Result<_, ErrorReported> =
417 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
420 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
423 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
424 trait_ref, poly_projections, poly_trait_ref);
428 fn ast_path_to_mono_trait_ref(&self,
432 trait_segment: &hir::PathSegment)
433 -> ty::TraitRef<'tcx>
435 let (substs, assoc_bindings) =
436 self.create_substs_for_ast_trait_ref(span,
440 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
441 ty::TraitRef::new(trait_def_id, substs)
444 fn create_substs_for_ast_trait_ref(&self,
448 trait_segment: &hir::PathSegment)
449 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
451 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
454 let trait_def = self.tcx().trait_def(trait_def_id);
456 match trait_segment.parameters {
457 hir::AngleBracketedParameters(_) => {
458 // For now, require that parenthetical notation be used
459 // only with `Fn()` etc.
460 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
461 emit_feature_err(&self.tcx().sess.parse_sess,
462 "unboxed_closures", span, GateIssue::Language,
464 the precise format of `Fn`-family traits' \
465 type parameters is subject to change. \
466 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
469 hir::ParenthesizedParameters(_) => {
470 // For now, require that parenthetical notation be used
471 // only with `Fn()` etc.
472 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
473 emit_feature_err(&self.tcx().sess.parse_sess,
474 "unboxed_closures", span, GateIssue::Language,
476 parenthetical notation is only stable when used with `Fn`-family traits");
481 self.create_substs_for_ast_path(span,
483 &trait_segment.parameters,
487 fn trait_defines_associated_type_named(&self,
489 assoc_name: ast::Name)
492 self.tcx().associated_items(trait_def_id).any(|item| {
493 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
497 fn ast_type_binding_to_poly_projection_predicate(
499 _path_id: ast::NodeId,
500 trait_ref: ty::PolyTraitRef<'tcx>,
501 binding: &ConvertedBinding<'tcx>)
502 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
504 let tcx = self.tcx();
506 // Given something like `U : SomeTrait<T=X>`, we want to produce a
507 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
508 // subtle in the event that `T` is defined in a supertrait of
509 // `SomeTrait`, because in that case we need to upcast.
511 // That is, consider this case:
514 // trait SubTrait : SuperTrait<int> { }
515 // trait SuperTrait<A> { type T; }
517 // ... B : SubTrait<T=foo> ...
520 // We want to produce `<B as SuperTrait<int>>::T == foo`.
522 // Find any late-bound regions declared in `ty` that are not
523 // declared in the trait-ref. These are not wellformed.
527 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
528 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
529 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
530 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
531 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
532 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
533 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
534 let br_name = match *br {
535 ty::BrNamed(_, name) => name,
539 "anonymous bound region {:?} in binding but not trait ref",
543 struct_span_err!(tcx.sess,
546 "binding for associated type `{}` references lifetime `{}`, \
547 which does not appear in the trait input types",
548 binding.item_name, br_name)
552 // Simple case: X is defined in the current trait.
553 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
554 return Ok(trait_ref.map_bound(|trait_ref| {
555 ty::ProjectionPredicate {
556 projection_ty: ty::ProjectionTy::from_ref_and_name(
566 // Otherwise, we have to walk through the supertraits to find
569 traits::supertraits(tcx, trait_ref.clone())
570 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
572 let candidate = self.one_bound_for_assoc_type(candidates,
573 &trait_ref.to_string(),
574 &binding.item_name.as_str(),
577 Ok(candidate.map_bound(|trait_ref| {
578 ty::ProjectionPredicate {
579 projection_ty: ty::ProjectionTy::from_ref_and_name(
589 fn ast_path_to_ty(&self,
592 item_segment: &hir::PathSegment)
595 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
598 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
602 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
603 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
604 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
605 -> ty::ExistentialTraitRef<'tcx> {
606 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
607 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
610 fn conv_object_ty_poly_trait_ref(&self,
612 trait_bounds: &[hir::PolyTraitRef],
613 lifetime: &hir::Lifetime)
616 let tcx = self.tcx();
618 if trait_bounds.is_empty() {
619 span_err!(tcx.sess, span, E0224,
620 "at least one non-builtin trait is required for an object type");
621 return tcx.types.err;
624 let mut projection_bounds = vec![];
625 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
626 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
628 &mut projection_bounds);
630 for trait_bound in trait_bounds[1..].iter() {
631 // Sanity check for non-principal trait bounds
632 self.instantiate_poly_trait_ref(trait_bound,
637 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
639 if !trait_bounds.is_empty() {
640 let b = &trait_bounds[0];
641 let span = b.trait_ref.path.span;
642 struct_span_err!(self.tcx().sess, span, E0225,
643 "only Send/Sync traits can be used as additional traits in a trait object")
644 .span_label(span, "non-Send/Sync additional trait")
648 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
649 let existential_principal = principal.map_bound(|trait_ref| {
650 self.trait_ref_to_existential(trait_ref)
652 let existential_projections = projection_bounds.iter().map(|bound| {
653 bound.map_bound(|b| {
654 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
655 ty::ExistentialProjection {
657 item_def_id: b.projection_ty.item_def_id,
658 substs: trait_ref.substs,
663 // check that there are no gross object safety violations,
664 // most importantly, that the supertraits don't contain Self,
666 let object_safety_violations =
667 tcx.astconv_object_safety_violations(principal.def_id());
668 if !object_safety_violations.is_empty() {
669 tcx.report_object_safety_error(
670 span, principal.def_id(), object_safety_violations)
672 return tcx.types.err;
675 let mut associated_types = FxHashSet::default();
676 for tr in traits::supertraits(tcx, principal) {
677 associated_types.extend(tcx.associated_items(tr.def_id())
678 .filter(|item| item.kind == ty::AssociatedKind::Type)
679 .map(|item| item.def_id));
682 for projection_bound in &projection_bounds {
683 associated_types.remove(&projection_bound.0.projection_ty.item_def_id);
686 for item_def_id in associated_types {
687 let assoc_item = tcx.associated_item(item_def_id);
688 let trait_def_id = assoc_item.container.id();
689 struct_span_err!(tcx.sess, span, E0191,
690 "the value of the associated type `{}` (from the trait `{}`) must be specified",
692 tcx.item_path_str(trait_def_id))
693 .span_label(span, format!(
694 "missing associated type `{}` value", assoc_item.name))
699 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
700 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
701 .chain(existential_projections
702 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
703 .collect::<AccumulateVec<[_; 8]>>();
704 v.sort_by(|a, b| a.cmp(tcx, b));
705 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
708 // Explicitly specified region bound. Use that.
709 let region_bound = if !lifetime.is_elided() {
710 self.ast_region_to_region(lifetime, None)
712 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
713 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
714 self.ast_region_to_region(lifetime, None)
716 self.re_infer(span, None).unwrap_or_else(|| {
717 span_err!(tcx.sess, span, E0228,
718 "the lifetime bound for this object type cannot be deduced \
719 from context; please supply an explicit bound");
726 debug!("region_bound: {:?}", region_bound);
728 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
729 debug!("trait_object_type: {:?}", ty);
733 fn report_ambiguous_associated_type(&self,
738 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
739 .span_label(span, "ambiguous associated type")
740 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
741 type_str, trait_str, name))
746 // Search for a bound on a type parameter which includes the associated item
747 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
748 // This function will fail if there are no suitable bounds or there is
750 fn find_bound_for_assoc_item(&self,
751 ty_param_def_id: DefId,
752 assoc_name: ast::Name,
754 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
756 let tcx = self.tcx();
758 let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
759 .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
761 // Check that there is exactly one way to find an associated type with the
763 let suitable_bounds =
764 traits::transitive_bounds(tcx, &bounds)
765 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
767 let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
768 let param_name = tcx.hir.ty_param_name(param_node_id);
769 self.one_bound_for_assoc_type(suitable_bounds,
770 ¶m_name.as_str(),
771 &assoc_name.as_str(),
776 // Checks that bounds contains exactly one element and reports appropriate
778 fn one_bound_for_assoc_type<I>(&self,
783 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
784 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
786 let bound = match bounds.next() {
787 Some(bound) => bound,
789 struct_span_err!(self.tcx().sess, span, E0220,
790 "associated type `{}` not found for `{}`",
793 .span_label(span, format!("associated type `{}` not found", assoc_name))
795 return Err(ErrorReported);
799 if let Some(bound2) = bounds.next() {
800 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
801 let mut err = struct_span_err!(
802 self.tcx().sess, span, E0221,
803 "ambiguous associated type `{}` in bounds of `{}`",
806 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
808 for bound in bounds {
809 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
810 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
812 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
814 if let Some(span) = bound_span {
815 err.span_label(span, format!("ambiguous `{}` from `{}`",
819 span_note!(&mut err, span,
820 "associated type `{}` could derive from `{}`",
831 // Create a type from a path to an associated type.
832 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
833 // and item_segment is the path segment for D. We return a type and a def for
835 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
836 // parameter or Self.
837 pub fn associated_path_def_to_ty(&self,
842 item_segment: &hir::PathSegment)
845 let tcx = self.tcx();
846 let assoc_name = item_segment.name;
848 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
850 self.prohibit_type_params(slice::ref_slice(item_segment));
852 // Find the type of the associated item, and the trait where the associated
854 let bound = match (&ty.sty, ty_path_def) {
855 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
856 // `Self` in an impl of a trait - we have a concrete self type and a
858 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
859 Some(trait_ref) => trait_ref,
861 // A cycle error occurred, most likely.
862 return (tcx.types.err, Def::Err);
867 traits::supertraits(tcx, ty::Binder(trait_ref))
868 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
871 match self.one_bound_for_assoc_type(candidates,
873 &assoc_name.as_str(),
876 Err(ErrorReported) => return (tcx.types.err, Def::Err),
879 (&ty::TyParam(_), Def::SelfTy(Some(param_did), None)) |
880 (&ty::TyParam(_), Def::TyParam(param_did)) => {
881 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
883 Err(ErrorReported) => return (tcx.types.err, Def::Err),
887 // Don't print TyErr to the user.
888 if !ty.references_error() {
889 self.report_ambiguous_associated_type(span,
892 &assoc_name.as_str());
894 return (tcx.types.err, Def::Err);
898 let trait_did = bound.0.def_id;
899 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name)
900 .expect("missing associated type");
902 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
903 let ty = self.normalize_ty(span, ty);
905 let def = Def::AssociatedTy(item.def_id);
906 let def_scope = tcx.adjust(assoc_name, item.container.id(), ref_id).1;
907 if !item.vis.is_accessible_from(def_scope, tcx) {
908 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
909 tcx.sess.span_err(span, &msg);
911 tcx.check_stability(item.def_id, ref_id, span);
916 fn qpath_to_ty(&self,
918 opt_self_ty: Option<Ty<'tcx>>,
920 trait_segment: &hir::PathSegment,
921 item_segment: &hir::PathSegment)
924 let tcx = self.tcx();
925 let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
927 self.prohibit_type_params(slice::ref_slice(item_segment));
929 let self_ty = if let Some(ty) = opt_self_ty {
932 let path_str = tcx.item_path_str(trait_def_id);
933 self.report_ambiguous_associated_type(span,
936 &item_segment.name.as_str());
937 return tcx.types.err;
940 debug!("qpath_to_ty: self_type={:?}", self_ty);
942 let trait_ref = self.ast_path_to_mono_trait_ref(span,
947 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
949 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
952 pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
953 for segment in segments {
954 if let hir::ParenthesizedParameters(_) = segment.parameters {
955 self.prohibit_parenthesized_params(segment, false);
958 for typ in segment.parameters.types() {
959 struct_span_err!(self.tcx().sess, typ.span, E0109,
960 "type parameters are not allowed on this type")
961 .span_label(typ.span, "type parameter not allowed")
965 for lifetime in segment.parameters.lifetimes() {
966 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
967 "lifetime parameters are not allowed on this type")
968 .span_label(lifetime.span,
969 "lifetime parameter not allowed on this type")
973 for binding in segment.parameters.bindings() {
974 self.prohibit_projection(binding.span);
980 pub fn prohibit_parenthesized_params(&self, segment: &hir::PathSegment, emit_error: bool) {
981 if let hir::ParenthesizedParameters(ref data) = segment.parameters {
983 struct_span_err!(self.tcx().sess, data.span, E0214,
984 "parenthesized parameters may only be used with a trait")
985 .span_label(data.span, "only traits may use parentheses")
988 let msg = "parenthesized parameters may only be used with a trait".to_string();
989 self.tcx().sess.add_lint(PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
990 ast::CRATE_NODE_ID, data.span, msg);
995 pub fn prohibit_projection(&self, span: Span) {
996 let mut err = struct_span_err!(self.tcx().sess, span, E0229,
997 "associated type bindings are not allowed here");
998 err.span_label(span, "associated type not allowed here").emit();
1001 // Check a type Path and convert it to a Ty.
1002 pub fn def_to_ty(&self,
1003 opt_self_ty: Option<Ty<'tcx>>,
1005 permit_variants: bool)
1007 let tcx = self.tcx();
1009 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1010 path.def, opt_self_ty, path.segments);
1012 let span = path.span;
1014 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1015 assert_eq!(opt_self_ty, None);
1016 self.prohibit_type_params(path.segments.split_last().unwrap().1);
1017 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1019 Def::Variant(did) if permit_variants => {
1020 // Convert "variant type" as if it were a real type.
1021 // The resulting `Ty` is type of the variant's enum for now.
1022 assert_eq!(opt_self_ty, None);
1023 self.prohibit_type_params(path.segments.split_last().unwrap().1);
1024 self.ast_path_to_ty(span,
1025 tcx.parent_def_id(did).unwrap(),
1026 path.segments.last().unwrap())
1028 Def::TyParam(did) => {
1029 assert_eq!(opt_self_ty, None);
1030 self.prohibit_type_params(&path.segments);
1032 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1033 let item_id = tcx.hir.get_parent_node(node_id);
1034 let item_def_id = tcx.hir.local_def_id(item_id);
1035 let generics = tcx.generics_of(item_def_id);
1036 let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id).index];
1037 tcx.mk_param(index, tcx.hir.name(node_id))
1039 Def::SelfTy(_, Some(def_id)) => {
1040 // Self in impl (we know the concrete type).
1042 assert_eq!(opt_self_ty, None);
1043 self.prohibit_type_params(&path.segments);
1045 tcx.at(span).type_of(def_id)
1047 Def::SelfTy(Some(_), None) => {
1049 assert_eq!(opt_self_ty, None);
1050 self.prohibit_type_params(&path.segments);
1053 Def::AssociatedTy(def_id) => {
1054 self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1055 self.qpath_to_ty(span,
1058 &path.segments[path.segments.len()-2],
1059 path.segments.last().unwrap())
1061 Def::PrimTy(prim_ty) => {
1062 assert_eq!(opt_self_ty, None);
1063 self.prohibit_type_params(&path.segments);
1065 hir::TyBool => tcx.types.bool,
1066 hir::TyChar => tcx.types.char,
1067 hir::TyInt(it) => tcx.mk_mach_int(it),
1068 hir::TyUint(uit) => tcx.mk_mach_uint(uit),
1069 hir::TyFloat(ft) => tcx.mk_mach_float(ft),
1070 hir::TyStr => tcx.mk_str()
1074 self.set_tainted_by_errors();
1075 return self.tcx().types.err;
1077 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1081 /// Parses the programmer's textual representation of a type into our
1082 /// internal notion of a type.
1083 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1084 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1087 let tcx = self.tcx();
1089 let result_ty = match ast_ty.node {
1090 hir::TySlice(ref ty) => {
1091 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1093 hir::TyPtr(ref mt) => {
1094 tcx.mk_ptr(ty::TypeAndMut {
1095 ty: self.ast_ty_to_ty(&mt.ty),
1099 hir::TyRptr(ref region, ref mt) => {
1100 let r = self.ast_region_to_region(region, None);
1101 debug!("TyRef r={:?}", r);
1102 let t = self.ast_ty_to_ty(&mt.ty);
1103 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1108 hir::TyTup(ref fields) => {
1109 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1111 hir::TyBareFn(ref bf) => {
1112 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1113 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1115 // Find any late-bound regions declared in return type that do
1116 // not appear in the arguments. These are not wellformed.
1120 // for<'a> fn() -> &'a str <-- 'a is bad
1121 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1123 // Note that we do this check **here** and not in
1124 // `ty_of_bare_fn` because the latter is also used to make
1125 // the types for fn items, and we do not want to issue a
1126 // warning then. (Once we fix #32330, the regions we are
1127 // checking for here would be considered early bound
1129 let inputs = bare_fn_ty.inputs();
1130 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1131 &inputs.map_bound(|i| i.to_owned()));
1132 let output = bare_fn_ty.output();
1133 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1134 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1135 let br_name = match *br {
1136 ty::BrNamed(_, name) => name,
1139 bf.decl.output.span(),
1140 "anonymous bound region {:?} in return but not args",
1144 struct_span_err!(tcx.sess,
1147 "return type references lifetime `{}`, \
1148 which does not appear in the fn input types",
1152 tcx.mk_fn_ptr(bare_fn_ty)
1154 hir::TyTraitObject(ref bounds, ref lifetime) => {
1155 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1157 hir::TyImplTrait(_) => {
1158 // Figure out if we can allow an `impl Trait` here, by walking up
1159 // to a `fn` or inherent `impl` method, going only through `Ty`
1160 // or `TraitRef` nodes (as nothing else should be in types) and
1161 // ensuring that we reach the `fn`/method signature's return type.
1162 let mut node_id = ast_ty.id;
1163 let fn_decl = loop {
1164 let parent = tcx.hir.get_parent_node(node_id);
1165 match tcx.hir.get(parent) {
1166 hir::map::NodeItem(&hir::Item {
1167 node: hir::ItemFn(ref fn_decl, ..), ..
1168 }) => break Some(fn_decl),
1170 hir::map::NodeImplItem(&hir::ImplItem {
1171 node: hir::ImplItemKind::Method(ref sig, _), ..
1173 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1174 hir::ItemImpl(.., None, _, _) => {
1175 break Some(&sig.decl)
1181 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1187 let allow = fn_decl.map_or(false, |fd| {
1189 hir::DefaultReturn(_) => false,
1190 hir::Return(ref ty) => ty.id == node_id
1194 // Create the anonymized type.
1196 let def_id = tcx.hir.local_def_id(ast_ty.id);
1197 tcx.mk_anon(def_id, Substs::identity_for_item(tcx, def_id))
1199 span_err!(tcx.sess, ast_ty.span, E0562,
1200 "`impl Trait` not allowed outside of function \
1201 and inherent method return types");
1205 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1206 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1207 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1208 self.ast_ty_to_ty(qself)
1210 self.def_to_ty(opt_self_ty, path, false)
1212 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1213 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1214 let ty = self.ast_ty_to_ty(qself);
1216 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1221 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1223 hir::TyArray(ref ty, length) => {
1224 if let Ok(length) = eval_length(tcx, length, "array length") {
1225 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1227 self.tcx().types.err
1230 hir::TyTypeof(ref _e) => {
1231 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1232 "`typeof` is a reserved keyword but unimplemented")
1233 .span_label(ast_ty.span, "reserved keyword")
1239 // TyInfer also appears as the type of arguments or return
1240 // values in a ExprClosure, or as
1241 // the type of local variables. Both of these cases are
1242 // handled specially and will not descend into this routine.
1243 self.ty_infer(ast_ty.span)
1253 pub fn ty_of_arg(&self,
1255 expected_ty: Option<Ty<'tcx>>)
1259 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1260 hir::TyInfer => self.ty_infer(ty.span),
1261 _ => self.ast_ty_to_ty(ty),
1265 pub fn ty_of_fn(&self,
1266 unsafety: hir::Unsafety,
1269 -> ty::PolyFnSig<'tcx> {
1272 let input_tys: Vec<Ty> =
1273 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1275 let output_ty = match decl.output {
1276 hir::Return(ref output) => self.ast_ty_to_ty(output),
1277 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1280 debug!("ty_of_fn: output_ty={:?}", output_ty);
1282 ty::Binder(self.tcx().mk_fn_sig(
1283 input_tys.into_iter(),
1291 pub fn ty_of_closure(&self,
1292 unsafety: hir::Unsafety,
1295 expected_sig: Option<ty::FnSig<'tcx>>)
1296 -> ty::PolyFnSig<'tcx>
1298 debug!("ty_of_closure(expected_sig={:?})",
1301 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1302 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1303 // no guarantee that the correct number of expected args
1305 if i < e.inputs().len() {
1311 self.ty_of_arg(a, expected_arg_ty)
1314 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1316 let is_infer = match decl.output {
1317 hir::Return(ref output) if output.node == hir::TyInfer => true,
1318 hir::DefaultReturn(..) => true,
1322 let output_ty = match decl.output {
1323 _ if is_infer && expected_ret_ty.is_some() =>
1324 expected_ret_ty.unwrap(),
1325 _ if is_infer => self.ty_infer(decl.output.span()),
1326 hir::Return(ref output) =>
1327 self.ast_ty_to_ty(&output),
1328 hir::DefaultReturn(..) => bug!(),
1331 debug!("ty_of_closure: output_ty={:?}", output_ty);
1333 ty::Binder(self.tcx().mk_fn_sig(
1342 /// Given the bounds on an object, determines what single region bound (if any) we can
1343 /// use to summarize this type. The basic idea is that we will use the bound the user
1344 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1345 /// for region bounds. It may be that we can derive no bound at all, in which case
1346 /// we return `None`.
1347 fn compute_object_lifetime_bound(&self,
1349 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1350 -> Option<ty::Region<'tcx>> // if None, use the default
1352 let tcx = self.tcx();
1354 debug!("compute_opt_region_bound(existential_predicates={:?})",
1355 existential_predicates);
1357 // No explicit region bound specified. Therefore, examine trait
1358 // bounds and see if we can derive region bounds from those.
1359 let derived_region_bounds =
1360 object_region_bounds(tcx, existential_predicates);
1362 // If there are no derived region bounds, then report back that we
1363 // can find no region bound. The caller will use the default.
1364 if derived_region_bounds.is_empty() {
1368 // If any of the derived region bounds are 'static, that is always
1370 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1371 return Some(tcx.types.re_static);
1374 // Determine whether there is exactly one unique region in the set
1375 // of derived region bounds. If so, use that. Otherwise, report an
1377 let r = derived_region_bounds[0];
1378 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1379 span_err!(tcx.sess, span, E0227,
1380 "ambiguous lifetime bound, explicit lifetime bound required");
1386 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1387 /// remaining general trait bounds.
1388 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1389 trait_bounds: &'b [hir::PolyTraitRef])
1390 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1392 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1393 match bound.trait_ref.path.def {
1394 Def::Trait(trait_did) => {
1395 // Checks whether `trait_did` refers to one of the builtin
1396 // traits, like `Send`, and adds it to `auto_traits` if so.
1397 if Some(trait_did) == tcx.lang_items.send_trait() ||
1398 Some(trait_did) == tcx.lang_items.sync_trait() {
1399 let segments = &bound.trait_ref.path.segments;
1400 let parameters = &segments[segments.len() - 1].parameters;
1401 if !parameters.types().is_empty() {
1402 check_type_argument_count(tcx, bound.trait_ref.path.span,
1403 parameters.types().len(), &[]);
1405 if !parameters.lifetimes().is_empty() {
1406 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1407 parameters.lifetimes().len(), 0);
1418 let auto_traits = auto_traits.into_iter().map(|tr| {
1419 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1424 }).collect::<Vec<_>>();
1426 (auto_traits, trait_bounds)
1429 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1430 ty_param_defs: &[ty::TypeParameterDef]) {
1431 let accepted = ty_param_defs.len();
1432 let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1433 if supplied < required {
1434 let expected = if required < accepted {
1439 let arguments_plural = if required == 1 { "" } else { "s" };
1441 struct_span_err!(tcx.sess, span, E0243,
1442 "wrong number of type arguments: {} {}, found {}",
1443 expected, required, supplied)
1445 format!("{} {} type argument{}",
1450 } else if supplied > accepted {
1451 let expected = if required < accepted {
1452 format!("expected at most {}", accepted)
1454 format!("expected {}", accepted)
1456 let arguments_plural = if accepted == 1 { "" } else { "s" };
1458 struct_span_err!(tcx.sess, span, E0244,
1459 "wrong number of type arguments: {}, found {}",
1463 format!("{} type argument{}",
1464 if accepted == 0 { "expected no" } else { &expected },
1471 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1472 let label = if number < expected {
1474 format!("expected {} lifetime parameter", expected)
1476 format!("expected {} lifetime parameters", expected)
1479 let additional = number - expected;
1480 if additional == 1 {
1481 "unexpected lifetime parameter".to_string()
1483 format!("{} unexpected lifetime parameters", additional)
1486 struct_span_err!(tcx.sess, span, E0107,
1487 "wrong number of lifetime parameters: expected {}, found {}",
1489 .span_label(span, label)
1493 // A helper struct for conveniently grouping a set of bounds which we pass to
1494 // and return from functions in multiple places.
1495 #[derive(PartialEq, Eq, Clone, Debug)]
1496 pub struct Bounds<'tcx> {
1497 pub region_bounds: Vec<ty::Region<'tcx>>,
1498 pub implicitly_sized: bool,
1499 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1500 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1503 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1504 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1505 -> Vec<ty::Predicate<'tcx>>
1507 let mut vec = Vec::new();
1509 // If it could be sized, and is, add the sized predicate
1510 if self.implicitly_sized {
1511 if let Some(sized) = tcx.lang_items.sized_trait() {
1512 let trait_ref = ty::TraitRef {
1514 substs: tcx.mk_substs_trait(param_ty, &[])
1516 vec.push(trait_ref.to_predicate());
1520 for ®ion_bound in &self.region_bounds {
1521 // account for the binder being introduced below; no need to shift `param_ty`
1522 // because, at present at least, it can only refer to early-bound regions
1523 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1524 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1527 for bound_trait_ref in &self.trait_bounds {
1528 vec.push(bound_trait_ref.to_predicate());
1531 for projection in &self.projection_bounds {
1532 vec.push(projection.to_predicate());
1539 pub enum ExplicitSelf<'tcx> {
1541 ByReference(ty::Region<'tcx>, hir::Mutability),
1545 impl<'tcx> ExplicitSelf<'tcx> {
1546 /// We wish to (for now) categorize an explicit self
1547 /// declaration like `self: SomeType` into either `self`,
1548 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1549 /// by some simple pattern matching. A more precise check
1550 /// is done later in `check_method_self_type()`.
1555 /// impl Foo for &T {
1556 /// // Legal declarations:
1557 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1558 /// fn method2(self: &T); // ExplicitSelf::ByValue
1559 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1561 /// // Invalid cases will be caught later by `check_method_self_type`:
1562 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1566 /// To do the check we just count the number of "modifiers"
1567 /// on each type and compare them. If they are the same or
1568 /// the impl has more, we call it "by value". Otherwise, we
1569 /// look at the outermost modifier on the method decl and
1570 /// call it by-ref, by-box as appropriate. For method1, for
1571 /// example, the impl type has one modifier, but the method
1572 /// type has two, so we end up with
1573 /// ExplicitSelf::ByReference.
1574 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1575 self_arg_ty: Ty<'tcx>)
1576 -> ExplicitSelf<'tcx> {
1577 fn count_modifiers(ty: Ty) -> usize {
1579 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1580 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1585 let impl_modifiers = count_modifiers(untransformed_self_ty);
1586 let method_modifiers = count_modifiers(self_arg_ty);
1588 if impl_modifiers >= method_modifiers {
1589 ExplicitSelf::ByValue
1591 match self_arg_ty.sty {
1592 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1593 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1594 _ => ExplicitSelf::ByValue,