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_back::slice;
26 use require_c_abi_if_variadic;
27 use util::common::{ErrorReported, FN_OUTPUT_NAME};
28 use util::nodemap::FxHashSet;
31 use syntax::{abi, ast};
32 use syntax::feature_gate::{GateIssue, emit_feature_err};
33 use syntax::symbol::Symbol;
36 pub trait AstConv<'gcx, 'tcx> {
37 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
39 /// Returns the set of bounds in scope for the type parameter with
41 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
42 -> ty::GenericPredicates<'tcx>;
44 /// What lifetime should we use when a lifetime is omitted (and not elided)?
45 fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
46 -> Option<ty::Region<'tcx>>;
48 /// What type should we use when a type is omitted?
49 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
51 /// Same as ty_infer, but with a known type parameter definition.
52 fn ty_infer_for_def(&self,
53 _def: &ty::TypeParameterDef,
54 _substs: &[Kind<'tcx>],
55 span: Span) -> Ty<'tcx> {
59 /// Projecting an associated type from a (potentially)
60 /// higher-ranked trait reference is more complicated, because of
61 /// the possibility of late-bound regions appearing in the
62 /// associated type binding. This is not legal in function
63 /// signatures for that reason. In a function body, we can always
64 /// handle it because we can use inference variables to remove the
65 /// late-bound regions.
66 fn projected_ty_from_poly_trait_ref(&self,
68 poly_trait_ref: ty::PolyTraitRef<'tcx>,
72 /// Normalize an associated type coming from the user.
73 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
75 /// Invoked when we encounter an error from some prior pass
76 /// (e.g. resolve) that is translated into a ty-error. This is
77 /// used to help suppress derived errors typeck might otherwise
79 fn set_tainted_by_errors(&self);
82 struct ConvertedBinding<'tcx> {
88 /// Dummy type used for the `Self` of a `TraitRef` created for converting
89 /// a trait object, and which gets removed in `ExistentialTraitRef`.
90 /// This type must not appear anywhere in other converted types.
91 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
93 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
94 pub fn ast_region_to_region(&self,
95 lifetime: &hir::Lifetime,
96 def: Option<&ty::RegionParameterDef>)
100 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
101 Some(&rl::Region::Static) => {
105 Some(&rl::Region::LateBound(debruijn, id)) => {
106 let name = tcx.hir.name(id);
107 tcx.mk_region(ty::ReLateBound(debruijn,
108 ty::BrNamed(tcx.hir.local_def_id(id), name)))
111 Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
112 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
115 Some(&rl::Region::EarlyBound(index, id)) => {
116 let name = tcx.hir.name(id);
117 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
118 def_id: tcx.hir.local_def_id(id),
124 Some(&rl::Region::Free(scope, id)) => {
125 let name = tcx.hir.name(id);
126 tcx.mk_region(ty::ReFree(ty::FreeRegion {
128 bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name)
131 // (*) -- not late-bound, won't change
135 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
139 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
146 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
147 /// returns an appropriate set of substitutions for this particular reference to `I`.
148 pub fn ast_path_substs_for_ty(&self,
151 item_segment: &hir::PathSegment)
152 -> &'tcx Substs<'tcx>
154 let tcx = self.tcx();
156 match item_segment.parameters {
157 hir::AngleBracketedParameters(_) => {}
158 hir::ParenthesizedParameters(..) => {
159 struct_span_err!(tcx.sess, span, E0214,
160 "parenthesized parameters may only be used with a trait")
161 .span_label(span, "only traits may use parentheses")
164 return Substs::for_item(tcx, def_id, |_, _| {
172 let (substs, assoc_bindings) =
173 self.create_substs_for_ast_path(span,
175 &item_segment.parameters,
178 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
183 /// Given the type/region arguments provided to some path (along with
184 /// an implicit Self, if this is a trait reference) returns the complete
185 /// set of substitutions. This may involve applying defaulted type parameters.
187 /// Note that the type listing given here is *exactly* what the user provided.
188 fn create_substs_for_ast_path(&self,
191 parameters: &hir::PathParameters,
192 self_ty: Option<Ty<'tcx>>)
193 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
195 let tcx = self.tcx();
197 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
199 def_id, self_ty, parameters);
201 let (lifetimes, num_types_provided, infer_types) = match *parameters {
202 hir::AngleBracketedParameters(ref data) => {
203 (&data.lifetimes[..], data.types.len(), data.infer_types)
205 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
208 // If the type is parameterized by this region, then replace this
209 // region with the current anon region binding (in other words,
210 // whatever & would get replaced with).
211 let decl_generics = tcx.generics_of(def_id);
212 let expected_num_region_params = decl_generics.regions.len();
213 let supplied_num_region_params = lifetimes.len();
214 if expected_num_region_params != supplied_num_region_params {
215 report_lifetime_number_error(tcx, span,
216 supplied_num_region_params,
217 expected_num_region_params);
220 // If a self-type was declared, one should be provided.
221 assert_eq!(decl_generics.has_self, self_ty.is_some());
223 // Check the number of type parameters supplied by the user.
224 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
225 if !infer_types || num_types_provided > ty_param_defs.len() {
226 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
229 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
230 let default_needs_object_self = |p: &ty::TypeParameterDef| {
231 if is_object && p.has_default {
232 if tcx.at(span).type_of(p.def_id).has_self_ty() {
233 // There is no suitable inference default for a type parameter
234 // that references self, in an object type.
242 let mut output_assoc_binding = None;
243 let substs = Substs::for_item(tcx, def_id, |def, _| {
244 let i = def.index as usize - self_ty.is_some() as usize;
245 if let Some(lifetime) = lifetimes.get(i) {
246 self.ast_region_to_region(lifetime, Some(def))
251 let i = def.index as usize;
253 // Handle Self first, so we can adjust the index to match the AST.
254 if let (0, Some(ty)) = (i, self_ty) {
258 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
259 if i < num_types_provided {
260 // A provided type parameter.
262 hir::AngleBracketedParameters(ref data) => {
263 self.ast_ty_to_ty(&data.types[i])
265 hir::ParenthesizedParameters(ref data) => {
267 let (ty, assoc) = self.convert_parenthesized_parameters(data);
268 output_assoc_binding = Some(assoc);
272 } else if infer_types {
273 // No type parameters were provided, we can infer all.
274 let ty_var = if !default_needs_object_self(def) {
275 self.ty_infer_for_def(def, substs, span)
280 } else if def.has_default {
281 // No type parameter provided, but a default exists.
283 // If we are converting an object type, then the
284 // `Self` parameter is unknown. However, some of the
285 // other type parameters may reference `Self` in their
286 // defaults. This will lead to an ICE if we are not
288 if default_needs_object_self(def) {
289 struct_span_err!(tcx.sess, span, E0393,
290 "the type parameter `{}` must be explicitly specified",
292 .span_label(span, format!("missing reference to `{}`", def.name))
293 .note(&format!("because of the default `Self` reference, \
294 type parameters must be specified on object types"))
298 // This is a default type parameter.
301 tcx.at(span).type_of(def.def_id)
302 .subst_spanned(tcx, substs, Some(span))
306 // We've already errored above about the mismatch.
311 let assoc_bindings = match *parameters {
312 hir::AngleBracketedParameters(ref data) => {
313 data.bindings.iter().map(|b| {
316 ty: self.ast_ty_to_ty(&b.ty),
321 hir::ParenthesizedParameters(ref data) => {
322 vec![output_assoc_binding.unwrap_or_else(|| {
323 // This is an error condition, but we should
324 // get the associated type binding anyway.
325 self.convert_parenthesized_parameters(data).1
330 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
331 decl_generics, self_ty, substs);
333 (substs, assoc_bindings)
336 fn convert_parenthesized_parameters(&self,
337 data: &hir::ParenthesizedParameterData)
338 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
340 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
341 self.ast_ty_to_ty(a_t)
344 let (output, output_span) = match data.output {
345 Some(ref output_ty) => {
346 (self.ast_ty_to_ty(output_ty), output_ty.span)
349 (self.tcx().mk_nil(), data.span)
353 let output_binding = ConvertedBinding {
354 item_name: Symbol::intern(FN_OUTPUT_NAME),
359 (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
362 /// Instantiates the path for the given trait reference, assuming that it's
363 /// bound to a valid trait type. Returns the def_id for the defining trait.
364 /// Fails if the type is a type other than a trait type.
366 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
367 /// are disallowed. Otherwise, they are pushed onto the vector given.
368 pub fn instantiate_mono_trait_ref(&self,
369 trait_ref: &hir::TraitRef,
371 -> ty::TraitRef<'tcx>
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 let (substs, assoc_bindings) =
406 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
409 trait_ref.path.segments.last().unwrap());
410 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
412 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
413 // specify type to assert that error was already reported in Err case:
414 let predicate: Result<_, ErrorReported> =
415 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
418 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
421 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
422 trait_ref, poly_projections, poly_trait_ref);
426 fn ast_path_to_mono_trait_ref(&self,
430 trait_segment: &hir::PathSegment)
431 -> ty::TraitRef<'tcx>
433 let (substs, assoc_bindings) =
434 self.create_substs_for_ast_trait_ref(span,
438 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
439 ty::TraitRef::new(trait_def_id, substs)
442 fn create_substs_for_ast_trait_ref(&self,
446 trait_segment: &hir::PathSegment)
447 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
449 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
452 let trait_def = self.tcx().trait_def(trait_def_id);
454 match trait_segment.parameters {
455 hir::AngleBracketedParameters(_) => {
456 // For now, require that parenthetical notation be used
457 // only with `Fn()` etc.
458 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
459 emit_feature_err(&self.tcx().sess.parse_sess,
460 "unboxed_closures", span, GateIssue::Language,
462 the precise format of `Fn`-family traits' \
463 type parameters is subject to change. \
464 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
467 hir::ParenthesizedParameters(_) => {
468 // For now, require that parenthetical notation be used
469 // only with `Fn()` etc.
470 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
471 emit_feature_err(&self.tcx().sess.parse_sess,
472 "unboxed_closures", span, GateIssue::Language,
474 parenthetical notation is only stable when used with `Fn`-family traits");
479 self.create_substs_for_ast_path(span,
481 &trait_segment.parameters,
485 fn trait_defines_associated_type_named(&self,
487 assoc_name: ast::Name)
490 self.tcx().associated_items(trait_def_id).any(|item| {
491 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
495 fn ast_type_binding_to_poly_projection_predicate(
497 _path_id: ast::NodeId,
498 trait_ref: ty::PolyTraitRef<'tcx>,
499 binding: &ConvertedBinding<'tcx>)
500 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
502 let tcx = self.tcx();
504 // Given something like `U : SomeTrait<T=X>`, we want to produce a
505 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
506 // subtle in the event that `T` is defined in a supertrait of
507 // `SomeTrait`, because in that case we need to upcast.
509 // That is, consider this case:
512 // trait SubTrait : SuperTrait<int> { }
513 // trait SuperTrait<A> { type T; }
515 // ... B : SubTrait<T=foo> ...
518 // We want to produce `<B as SuperTrait<int>>::T == foo`.
520 // Find any late-bound regions declared in `ty` that are not
521 // declared in the trait-ref. These are not wellformed.
525 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
526 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
527 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
528 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
529 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
530 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
531 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
532 let br_name = match *br {
533 ty::BrNamed(_, name) => name,
537 "anonymous bound region {:?} in binding but not trait ref",
541 struct_span_err!(tcx.sess,
544 "binding for associated type `{}` references lifetime `{}`, \
545 which does not appear in the trait input types",
546 binding.item_name, br_name)
550 // Simple case: X is defined in the current trait.
551 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
552 return Ok(trait_ref.map_bound(|trait_ref| {
553 ty::ProjectionPredicate {
554 projection_ty: ty::ProjectionTy {
555 trait_ref: trait_ref,
556 item_name: binding.item_name,
563 // Otherwise, we have to walk through the supertraits to find
566 traits::supertraits(tcx, trait_ref.clone())
567 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
569 let candidate = self.one_bound_for_assoc_type(candidates,
570 &trait_ref.to_string(),
571 &binding.item_name.as_str(),
574 Ok(candidate.map_bound(|trait_ref| {
575 ty::ProjectionPredicate {
576 projection_ty: ty::ProjectionTy {
577 trait_ref: trait_ref,
578 item_name: binding.item_name,
585 fn ast_path_to_ty(&self,
588 item_segment: &hir::PathSegment)
591 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
594 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
598 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
599 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
600 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
601 -> ty::ExistentialTraitRef<'tcx> {
602 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
603 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
606 fn conv_object_ty_poly_trait_ref(&self,
608 trait_bounds: &[hir::PolyTraitRef],
609 lifetime: &hir::Lifetime)
612 let tcx = self.tcx();
614 if trait_bounds.is_empty() {
615 span_err!(tcx.sess, span, E0224,
616 "at least one non-builtin trait is required for an object type");
617 return tcx.types.err;
620 let mut projection_bounds = vec![];
621 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
622 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
624 &mut projection_bounds);
626 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
628 if !trait_bounds.is_empty() {
629 let b = &trait_bounds[0];
630 let span = b.trait_ref.path.span;
631 struct_span_err!(self.tcx().sess, span, E0225,
632 "only Send/Sync traits can be used as additional traits in a trait object")
633 .span_label(span, "non-Send/Sync additional trait")
637 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
638 let existential_principal = principal.map_bound(|trait_ref| {
639 self.trait_ref_to_existential(trait_ref)
641 let existential_projections = projection_bounds.iter().map(|bound| {
642 bound.map_bound(|b| {
643 let p = b.projection_ty;
644 ty::ExistentialProjection {
645 trait_ref: self.trait_ref_to_existential(p.trait_ref),
646 item_name: p.item_name,
652 // check that there are no gross object safety violations,
653 // most importantly, that the supertraits don't contain Self,
655 let object_safety_violations =
656 tcx.astconv_object_safety_violations(principal.def_id());
657 if !object_safety_violations.is_empty() {
658 tcx.report_object_safety_error(
659 span, principal.def_id(), object_safety_violations)
661 return tcx.types.err;
664 let mut associated_types = FxHashSet::default();
665 for tr in traits::supertraits(tcx, principal) {
666 associated_types.extend(tcx.associated_items(tr.def_id())
667 .filter(|item| item.kind == ty::AssociatedKind::Type)
668 .map(|item| (tr.def_id(), item.name)));
671 for projection_bound in &projection_bounds {
672 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
673 projection_bound.0.projection_ty.item_name);
674 associated_types.remove(&pair);
677 for (trait_def_id, name) in associated_types {
678 struct_span_err!(tcx.sess, span, E0191,
679 "the value of the associated type `{}` (from the trait `{}`) must be specified",
681 tcx.item_path_str(trait_def_id))
682 .span_label(span, format!(
683 "missing associated type `{}` value", name))
688 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
689 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
690 .chain(existential_projections
691 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
692 .collect::<AccumulateVec<[_; 8]>>();
693 v.sort_by(|a, b| a.cmp(tcx, b));
694 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
697 // Explicitly specified region bound. Use that.
698 let region_bound = if !lifetime.is_elided() {
699 self.ast_region_to_region(lifetime, None)
701 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
702 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
703 self.ast_region_to_region(lifetime, None)
705 self.re_infer(span, None).unwrap_or_else(|| {
706 span_err!(tcx.sess, span, E0228,
707 "the lifetime bound for this object type cannot be deduced \
708 from context; please supply an explicit bound");
715 debug!("region_bound: {:?}", region_bound);
717 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
718 debug!("trait_object_type: {:?}", ty);
722 fn report_ambiguous_associated_type(&self,
727 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
728 .span_label(span, "ambiguous associated type")
729 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
730 type_str, trait_str, name))
735 // Search for a bound on a type parameter which includes the associated item
736 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
737 // This function will fail if there are no suitable bounds or there is
739 fn find_bound_for_assoc_item(&self,
740 ty_param_def_id: DefId,
741 assoc_name: ast::Name,
743 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
745 let tcx = self.tcx();
747 let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
748 .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
750 // Check that there is exactly one way to find an associated type with the
752 let suitable_bounds =
753 traits::transitive_bounds(tcx, &bounds)
754 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
756 let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
757 let param_name = tcx.hir.ty_param_name(param_node_id);
758 self.one_bound_for_assoc_type(suitable_bounds,
759 ¶m_name.as_str(),
760 &assoc_name.as_str(),
765 // Checks that bounds contains exactly one element and reports appropriate
767 fn one_bound_for_assoc_type<I>(&self,
772 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
773 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
775 let bound = match bounds.next() {
776 Some(bound) => bound,
778 struct_span_err!(self.tcx().sess, span, E0220,
779 "associated type `{}` not found for `{}`",
782 .span_label(span, format!("associated type `{}` not found", assoc_name))
784 return Err(ErrorReported);
788 if let Some(bound2) = bounds.next() {
789 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
790 let mut err = struct_span_err!(
791 self.tcx().sess, span, E0221,
792 "ambiguous associated type `{}` in bounds of `{}`",
795 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
797 for bound in bounds {
798 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
799 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
801 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
803 if let Some(span) = bound_span {
804 err.span_label(span, format!("ambiguous `{}` from `{}`",
808 span_note!(&mut err, span,
809 "associated type `{}` could derive from `{}`",
820 // Create a type from a path to an associated type.
821 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
822 // and item_segment is the path segment for D. We return a type and a def for
824 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
825 // parameter or Self.
826 pub fn associated_path_def_to_ty(&self,
831 item_segment: &hir::PathSegment)
834 let tcx = self.tcx();
835 let assoc_name = item_segment.name;
837 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
839 self.prohibit_type_params(slice::ref_slice(item_segment));
841 // Find the type of the associated item, and the trait where the associated
843 let bound = match (&ty.sty, ty_path_def) {
844 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
845 // `Self` in an impl of a trait - we have a concrete self type and a
847 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
848 Some(trait_ref) => trait_ref,
850 // A cycle error occurred, most likely.
851 return (tcx.types.err, Def::Err);
856 traits::supertraits(tcx, ty::Binder(trait_ref))
857 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
860 match self.one_bound_for_assoc_type(candidates,
862 &assoc_name.as_str(),
865 Err(ErrorReported) => return (tcx.types.err, Def::Err),
868 (&ty::TyParam(_), Def::SelfTy(Some(param_did), None)) |
869 (&ty::TyParam(_), Def::TyParam(param_did)) => {
870 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
872 Err(ErrorReported) => return (tcx.types.err, Def::Err),
876 // Don't print TyErr to the user.
877 if !ty.references_error() {
878 self.report_ambiguous_associated_type(span,
881 &assoc_name.as_str());
883 return (tcx.types.err, Def::Err);
887 let trait_did = bound.0.def_id;
888 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
889 let ty = self.normalize_ty(span, ty);
891 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name)
892 .expect("missing associated type");
893 let def = Def::AssociatedTy(item.def_id);
894 if !tcx.vis_is_accessible_from(item.vis, ref_id) {
895 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
896 tcx.sess.span_err(span, &msg);
898 tcx.check_stability(item.def_id, ref_id, span);
903 fn qpath_to_ty(&self,
905 opt_self_ty: Option<Ty<'tcx>>,
907 trait_segment: &hir::PathSegment,
908 item_segment: &hir::PathSegment)
911 let tcx = self.tcx();
913 self.prohibit_type_params(slice::ref_slice(item_segment));
915 let self_ty = if let Some(ty) = opt_self_ty {
918 let path_str = tcx.item_path_str(trait_def_id);
919 self.report_ambiguous_associated_type(span,
922 &item_segment.name.as_str());
923 return tcx.types.err;
926 debug!("qpath_to_ty: self_type={:?}", self_ty);
928 let trait_ref = self.ast_path_to_mono_trait_ref(span,
933 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
935 self.normalize_ty(span, tcx.mk_projection(trait_ref, item_segment.name))
938 pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
939 for segment in segments {
940 for typ in segment.parameters.types() {
941 struct_span_err!(self.tcx().sess, typ.span, E0109,
942 "type parameters are not allowed on this type")
943 .span_label(typ.span, "type parameter not allowed")
947 for lifetime in segment.parameters.lifetimes() {
948 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
949 "lifetime parameters are not allowed on this type")
950 .span_label(lifetime.span,
951 "lifetime parameter not allowed on this type")
955 for binding in segment.parameters.bindings() {
956 self.prohibit_projection(binding.span);
962 pub fn prohibit_projection(&self, span: Span) {
963 let mut err = struct_span_err!(self.tcx().sess, span, E0229,
964 "associated type bindings are not allowed here");
965 err.span_label(span, "associate type not allowed here").emit();
968 // Check a type Path and convert it to a Ty.
969 pub fn def_to_ty(&self,
970 opt_self_ty: Option<Ty<'tcx>>,
972 permit_variants: bool)
974 let tcx = self.tcx();
976 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
977 path.def, opt_self_ty, path.segments);
979 let span = path.span;
981 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
982 assert_eq!(opt_self_ty, None);
983 self.prohibit_type_params(path.segments.split_last().unwrap().1);
984 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
986 Def::Variant(did) if permit_variants => {
987 // Convert "variant type" as if it were a real type.
988 // The resulting `Ty` is type of the variant's enum for now.
989 assert_eq!(opt_self_ty, None);
990 self.prohibit_type_params(path.segments.split_last().unwrap().1);
991 self.ast_path_to_ty(span,
992 tcx.parent_def_id(did).unwrap(),
993 path.segments.last().unwrap())
995 Def::TyParam(did) => {
996 assert_eq!(opt_self_ty, None);
997 self.prohibit_type_params(&path.segments);
999 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1000 let item_id = tcx.hir.get_parent_node(node_id);
1001 let item_def_id = tcx.hir.local_def_id(item_id);
1002 let generics = tcx.generics_of(item_def_id);
1003 let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id).index];
1004 tcx.mk_param(index, tcx.hir.name(node_id))
1006 Def::SelfTy(_, Some(def_id)) => {
1007 // Self in impl (we know the concrete type).
1009 assert_eq!(opt_self_ty, None);
1010 self.prohibit_type_params(&path.segments);
1012 tcx.at(span).type_of(def_id)
1014 Def::SelfTy(Some(_), None) => {
1016 assert_eq!(opt_self_ty, None);
1017 self.prohibit_type_params(&path.segments);
1020 Def::AssociatedTy(def_id) => {
1021 self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1022 let trait_did = tcx.parent_def_id(def_id).unwrap();
1023 self.qpath_to_ty(span,
1026 &path.segments[path.segments.len()-2],
1027 path.segments.last().unwrap())
1029 Def::PrimTy(prim_ty) => {
1030 assert_eq!(opt_self_ty, None);
1031 self.prohibit_type_params(&path.segments);
1033 hir::TyBool => tcx.types.bool,
1034 hir::TyChar => tcx.types.char,
1035 hir::TyInt(it) => tcx.mk_mach_int(it),
1036 hir::TyUint(uit) => tcx.mk_mach_uint(uit),
1037 hir::TyFloat(ft) => tcx.mk_mach_float(ft),
1038 hir::TyStr => tcx.mk_str()
1042 self.set_tainted_by_errors();
1043 return self.tcx().types.err;
1045 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1049 /// Parses the programmer's textual representation of a type into our
1050 /// internal notion of a type.
1051 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1052 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1055 let tcx = self.tcx();
1057 let result_ty = match ast_ty.node {
1058 hir::TySlice(ref ty) => {
1059 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1061 hir::TyPtr(ref mt) => {
1062 tcx.mk_ptr(ty::TypeAndMut {
1063 ty: self.ast_ty_to_ty(&mt.ty),
1067 hir::TyRptr(ref region, ref mt) => {
1068 let r = self.ast_region_to_region(region, None);
1069 debug!("TyRef r={:?}", r);
1070 let t = self.ast_ty_to_ty(&mt.ty);
1071 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1076 hir::TyTup(ref fields) => {
1077 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1079 hir::TyBareFn(ref bf) => {
1080 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1081 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1083 // Find any late-bound regions declared in return type that do
1084 // not appear in the arguments. These are not wellformed.
1088 // for<'a> fn() -> &'a str <-- 'a is bad
1089 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1091 // Note that we do this check **here** and not in
1092 // `ty_of_bare_fn` because the latter is also used to make
1093 // the types for fn items, and we do not want to issue a
1094 // warning then. (Once we fix #32330, the regions we are
1095 // checking for here would be considered early bound
1097 let inputs = bare_fn_ty.inputs();
1098 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1099 &inputs.map_bound(|i| i.to_owned()));
1100 let output = bare_fn_ty.output();
1101 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1102 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1103 let br_name = match *br {
1104 ty::BrNamed(_, name) => name,
1107 bf.decl.output.span(),
1108 "anonymous bound region {:?} in return but not args",
1112 struct_span_err!(tcx.sess,
1115 "return type references lifetime `{}`, \
1116 which does not appear in the fn input types",
1120 tcx.mk_fn_ptr(bare_fn_ty)
1122 hir::TyTraitObject(ref bounds, ref lifetime) => {
1123 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1125 hir::TyImplTrait(_) => {
1126 // Figure out if we can allow an `impl Trait` here, by walking up
1127 // to a `fn` or inherent `impl` method, going only through `Ty`
1128 // or `TraitRef` nodes (as nothing else should be in types) and
1129 // ensuring that we reach the `fn`/method signature's return type.
1130 let mut node_id = ast_ty.id;
1131 let fn_decl = loop {
1132 let parent = tcx.hir.get_parent_node(node_id);
1133 match tcx.hir.get(parent) {
1134 hir::map::NodeItem(&hir::Item {
1135 node: hir::ItemFn(ref fn_decl, ..), ..
1136 }) => break Some(fn_decl),
1138 hir::map::NodeImplItem(&hir::ImplItem {
1139 node: hir::ImplItemKind::Method(ref sig, _), ..
1141 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1142 hir::ItemImpl(.., None, _, _) => {
1143 break Some(&sig.decl)
1149 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1155 let allow = fn_decl.map_or(false, |fd| {
1157 hir::DefaultReturn(_) => false,
1158 hir::Return(ref ty) => ty.id == node_id
1162 // Create the anonymized type.
1164 let def_id = tcx.hir.local_def_id(ast_ty.id);
1165 tcx.mk_anon(def_id, Substs::identity_for_item(tcx, def_id))
1167 span_err!(tcx.sess, ast_ty.span, E0562,
1168 "`impl Trait` not allowed outside of function \
1169 and inherent method return types");
1173 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1174 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1175 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1176 self.ast_ty_to_ty(qself)
1178 self.def_to_ty(opt_self_ty, path, false)
1180 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1181 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1182 let ty = self.ast_ty_to_ty(qself);
1184 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1189 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1191 hir::TyArray(ref ty, length) => {
1192 if let Ok(length) = eval_length(tcx, length, "array length") {
1193 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1195 self.tcx().types.err
1198 hir::TyTypeof(ref _e) => {
1199 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1200 "`typeof` is a reserved keyword but unimplemented")
1201 .span_label(ast_ty.span, "reserved keyword")
1207 // TyInfer also appears as the type of arguments or return
1208 // values in a ExprClosure, or as
1209 // the type of local variables. Both of these cases are
1210 // handled specially and will not descend into this routine.
1211 self.ty_infer(ast_ty.span)
1221 pub fn ty_of_arg(&self,
1223 expected_ty: Option<Ty<'tcx>>)
1227 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1228 hir::TyInfer => self.ty_infer(ty.span),
1229 _ => self.ast_ty_to_ty(ty),
1233 pub fn ty_of_fn(&self,
1234 unsafety: hir::Unsafety,
1237 -> ty::PolyFnSig<'tcx> {
1240 let input_tys: Vec<Ty> =
1241 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1243 let output_ty = match decl.output {
1244 hir::Return(ref output) => self.ast_ty_to_ty(output),
1245 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1248 debug!("ty_of_fn: output_ty={:?}", output_ty);
1250 ty::Binder(self.tcx().mk_fn_sig(
1251 input_tys.into_iter(),
1259 pub fn ty_of_closure(&self,
1260 unsafety: hir::Unsafety,
1263 expected_sig: Option<ty::FnSig<'tcx>>)
1264 -> ty::PolyFnSig<'tcx>
1266 debug!("ty_of_closure(expected_sig={:?})",
1269 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1270 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1271 // no guarantee that the correct number of expected args
1273 if i < e.inputs().len() {
1279 self.ty_of_arg(a, expected_arg_ty)
1282 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1284 let is_infer = match decl.output {
1285 hir::Return(ref output) if output.node == hir::TyInfer => true,
1286 hir::DefaultReturn(..) => true,
1290 let output_ty = match decl.output {
1291 _ if is_infer && expected_ret_ty.is_some() =>
1292 expected_ret_ty.unwrap(),
1293 _ if is_infer => self.ty_infer(decl.output.span()),
1294 hir::Return(ref output) =>
1295 self.ast_ty_to_ty(&output),
1296 hir::DefaultReturn(..) => bug!(),
1299 debug!("ty_of_closure: output_ty={:?}", output_ty);
1301 ty::Binder(self.tcx().mk_fn_sig(
1310 /// Given the bounds on an object, determines what single region bound (if any) we can
1311 /// use to summarize this type. The basic idea is that we will use the bound the user
1312 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1313 /// for region bounds. It may be that we can derive no bound at all, in which case
1314 /// we return `None`.
1315 fn compute_object_lifetime_bound(&self,
1317 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1318 -> Option<ty::Region<'tcx>> // if None, use the default
1320 let tcx = self.tcx();
1322 debug!("compute_opt_region_bound(existential_predicates={:?})",
1323 existential_predicates);
1325 // No explicit region bound specified. Therefore, examine trait
1326 // bounds and see if we can derive region bounds from those.
1327 let derived_region_bounds =
1328 object_region_bounds(tcx, existential_predicates);
1330 // If there are no derived region bounds, then report back that we
1331 // can find no region bound. The caller will use the default.
1332 if derived_region_bounds.is_empty() {
1336 // If any of the derived region bounds are 'static, that is always
1338 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1339 return Some(tcx.types.re_static);
1342 // Determine whether there is exactly one unique region in the set
1343 // of derived region bounds. If so, use that. Otherwise, report an
1345 let r = derived_region_bounds[0];
1346 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1347 span_err!(tcx.sess, span, E0227,
1348 "ambiguous lifetime bound, explicit lifetime bound required");
1354 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1355 /// remaining general trait bounds.
1356 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1357 trait_bounds: &'b [hir::PolyTraitRef])
1358 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1360 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1361 match bound.trait_ref.path.def {
1362 Def::Trait(trait_did) => {
1363 // Checks whether `trait_did` refers to one of the builtin
1364 // traits, like `Send`, and adds it to `auto_traits` if so.
1365 if Some(trait_did) == tcx.lang_items.send_trait() ||
1366 Some(trait_did) == tcx.lang_items.sync_trait() {
1367 let segments = &bound.trait_ref.path.segments;
1368 let parameters = &segments[segments.len() - 1].parameters;
1369 if !parameters.types().is_empty() {
1370 check_type_argument_count(tcx, bound.trait_ref.path.span,
1371 parameters.types().len(), &[]);
1373 if !parameters.lifetimes().is_empty() {
1374 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1375 parameters.lifetimes().len(), 0);
1386 let auto_traits = auto_traits.into_iter().map(|tr| {
1387 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1392 }).collect::<Vec<_>>();
1394 (auto_traits, trait_bounds)
1397 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1398 ty_param_defs: &[ty::TypeParameterDef]) {
1399 let accepted = ty_param_defs.len();
1400 let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1401 if supplied < required {
1402 let expected = if required < accepted {
1407 let arguments_plural = if required == 1 { "" } else { "s" };
1409 struct_span_err!(tcx.sess, span, E0243,
1410 "wrong number of type arguments: {} {}, found {}",
1411 expected, required, supplied)
1413 format!("{} {} type argument{}",
1418 } else if supplied > accepted {
1419 let expected = if required < accepted {
1420 format!("expected at most {}", accepted)
1422 format!("expected {}", accepted)
1424 let arguments_plural = if accepted == 1 { "" } else { "s" };
1426 struct_span_err!(tcx.sess, span, E0244,
1427 "wrong number of type arguments: {}, found {}",
1431 format!("{} type argument{}",
1432 if accepted == 0 { "expected no" } else { &expected },
1439 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1440 let label = if number < expected {
1442 format!("expected {} lifetime parameter", expected)
1444 format!("expected {} lifetime parameters", expected)
1447 let additional = number - expected;
1448 if additional == 1 {
1449 "unexpected lifetime parameter".to_string()
1451 format!("{} unexpected lifetime parameters", additional)
1454 struct_span_err!(tcx.sess, span, E0107,
1455 "wrong number of lifetime parameters: expected {}, found {}",
1457 .span_label(span, label)
1461 // A helper struct for conveniently grouping a set of bounds which we pass to
1462 // and return from functions in multiple places.
1463 #[derive(PartialEq, Eq, Clone, Debug)]
1464 pub struct Bounds<'tcx> {
1465 pub region_bounds: Vec<ty::Region<'tcx>>,
1466 pub implicitly_sized: bool,
1467 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1468 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1471 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1472 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1473 -> Vec<ty::Predicate<'tcx>>
1475 let mut vec = Vec::new();
1477 // If it could be sized, and is, add the sized predicate
1478 if self.implicitly_sized {
1479 if let Some(sized) = tcx.lang_items.sized_trait() {
1480 let trait_ref = ty::TraitRef {
1482 substs: tcx.mk_substs_trait(param_ty, &[])
1484 vec.push(trait_ref.to_predicate());
1488 for ®ion_bound in &self.region_bounds {
1489 // account for the binder being introduced below; no need to shift `param_ty`
1490 // because, at present at least, it can only refer to early-bound regions
1491 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1492 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1495 for bound_trait_ref in &self.trait_bounds {
1496 vec.push(bound_trait_ref.to_predicate());
1499 for projection in &self.projection_bounds {
1500 vec.push(projection.to_predicate());
1507 pub enum ExplicitSelf<'tcx> {
1509 ByReference(ty::Region<'tcx>, hir::Mutability),
1513 impl<'tcx> ExplicitSelf<'tcx> {
1514 /// We wish to (for now) categorize an explicit self
1515 /// declaration like `self: SomeType` into either `self`,
1516 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1517 /// by some simple pattern matching. A more precise check
1518 /// is done later in `check_method_self_type()`.
1523 /// impl Foo for &T {
1524 /// // Legal declarations:
1525 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1526 /// fn method2(self: &T); // ExplicitSelf::ByValue
1527 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1529 /// // Invalid cases will be caught later by `check_method_self_type`:
1530 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1534 /// To do the check we just count the number of "modifiers"
1535 /// on each type and compare them. If they are the same or
1536 /// the impl has more, we call it "by value". Otherwise, we
1537 /// look at the outermost modifier on the method decl and
1538 /// call it by-ref, by-box as appropriate. For method1, for
1539 /// example, the impl type has one modifier, but the method
1540 /// type has two, so we end up with
1541 /// ExplicitSelf::ByReference.
1542 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1543 self_arg_ty: Ty<'tcx>)
1544 -> ExplicitSelf<'tcx> {
1545 fn count_modifiers(ty: Ty) -> usize {
1547 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1548 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1553 let impl_modifiers = count_modifiers(untransformed_self_ty);
1554 let method_modifiers = count_modifiers(self_arg_ty);
1556 if impl_modifiers >= method_modifiers {
1557 ExplicitSelf::ByValue
1559 match self_arg_ty.sty {
1560 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1561 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1562 _ => ExplicitSelf::ByValue,