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 let def_scope = tcx.adjust(assoc_name, item.container.id(), ref_id).1;
895 if !item.vis.is_accessible_from(def_scope, tcx) {
896 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
897 tcx.sess.span_err(span, &msg);
899 tcx.check_stability(item.def_id, ref_id, span);
904 fn qpath_to_ty(&self,
906 opt_self_ty: Option<Ty<'tcx>>,
908 trait_segment: &hir::PathSegment,
909 item_segment: &hir::PathSegment)
912 let tcx = self.tcx();
914 self.prohibit_type_params(slice::ref_slice(item_segment));
916 let self_ty = if let Some(ty) = opt_self_ty {
919 let path_str = tcx.item_path_str(trait_def_id);
920 self.report_ambiguous_associated_type(span,
923 &item_segment.name.as_str());
924 return tcx.types.err;
927 debug!("qpath_to_ty: self_type={:?}", self_ty);
929 let trait_ref = self.ast_path_to_mono_trait_ref(span,
934 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
936 self.normalize_ty(span, tcx.mk_projection(trait_ref, item_segment.name))
939 pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
940 for segment in segments {
941 for typ in segment.parameters.types() {
942 struct_span_err!(self.tcx().sess, typ.span, E0109,
943 "type parameters are not allowed on this type")
944 .span_label(typ.span, "type parameter not allowed")
948 for lifetime in segment.parameters.lifetimes() {
949 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
950 "lifetime parameters are not allowed on this type")
951 .span_label(lifetime.span,
952 "lifetime parameter not allowed on this type")
956 for binding in segment.parameters.bindings() {
957 self.prohibit_projection(binding.span);
963 pub fn prohibit_projection(&self, span: Span) {
964 let mut err = struct_span_err!(self.tcx().sess, span, E0229,
965 "associated type bindings are not allowed here");
966 err.span_label(span, "associated type not allowed here").emit();
969 // Check a type Path and convert it to a Ty.
970 pub fn def_to_ty(&self,
971 opt_self_ty: Option<Ty<'tcx>>,
973 permit_variants: bool)
975 let tcx = self.tcx();
977 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
978 path.def, opt_self_ty, path.segments);
980 let span = path.span;
982 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
983 assert_eq!(opt_self_ty, None);
984 self.prohibit_type_params(path.segments.split_last().unwrap().1);
985 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
987 Def::Variant(did) if permit_variants => {
988 // Convert "variant type" as if it were a real type.
989 // The resulting `Ty` is type of the variant's enum for now.
990 assert_eq!(opt_self_ty, None);
991 self.prohibit_type_params(path.segments.split_last().unwrap().1);
992 self.ast_path_to_ty(span,
993 tcx.parent_def_id(did).unwrap(),
994 path.segments.last().unwrap())
996 Def::TyParam(did) => {
997 assert_eq!(opt_self_ty, None);
998 self.prohibit_type_params(&path.segments);
1000 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1001 let item_id = tcx.hir.get_parent_node(node_id);
1002 let item_def_id = tcx.hir.local_def_id(item_id);
1003 let generics = tcx.generics_of(item_def_id);
1004 let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id).index];
1005 tcx.mk_param(index, tcx.hir.name(node_id))
1007 Def::SelfTy(_, Some(def_id)) => {
1008 // Self in impl (we know the concrete type).
1010 assert_eq!(opt_self_ty, None);
1011 self.prohibit_type_params(&path.segments);
1013 tcx.at(span).type_of(def_id)
1015 Def::SelfTy(Some(_), None) => {
1017 assert_eq!(opt_self_ty, None);
1018 self.prohibit_type_params(&path.segments);
1021 Def::AssociatedTy(def_id) => {
1022 self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1023 let trait_did = tcx.parent_def_id(def_id).unwrap();
1024 self.qpath_to_ty(span,
1027 &path.segments[path.segments.len()-2],
1028 path.segments.last().unwrap())
1030 Def::PrimTy(prim_ty) => {
1031 assert_eq!(opt_self_ty, None);
1032 self.prohibit_type_params(&path.segments);
1034 hir::TyBool => tcx.types.bool,
1035 hir::TyChar => tcx.types.char,
1036 hir::TyInt(it) => tcx.mk_mach_int(it),
1037 hir::TyUint(uit) => tcx.mk_mach_uint(uit),
1038 hir::TyFloat(ft) => tcx.mk_mach_float(ft),
1039 hir::TyStr => tcx.mk_str()
1043 self.set_tainted_by_errors();
1044 return self.tcx().types.err;
1046 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1050 /// Parses the programmer's textual representation of a type into our
1051 /// internal notion of a type.
1052 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1053 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1056 let tcx = self.tcx();
1058 let result_ty = match ast_ty.node {
1059 hir::TySlice(ref ty) => {
1060 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1062 hir::TyPtr(ref mt) => {
1063 tcx.mk_ptr(ty::TypeAndMut {
1064 ty: self.ast_ty_to_ty(&mt.ty),
1068 hir::TyRptr(ref region, ref mt) => {
1069 let r = self.ast_region_to_region(region, None);
1070 debug!("TyRef r={:?}", r);
1071 let t = self.ast_ty_to_ty(&mt.ty);
1072 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1077 hir::TyTup(ref fields) => {
1078 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1080 hir::TyBareFn(ref bf) => {
1081 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1082 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1084 // Find any late-bound regions declared in return type that do
1085 // not appear in the arguments. These are not wellformed.
1089 // for<'a> fn() -> &'a str <-- 'a is bad
1090 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1092 // Note that we do this check **here** and not in
1093 // `ty_of_bare_fn` because the latter is also used to make
1094 // the types for fn items, and we do not want to issue a
1095 // warning then. (Once we fix #32330, the regions we are
1096 // checking for here would be considered early bound
1098 let inputs = bare_fn_ty.inputs();
1099 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1100 &inputs.map_bound(|i| i.to_owned()));
1101 let output = bare_fn_ty.output();
1102 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1103 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1104 let br_name = match *br {
1105 ty::BrNamed(_, name) => name,
1108 bf.decl.output.span(),
1109 "anonymous bound region {:?} in return but not args",
1113 struct_span_err!(tcx.sess,
1116 "return type references lifetime `{}`, \
1117 which does not appear in the fn input types",
1121 tcx.mk_fn_ptr(bare_fn_ty)
1123 hir::TyTraitObject(ref bounds, ref lifetime) => {
1124 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1126 hir::TyImplTrait(_) => {
1127 // Figure out if we can allow an `impl Trait` here, by walking up
1128 // to a `fn` or inherent `impl` method, going only through `Ty`
1129 // or `TraitRef` nodes (as nothing else should be in types) and
1130 // ensuring that we reach the `fn`/method signature's return type.
1131 let mut node_id = ast_ty.id;
1132 let fn_decl = loop {
1133 let parent = tcx.hir.get_parent_node(node_id);
1134 match tcx.hir.get(parent) {
1135 hir::map::NodeItem(&hir::Item {
1136 node: hir::ItemFn(ref fn_decl, ..), ..
1137 }) => break Some(fn_decl),
1139 hir::map::NodeImplItem(&hir::ImplItem {
1140 node: hir::ImplItemKind::Method(ref sig, _), ..
1142 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1143 hir::ItemImpl(.., None, _, _) => {
1144 break Some(&sig.decl)
1150 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1156 let allow = fn_decl.map_or(false, |fd| {
1158 hir::DefaultReturn(_) => false,
1159 hir::Return(ref ty) => ty.id == node_id
1163 // Create the anonymized type.
1165 let def_id = tcx.hir.local_def_id(ast_ty.id);
1166 tcx.mk_anon(def_id, Substs::identity_for_item(tcx, def_id))
1168 span_err!(tcx.sess, ast_ty.span, E0562,
1169 "`impl Trait` not allowed outside of function \
1170 and inherent method return types");
1174 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1175 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1176 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1177 self.ast_ty_to_ty(qself)
1179 self.def_to_ty(opt_self_ty, path, false)
1181 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1182 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1183 let ty = self.ast_ty_to_ty(qself);
1185 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1190 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1192 hir::TyArray(ref ty, length) => {
1193 if let Ok(length) = eval_length(tcx, length, "array length") {
1194 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1196 self.tcx().types.err
1199 hir::TyTypeof(ref _e) => {
1200 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1201 "`typeof` is a reserved keyword but unimplemented")
1202 .span_label(ast_ty.span, "reserved keyword")
1208 // TyInfer also appears as the type of arguments or return
1209 // values in a ExprClosure, or as
1210 // the type of local variables. Both of these cases are
1211 // handled specially and will not descend into this routine.
1212 self.ty_infer(ast_ty.span)
1222 pub fn ty_of_arg(&self,
1224 expected_ty: Option<Ty<'tcx>>)
1228 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1229 hir::TyInfer => self.ty_infer(ty.span),
1230 _ => self.ast_ty_to_ty(ty),
1234 pub fn ty_of_fn(&self,
1235 unsafety: hir::Unsafety,
1238 -> ty::PolyFnSig<'tcx> {
1241 let input_tys: Vec<Ty> =
1242 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1244 let output_ty = match decl.output {
1245 hir::Return(ref output) => self.ast_ty_to_ty(output),
1246 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1249 debug!("ty_of_fn: output_ty={:?}", output_ty);
1251 ty::Binder(self.tcx().mk_fn_sig(
1252 input_tys.into_iter(),
1260 pub fn ty_of_closure(&self,
1261 unsafety: hir::Unsafety,
1264 expected_sig: Option<ty::FnSig<'tcx>>)
1265 -> ty::PolyFnSig<'tcx>
1267 debug!("ty_of_closure(expected_sig={:?})",
1270 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1271 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1272 // no guarantee that the correct number of expected args
1274 if i < e.inputs().len() {
1280 self.ty_of_arg(a, expected_arg_ty)
1283 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1285 let is_infer = match decl.output {
1286 hir::Return(ref output) if output.node == hir::TyInfer => true,
1287 hir::DefaultReturn(..) => true,
1291 let output_ty = match decl.output {
1292 _ if is_infer && expected_ret_ty.is_some() =>
1293 expected_ret_ty.unwrap(),
1294 _ if is_infer => self.ty_infer(decl.output.span()),
1295 hir::Return(ref output) =>
1296 self.ast_ty_to_ty(&output),
1297 hir::DefaultReturn(..) => bug!(),
1300 debug!("ty_of_closure: output_ty={:?}", output_ty);
1302 ty::Binder(self.tcx().mk_fn_sig(
1311 /// Given the bounds on an object, determines what single region bound (if any) we can
1312 /// use to summarize this type. The basic idea is that we will use the bound the user
1313 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1314 /// for region bounds. It may be that we can derive no bound at all, in which case
1315 /// we return `None`.
1316 fn compute_object_lifetime_bound(&self,
1318 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1319 -> Option<ty::Region<'tcx>> // if None, use the default
1321 let tcx = self.tcx();
1323 debug!("compute_opt_region_bound(existential_predicates={:?})",
1324 existential_predicates);
1326 // No explicit region bound specified. Therefore, examine trait
1327 // bounds and see if we can derive region bounds from those.
1328 let derived_region_bounds =
1329 object_region_bounds(tcx, existential_predicates);
1331 // If there are no derived region bounds, then report back that we
1332 // can find no region bound. The caller will use the default.
1333 if derived_region_bounds.is_empty() {
1337 // If any of the derived region bounds are 'static, that is always
1339 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1340 return Some(tcx.types.re_static);
1343 // Determine whether there is exactly one unique region in the set
1344 // of derived region bounds. If so, use that. Otherwise, report an
1346 let r = derived_region_bounds[0];
1347 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1348 span_err!(tcx.sess, span, E0227,
1349 "ambiguous lifetime bound, explicit lifetime bound required");
1355 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1356 /// remaining general trait bounds.
1357 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1358 trait_bounds: &'b [hir::PolyTraitRef])
1359 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1361 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1362 match bound.trait_ref.path.def {
1363 Def::Trait(trait_did) => {
1364 // Checks whether `trait_did` refers to one of the builtin
1365 // traits, like `Send`, and adds it to `auto_traits` if so.
1366 if Some(trait_did) == tcx.lang_items.send_trait() ||
1367 Some(trait_did) == tcx.lang_items.sync_trait() {
1368 let segments = &bound.trait_ref.path.segments;
1369 let parameters = &segments[segments.len() - 1].parameters;
1370 if !parameters.types().is_empty() {
1371 check_type_argument_count(tcx, bound.trait_ref.path.span,
1372 parameters.types().len(), &[]);
1374 if !parameters.lifetimes().is_empty() {
1375 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1376 parameters.lifetimes().len(), 0);
1387 let auto_traits = auto_traits.into_iter().map(|tr| {
1388 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1393 }).collect::<Vec<_>>();
1395 (auto_traits, trait_bounds)
1398 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1399 ty_param_defs: &[ty::TypeParameterDef]) {
1400 let accepted = ty_param_defs.len();
1401 let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1402 if supplied < required {
1403 let expected = if required < accepted {
1408 let arguments_plural = if required == 1 { "" } else { "s" };
1410 struct_span_err!(tcx.sess, span, E0243,
1411 "wrong number of type arguments: {} {}, found {}",
1412 expected, required, supplied)
1414 format!("{} {} type argument{}",
1419 } else if supplied > accepted {
1420 let expected = if required < accepted {
1421 format!("expected at most {}", accepted)
1423 format!("expected {}", accepted)
1425 let arguments_plural = if accepted == 1 { "" } else { "s" };
1427 struct_span_err!(tcx.sess, span, E0244,
1428 "wrong number of type arguments: {}, found {}",
1432 format!("{} type argument{}",
1433 if accepted == 0 { "expected no" } else { &expected },
1440 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1441 let label = if number < expected {
1443 format!("expected {} lifetime parameter", expected)
1445 format!("expected {} lifetime parameters", expected)
1448 let additional = number - expected;
1449 if additional == 1 {
1450 "unexpected lifetime parameter".to_string()
1452 format!("{} unexpected lifetime parameters", additional)
1455 struct_span_err!(tcx.sess, span, E0107,
1456 "wrong number of lifetime parameters: expected {}, found {}",
1458 .span_label(span, label)
1462 // A helper struct for conveniently grouping a set of bounds which we pass to
1463 // and return from functions in multiple places.
1464 #[derive(PartialEq, Eq, Clone, Debug)]
1465 pub struct Bounds<'tcx> {
1466 pub region_bounds: Vec<ty::Region<'tcx>>,
1467 pub implicitly_sized: bool,
1468 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1469 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1472 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1473 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1474 -> Vec<ty::Predicate<'tcx>>
1476 let mut vec = Vec::new();
1478 // If it could be sized, and is, add the sized predicate
1479 if self.implicitly_sized {
1480 if let Some(sized) = tcx.lang_items.sized_trait() {
1481 let trait_ref = ty::TraitRef {
1483 substs: tcx.mk_substs_trait(param_ty, &[])
1485 vec.push(trait_ref.to_predicate());
1489 for ®ion_bound in &self.region_bounds {
1490 // account for the binder being introduced below; no need to shift `param_ty`
1491 // because, at present at least, it can only refer to early-bound regions
1492 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1493 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1496 for bound_trait_ref in &self.trait_bounds {
1497 vec.push(bound_trait_ref.to_predicate());
1500 for projection in &self.projection_bounds {
1501 vec.push(projection.to_predicate());
1508 pub enum ExplicitSelf<'tcx> {
1510 ByReference(ty::Region<'tcx>, hir::Mutability),
1514 impl<'tcx> ExplicitSelf<'tcx> {
1515 /// We wish to (for now) categorize an explicit self
1516 /// declaration like `self: SomeType` into either `self`,
1517 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1518 /// by some simple pattern matching. A more precise check
1519 /// is done later in `check_method_self_type()`.
1524 /// impl Foo for &T {
1525 /// // Legal declarations:
1526 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1527 /// fn method2(self: &T); // ExplicitSelf::ByValue
1528 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1530 /// // Invalid cases will be caught later by `check_method_self_type`:
1531 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1535 /// To do the check we just count the number of "modifiers"
1536 /// on each type and compare them. If they are the same or
1537 /// the impl has more, we call it "by value". Otherwise, we
1538 /// look at the outermost modifier on the method decl and
1539 /// call it by-ref, by-box as appropriate. For method1, for
1540 /// example, the impl type has one modifier, but the method
1541 /// type has two, so we end up with
1542 /// ExplicitSelf::ByReference.
1543 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1544 self_arg_ty: Ty<'tcx>)
1545 -> ExplicitSelf<'tcx> {
1546 fn count_modifiers(ty: Ty) -> usize {
1548 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1549 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1554 let impl_modifiers = count_modifiers(untransformed_self_ty);
1555 let method_modifiers = count_modifiers(self_arg_ty);
1557 if impl_modifiers >= method_modifiers {
1558 ExplicitSelf::ByValue
1560 match self_arg_ty.sty {
1561 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1562 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1563 _ => ExplicitSelf::ByValue,