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 /// Return an (optional) substitution to convert bound type parameters that
45 /// are in scope into free ones. This function should only return Some
47 /// See ParameterEnvironment::free_substs for more information.
48 fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
50 /// What lifetime should we use when a lifetime is omitted (and not elided)?
51 fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
52 -> Option<ty::Region<'tcx>>;
54 /// What type should we use when a type is omitted?
55 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
57 /// Same as ty_infer, but with a known type parameter definition.
58 fn ty_infer_for_def(&self,
59 _def: &ty::TypeParameterDef,
60 _substs: &[Kind<'tcx>],
61 span: Span) -> Ty<'tcx> {
65 /// Projecting an associated type from a (potentially)
66 /// higher-ranked trait reference is more complicated, because of
67 /// the possibility of late-bound regions appearing in the
68 /// associated type binding. This is not legal in function
69 /// signatures for that reason. In a function body, we can always
70 /// handle it because we can use inference variables to remove the
71 /// late-bound regions.
72 fn projected_ty_from_poly_trait_ref(&self,
74 poly_trait_ref: ty::PolyTraitRef<'tcx>,
78 /// Normalize an associated type coming from the user.
79 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
81 /// Invoked when we encounter an error from some prior pass
82 /// (e.g. resolve) that is translated into a ty-error. This is
83 /// used to help suppress derived errors typeck might otherwise
85 fn set_tainted_by_errors(&self);
88 struct ConvertedBinding<'tcx> {
94 /// Dummy type used for the `Self` of a `TraitRef` created for converting
95 /// a trait object, and which gets removed in `ExistentialTraitRef`.
96 /// This type must not appear anywhere in other converted types.
97 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
99 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
100 pub fn ast_region_to_region(&self,
101 lifetime: &hir::Lifetime,
102 def: Option<&ty::RegionParameterDef>)
105 let tcx = self.tcx();
106 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
107 Some(&rl::Region::Static) => {
111 Some(&rl::Region::LateBound(debruijn, id)) => {
112 let name = tcx.hir.name(id);
113 tcx.mk_region(ty::ReLateBound(debruijn,
114 ty::BrNamed(tcx.hir.local_def_id(id), name)))
117 Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
118 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
121 Some(&rl::Region::EarlyBound(index, id)) => {
122 let name = tcx.hir.name(id);
123 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
129 Some(&rl::Region::Free(scope, id)) => {
130 let name = tcx.hir.name(id);
131 tcx.mk_region(ty::ReFree(ty::FreeRegion {
132 scope: Some(scope.to_code_extent(tcx)),
133 bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name)
136 // (*) -- not late-bound, won't change
140 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
144 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
151 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
152 /// returns an appropriate set of substitutions for this particular reference to `I`.
153 pub fn ast_path_substs_for_ty(&self,
156 item_segment: &hir::PathSegment)
157 -> &'tcx Substs<'tcx>
159 let tcx = self.tcx();
161 match item_segment.parameters {
162 hir::AngleBracketedParameters(_) => {}
163 hir::ParenthesizedParameters(..) => {
164 struct_span_err!(tcx.sess, span, E0214,
165 "parenthesized parameters may only be used with a trait")
166 .span_label(span, "only traits may use parentheses")
169 return Substs::for_item(tcx, def_id, |_, _| {
177 let (substs, assoc_bindings) =
178 self.create_substs_for_ast_path(span,
180 &item_segment.parameters,
183 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
188 /// Given the type/region arguments provided to some path (along with
189 /// an implicit Self, if this is a trait reference) returns the complete
190 /// set of substitutions. This may involve applying defaulted type parameters.
192 /// Note that the type listing given here is *exactly* what the user provided.
193 fn create_substs_for_ast_path(&self,
196 parameters: &hir::PathParameters,
197 self_ty: Option<Ty<'tcx>>)
198 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
200 let tcx = self.tcx();
202 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
204 def_id, self_ty, parameters);
206 let (lifetimes, num_types_provided, infer_types) = match *parameters {
207 hir::AngleBracketedParameters(ref data) => {
208 (&data.lifetimes[..], data.types.len(), data.infer_types)
210 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
213 // If the type is parameterized by this region, then replace this
214 // region with the current anon region binding (in other words,
215 // whatever & would get replaced with).
216 let decl_generics = tcx.generics_of(def_id);
217 let expected_num_region_params = decl_generics.regions.len();
218 let supplied_num_region_params = lifetimes.len();
219 if expected_num_region_params != supplied_num_region_params {
220 report_lifetime_number_error(tcx, span,
221 supplied_num_region_params,
222 expected_num_region_params);
225 // If a self-type was declared, one should be provided.
226 assert_eq!(decl_generics.has_self, self_ty.is_some());
228 // Check the number of type parameters supplied by the user.
229 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
230 if !infer_types || num_types_provided > ty_param_defs.len() {
231 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
234 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
235 let default_needs_object_self = |p: &ty::TypeParameterDef| {
236 if is_object && p.has_default {
237 if tcx.at(span).type_of(p.def_id).has_self_ty() {
238 // There is no suitable inference default for a type parameter
239 // that references self, in an object type.
247 let mut output_assoc_binding = None;
248 let substs = Substs::for_item(tcx, def_id, |def, _| {
249 let i = def.index as usize - self_ty.is_some() as usize;
250 if let Some(lifetime) = lifetimes.get(i) {
251 self.ast_region_to_region(lifetime, Some(def))
256 let i = def.index as usize;
258 // Handle Self first, so we can adjust the index to match the AST.
259 if let (0, Some(ty)) = (i, self_ty) {
263 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
264 if i < num_types_provided {
265 // A provided type parameter.
267 hir::AngleBracketedParameters(ref data) => {
268 self.ast_ty_to_ty(&data.types[i])
270 hir::ParenthesizedParameters(ref data) => {
272 let (ty, assoc) = self.convert_parenthesized_parameters(data);
273 output_assoc_binding = Some(assoc);
277 } else if infer_types {
278 // No type parameters were provided, we can infer all.
279 let ty_var = if !default_needs_object_self(def) {
280 self.ty_infer_for_def(def, substs, span)
285 } else if def.has_default {
286 // No type parameter provided, but a default exists.
288 // If we are converting an object type, then the
289 // `Self` parameter is unknown. However, some of the
290 // other type parameters may reference `Self` in their
291 // defaults. This will lead to an ICE if we are not
293 if default_needs_object_self(def) {
294 struct_span_err!(tcx.sess, span, E0393,
295 "the type parameter `{}` must be explicitly specified",
297 .span_label(span, format!("missing reference to `{}`", def.name))
298 .note(&format!("because of the default `Self` reference, \
299 type parameters must be specified on object types"))
303 // This is a default type parameter.
306 tcx.at(span).type_of(def.def_id)
307 .subst_spanned(tcx, substs, Some(span))
311 // We've already errored above about the mismatch.
316 let assoc_bindings = match *parameters {
317 hir::AngleBracketedParameters(ref data) => {
318 data.bindings.iter().map(|b| {
321 ty: self.ast_ty_to_ty(&b.ty),
326 hir::ParenthesizedParameters(ref data) => {
327 vec![output_assoc_binding.unwrap_or_else(|| {
328 // This is an error condition, but we should
329 // get the associated type binding anyway.
330 self.convert_parenthesized_parameters(data).1
335 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
336 decl_generics, self_ty, substs);
338 (substs, assoc_bindings)
341 fn convert_parenthesized_parameters(&self,
342 data: &hir::ParenthesizedParameterData)
343 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
345 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
346 self.ast_ty_to_ty(a_t)
349 let (output, output_span) = match data.output {
350 Some(ref output_ty) => {
351 (self.ast_ty_to_ty(output_ty), output_ty.span)
354 (self.tcx().mk_nil(), data.span)
358 let output_binding = ConvertedBinding {
359 item_name: Symbol::intern(FN_OUTPUT_NAME),
364 (self.tcx().mk_ty(ty::TyTuple(inputs, false)), output_binding)
367 /// Instantiates the path for the given trait reference, assuming that it's
368 /// bound to a valid trait type. Returns the def_id for the defining trait.
369 /// Fails if the type is a type other than a trait type.
371 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
372 /// are disallowed. Otherwise, they are pushed onto the vector given.
373 pub fn instantiate_mono_trait_ref(&self,
374 trait_ref: &hir::TraitRef,
376 -> ty::TraitRef<'tcx>
378 let trait_def_id = self.trait_def_id(trait_ref);
379 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
382 trait_ref.path.segments.last().unwrap())
385 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
386 let path = &trait_ref.path;
388 Def::Trait(trait_def_id) => trait_def_id,
390 self.tcx().sess.fatal("cannot continue compilation due to previous error");
393 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
394 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
399 pub fn instantiate_poly_trait_ref(&self,
400 ast_trait_ref: &hir::PolyTraitRef,
402 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
403 -> ty::PolyTraitRef<'tcx>
405 let trait_ref = &ast_trait_ref.trait_ref;
406 let trait_def_id = self.trait_def_id(trait_ref);
408 debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
410 let (substs, assoc_bindings) =
411 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
414 trait_ref.path.segments.last().unwrap());
415 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
417 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
418 // specify type to assert that error was already reported in Err case:
419 let predicate: Result<_, ErrorReported> =
420 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
423 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
426 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
427 trait_ref, poly_projections, poly_trait_ref);
431 fn ast_path_to_mono_trait_ref(&self,
435 trait_segment: &hir::PathSegment)
436 -> ty::TraitRef<'tcx>
438 let (substs, assoc_bindings) =
439 self.create_substs_for_ast_trait_ref(span,
443 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
444 ty::TraitRef::new(trait_def_id, substs)
447 fn create_substs_for_ast_trait_ref(&self,
451 trait_segment: &hir::PathSegment)
452 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
454 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
457 let trait_def = self.tcx().trait_def(trait_def_id);
459 match trait_segment.parameters {
460 hir::AngleBracketedParameters(_) => {
461 // For now, require that parenthetical notation be used
462 // only with `Fn()` etc.
463 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
464 emit_feature_err(&self.tcx().sess.parse_sess,
465 "unboxed_closures", span, GateIssue::Language,
467 the precise format of `Fn`-family traits' \
468 type parameters is subject to change. \
469 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
472 hir::ParenthesizedParameters(_) => {
473 // For now, require that parenthetical notation be used
474 // only with `Fn()` etc.
475 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
476 emit_feature_err(&self.tcx().sess.parse_sess,
477 "unboxed_closures", span, GateIssue::Language,
479 parenthetical notation is only stable when used with `Fn`-family traits");
484 self.create_substs_for_ast_path(span,
486 &trait_segment.parameters,
490 fn trait_defines_associated_type_named(&self,
492 assoc_name: ast::Name)
495 self.tcx().associated_items(trait_def_id).any(|item| {
496 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
500 fn ast_type_binding_to_poly_projection_predicate(
502 _path_id: ast::NodeId,
503 trait_ref: ty::PolyTraitRef<'tcx>,
504 binding: &ConvertedBinding<'tcx>)
505 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
507 let tcx = self.tcx();
509 // Given something like `U : SomeTrait<T=X>`, we want to produce a
510 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
511 // subtle in the event that `T` is defined in a supertrait of
512 // `SomeTrait`, because in that case we need to upcast.
514 // That is, consider this case:
517 // trait SubTrait : SuperTrait<int> { }
518 // trait SuperTrait<A> { type T; }
520 // ... B : SubTrait<T=foo> ...
523 // We want to produce `<B as SuperTrait<int>>::T == foo`.
525 // Find any late-bound regions declared in `ty` that are not
526 // declared in the trait-ref. These are not wellformed.
530 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
531 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
532 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
533 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
534 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
535 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
536 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
537 let br_name = match *br {
538 ty::BrNamed(_, name) => name,
542 "anonymous bound region {:?} in binding but not trait ref",
546 struct_span_err!(tcx.sess,
549 "binding for associated type `{}` references lifetime `{}`, \
550 which does not appear in the trait input types",
551 binding.item_name, br_name)
555 // Simple case: X is defined in the current trait.
556 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
557 return Ok(trait_ref.map_bound(|trait_ref| {
558 ty::ProjectionPredicate {
559 projection_ty: ty::ProjectionTy {
560 trait_ref: trait_ref,
561 item_name: binding.item_name,
568 // Otherwise, we have to walk through the supertraits to find
571 traits::supertraits(tcx, trait_ref.clone())
572 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
574 let candidate = self.one_bound_for_assoc_type(candidates,
575 &trait_ref.to_string(),
576 &binding.item_name.as_str(),
579 Ok(candidate.map_bound(|trait_ref| {
580 ty::ProjectionPredicate {
581 projection_ty: ty::ProjectionTy {
582 trait_ref: trait_ref,
583 item_name: binding.item_name,
590 fn ast_path_to_ty(&self,
593 item_segment: &hir::PathSegment)
596 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
599 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
603 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
604 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
605 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
606 -> ty::ExistentialTraitRef<'tcx> {
607 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
608 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
611 fn conv_object_ty_poly_trait_ref(&self,
613 trait_bounds: &[hir::PolyTraitRef],
614 lifetime: &hir::Lifetime)
617 let tcx = self.tcx();
619 if trait_bounds.is_empty() {
620 span_err!(tcx.sess, span, E0224,
621 "at least one non-builtin trait is required for an object type");
622 return tcx.types.err;
625 let mut projection_bounds = vec![];
626 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
627 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
629 &mut projection_bounds);
631 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
633 if !trait_bounds.is_empty() {
634 let b = &trait_bounds[0];
635 let span = b.trait_ref.path.span;
636 struct_span_err!(self.tcx().sess, span, E0225,
637 "only Send/Sync traits can be used as additional traits in a trait object")
638 .span_label(span, "non-Send/Sync additional trait")
642 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
643 let existential_principal = principal.map_bound(|trait_ref| {
644 self.trait_ref_to_existential(trait_ref)
646 let existential_projections = projection_bounds.iter().map(|bound| {
647 bound.map_bound(|b| {
648 let p = b.projection_ty;
649 ty::ExistentialProjection {
650 trait_ref: self.trait_ref_to_existential(p.trait_ref),
651 item_name: p.item_name,
657 // check that there are no gross object safety violations,
658 // most importantly, that the supertraits don't contain Self,
660 let object_safety_violations =
661 tcx.astconv_object_safety_violations(principal.def_id());
662 if !object_safety_violations.is_empty() {
663 tcx.report_object_safety_error(
664 span, principal.def_id(), object_safety_violations)
666 return tcx.types.err;
669 let mut associated_types = FxHashSet::default();
670 for tr in traits::supertraits(tcx, principal) {
671 associated_types.extend(tcx.associated_items(tr.def_id())
672 .filter(|item| item.kind == ty::AssociatedKind::Type)
673 .map(|item| (tr.def_id(), item.name)));
676 for projection_bound in &projection_bounds {
677 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
678 projection_bound.0.projection_ty.item_name);
679 associated_types.remove(&pair);
682 for (trait_def_id, name) in associated_types {
683 struct_span_err!(tcx.sess, span, E0191,
684 "the value of the associated type `{}` (from the trait `{}`) must be specified",
686 tcx.item_path_str(trait_def_id))
687 .span_label(span, format!(
688 "missing associated type `{}` value", name))
693 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
694 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
695 .chain(existential_projections
696 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
697 .collect::<AccumulateVec<[_; 8]>>();
698 v.sort_by(|a, b| a.cmp(tcx, b));
699 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
702 // Explicitly specified region bound. Use that.
703 let region_bound = if !lifetime.is_elided() {
704 self.ast_region_to_region(lifetime, None)
706 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
707 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
708 self.ast_region_to_region(lifetime, None)
710 self.re_infer(span, None).unwrap_or_else(|| {
711 span_err!(tcx.sess, span, E0228,
712 "the lifetime bound for this object type cannot be deduced \
713 from context; please supply an explicit bound");
720 debug!("region_bound: {:?}", region_bound);
722 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
723 debug!("trait_object_type: {:?}", ty);
727 fn report_ambiguous_associated_type(&self,
732 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
733 .span_label(span, "ambiguous associated type")
734 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
735 type_str, trait_str, name))
740 // Search for a bound on a type parameter which includes the associated item
741 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
742 // This function will fail if there are no suitable bounds or there is
744 fn find_bound_for_assoc_item(&self,
745 ty_param_def_id: DefId,
746 assoc_name: ast::Name,
748 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
750 let tcx = self.tcx();
752 let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
753 .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
755 // Check that there is exactly one way to find an associated type with the
757 let suitable_bounds =
758 traits::transitive_bounds(tcx, &bounds)
759 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
761 let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
762 let param_name = tcx.hir.ty_param_name(param_node_id);
763 self.one_bound_for_assoc_type(suitable_bounds,
764 ¶m_name.as_str(),
765 &assoc_name.as_str(),
770 // Checks that bounds contains exactly one element and reports appropriate
772 fn one_bound_for_assoc_type<I>(&self,
777 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
778 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
780 let bound = match bounds.next() {
781 Some(bound) => bound,
783 struct_span_err!(self.tcx().sess, span, E0220,
784 "associated type `{}` not found for `{}`",
787 .span_label(span, format!("associated type `{}` not found", assoc_name))
789 return Err(ErrorReported);
793 if let Some(bound2) = bounds.next() {
794 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
795 let mut err = struct_span_err!(
796 self.tcx().sess, span, E0221,
797 "ambiguous associated type `{}` in bounds of `{}`",
800 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
802 for bound in bounds {
803 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
804 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
806 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
808 if let Some(span) = bound_span {
809 err.span_label(span, format!("ambiguous `{}` from `{}`",
813 span_note!(&mut err, span,
814 "associated type `{}` could derive from `{}`",
825 // Create a type from a path to an associated type.
826 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
827 // and item_segment is the path segment for D. We return a type and a def for
829 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
830 // parameter or Self.
831 pub fn associated_path_def_to_ty(&self,
836 item_segment: &hir::PathSegment)
839 let tcx = self.tcx();
840 let assoc_name = item_segment.name;
842 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
844 self.prohibit_type_params(slice::ref_slice(item_segment));
846 // Find the type of the associated item, and the trait where the associated
848 let bound = match (&ty.sty, ty_path_def) {
849 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
850 // `Self` in an impl of a trait - we have a concrete self type and a
852 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
853 Some(trait_ref) => trait_ref,
855 // A cycle error occurred, most likely.
856 return (tcx.types.err, Def::Err);
860 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
861 trait_ref.subst(tcx, free_substs)
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 ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
900 let ty = self.normalize_ty(span, ty);
902 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name)
903 .expect("missing associated type");
904 let def = Def::AssociatedTy(item.def_id);
905 if !tcx.vis_is_accessible_from(item.vis, ref_id) {
906 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
907 tcx.sess.span_err(span, &msg);
909 tcx.check_stability(item.def_id, ref_id, span);
914 fn qpath_to_ty(&self,
916 opt_self_ty: Option<Ty<'tcx>>,
918 trait_segment: &hir::PathSegment,
919 item_segment: &hir::PathSegment)
922 let tcx = self.tcx();
924 self.prohibit_type_params(slice::ref_slice(item_segment));
926 let self_ty = if let Some(ty) = opt_self_ty {
929 let path_str = tcx.item_path_str(trait_def_id);
930 self.report_ambiguous_associated_type(span,
933 &item_segment.name.as_str());
934 return tcx.types.err;
937 debug!("qpath_to_ty: self_type={:?}", self_ty);
939 let trait_ref = self.ast_path_to_mono_trait_ref(span,
944 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
946 self.normalize_ty(span, tcx.mk_projection(trait_ref, item_segment.name))
949 pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
950 for segment in segments {
951 for typ in segment.parameters.types() {
952 struct_span_err!(self.tcx().sess, typ.span, E0109,
953 "type parameters are not allowed on this type")
954 .span_label(typ.span, "type parameter not allowed")
958 for lifetime in segment.parameters.lifetimes() {
959 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
960 "lifetime parameters are not allowed on this type")
961 .span_label(lifetime.span,
962 "lifetime parameter not allowed on this type")
966 for binding in segment.parameters.bindings() {
967 self.prohibit_projection(binding.span);
973 pub fn prohibit_projection(&self, span: Span) {
974 let mut err = struct_span_err!(self.tcx().sess, span, E0229,
975 "associated type bindings are not allowed here");
976 err.span_label(span, "associate type not allowed here").emit();
979 // Check a type Path and convert it to a Ty.
980 pub fn def_to_ty(&self,
981 opt_self_ty: Option<Ty<'tcx>>,
983 permit_variants: bool)
985 let tcx = self.tcx();
987 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
988 path.def, opt_self_ty, path.segments);
990 let span = path.span;
992 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
993 assert_eq!(opt_self_ty, None);
994 self.prohibit_type_params(path.segments.split_last().unwrap().1);
995 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
997 Def::Variant(did) if permit_variants => {
998 // Convert "variant type" as if it were a real type.
999 // The resulting `Ty` is type of the variant's enum for now.
1000 assert_eq!(opt_self_ty, None);
1001 self.prohibit_type_params(path.segments.split_last().unwrap().1);
1002 self.ast_path_to_ty(span,
1003 tcx.parent_def_id(did).unwrap(),
1004 path.segments.last().unwrap())
1006 Def::TyParam(did) => {
1007 assert_eq!(opt_self_ty, None);
1008 self.prohibit_type_params(&path.segments);
1010 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1011 let item_id = tcx.hir.get_parent_node(node_id);
1012 let item_def_id = tcx.hir.local_def_id(item_id);
1013 let generics = tcx.generics_of(item_def_id);
1014 let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id).index];
1015 tcx.mk_param(index, tcx.hir.name(node_id))
1017 Def::SelfTy(_, Some(def_id)) => {
1018 // Self in impl (we know the concrete type).
1020 assert_eq!(opt_self_ty, None);
1021 self.prohibit_type_params(&path.segments);
1023 let ty = tcx.at(span).type_of(def_id);
1024 if let Some(free_substs) = self.get_free_substs() {
1025 ty.subst(tcx, free_substs)
1030 Def::SelfTy(Some(_), None) => {
1032 assert_eq!(opt_self_ty, None);
1033 self.prohibit_type_params(&path.segments);
1036 Def::AssociatedTy(def_id) => {
1037 self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1038 let trait_did = tcx.parent_def_id(def_id).unwrap();
1039 self.qpath_to_ty(span,
1042 &path.segments[path.segments.len()-2],
1043 path.segments.last().unwrap())
1045 Def::PrimTy(prim_ty) => {
1046 assert_eq!(opt_self_ty, None);
1047 self.prohibit_type_params(&path.segments);
1049 hir::TyBool => tcx.types.bool,
1050 hir::TyChar => tcx.types.char,
1051 hir::TyInt(it) => tcx.mk_mach_int(it),
1052 hir::TyUint(uit) => tcx.mk_mach_uint(uit),
1053 hir::TyFloat(ft) => tcx.mk_mach_float(ft),
1054 hir::TyStr => tcx.mk_str()
1058 self.set_tainted_by_errors();
1059 return self.tcx().types.err;
1061 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1065 /// Parses the programmer's textual representation of a type into our
1066 /// internal notion of a type.
1067 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1068 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1071 let tcx = self.tcx();
1073 let result_ty = match ast_ty.node {
1074 hir::TySlice(ref ty) => {
1075 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1077 hir::TyPtr(ref mt) => {
1078 tcx.mk_ptr(ty::TypeAndMut {
1079 ty: self.ast_ty_to_ty(&mt.ty),
1083 hir::TyRptr(ref region, ref mt) => {
1084 let r = self.ast_region_to_region(region, None);
1085 debug!("TyRef r={:?}", r);
1086 let t = self.ast_ty_to_ty(&mt.ty);
1087 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1092 hir::TyTup(ref fields) => {
1093 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1095 hir::TyBareFn(ref bf) => {
1096 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1097 let bare_fn_ty = self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl);
1099 // Find any late-bound regions declared in return type that do
1100 // not appear in the arguments. These are not wellformed.
1104 // for<'a> fn() -> &'a str <-- 'a is bad
1105 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1107 // Note that we do this check **here** and not in
1108 // `ty_of_bare_fn` because the latter is also used to make
1109 // the types for fn items, and we do not want to issue a
1110 // warning then. (Once we fix #32330, the regions we are
1111 // checking for here would be considered early bound
1113 let inputs = bare_fn_ty.inputs();
1114 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1115 &inputs.map_bound(|i| i.to_owned()));
1116 let output = bare_fn_ty.output();
1117 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1118 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1119 let br_name = match *br {
1120 ty::BrNamed(_, name) => name,
1123 bf.decl.output.span(),
1124 "anonymous bound region {:?} in return but not args",
1128 struct_span_err!(tcx.sess,
1131 "return type references lifetime `{}`, \
1132 which does not appear in the fn input types",
1136 tcx.mk_fn_ptr(bare_fn_ty)
1138 hir::TyTraitObject(ref bounds, ref lifetime) => {
1139 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1141 hir::TyImplTrait(_) => {
1142 // Figure out if we can allow an `impl Trait` here, by walking up
1143 // to a `fn` or inherent `impl` method, going only through `Ty`
1144 // or `TraitRef` nodes (as nothing else should be in types) and
1145 // ensuring that we reach the `fn`/method signature's return type.
1146 let mut node_id = ast_ty.id;
1147 let fn_decl = loop {
1148 let parent = tcx.hir.get_parent_node(node_id);
1149 match tcx.hir.get(parent) {
1150 hir::map::NodeItem(&hir::Item {
1151 node: hir::ItemFn(ref fn_decl, ..), ..
1152 }) => break Some(fn_decl),
1154 hir::map::NodeImplItem(&hir::ImplItem {
1155 node: hir::ImplItemKind::Method(ref sig, _), ..
1157 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1158 hir::ItemImpl(.., None, _, _) => {
1159 break Some(&sig.decl)
1165 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1171 let allow = fn_decl.map_or(false, |fd| {
1173 hir::DefaultReturn(_) => false,
1174 hir::Return(ref ty) => ty.id == node_id
1178 // Create the anonymized type.
1180 let def_id = tcx.hir.local_def_id(ast_ty.id);
1181 tcx.mk_anon(def_id, Substs::identity_for_item(tcx, def_id))
1183 span_err!(tcx.sess, ast_ty.span, E0562,
1184 "`impl Trait` not allowed outside of function \
1185 and inherent method return types");
1189 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1190 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1191 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1192 self.ast_ty_to_ty(qself)
1194 self.def_to_ty(opt_self_ty, path, false)
1196 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1197 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1198 let ty = self.ast_ty_to_ty(qself);
1200 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1205 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1207 hir::TyArray(ref ty, length) => {
1208 if let Ok(length) = eval_length(tcx, length, "array length") {
1209 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1211 self.tcx().types.err
1214 hir::TyTypeof(ref _e) => {
1215 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1216 "`typeof` is a reserved keyword but unimplemented")
1217 .span_label(ast_ty.span, "reserved keyword")
1223 // TyInfer also appears as the type of arguments or return
1224 // values in a ExprClosure, or as
1225 // the type of local variables. Both of these cases are
1226 // handled specially and will not descend into this routine.
1227 self.ty_infer(ast_ty.span)
1237 pub fn ty_of_arg(&self,
1239 expected_ty: Option<Ty<'tcx>>)
1243 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1244 hir::TyInfer => self.ty_infer(ty.span),
1245 _ => self.ast_ty_to_ty(ty),
1249 pub fn ty_of_fn(&self,
1250 unsafety: hir::Unsafety,
1253 -> ty::PolyFnSig<'tcx> {
1256 let input_tys: Vec<Ty> =
1257 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1259 let output_ty = match decl.output {
1260 hir::Return(ref output) => self.ast_ty_to_ty(output),
1261 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1264 debug!("ty_of_fn: output_ty={:?}", output_ty);
1266 ty::Binder(self.tcx().mk_fn_sig(
1267 input_tys.into_iter(),
1275 pub fn ty_of_closure(&self,
1276 unsafety: hir::Unsafety,
1279 expected_sig: Option<ty::FnSig<'tcx>>)
1280 -> ty::PolyFnSig<'tcx>
1282 debug!("ty_of_closure(expected_sig={:?})",
1285 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1286 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1287 // no guarantee that the correct number of expected args
1289 if i < e.inputs().len() {
1295 self.ty_of_arg(a, expected_arg_ty)
1298 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1300 let is_infer = match decl.output {
1301 hir::Return(ref output) if output.node == hir::TyInfer => true,
1302 hir::DefaultReturn(..) => true,
1306 let output_ty = match decl.output {
1307 _ if is_infer && expected_ret_ty.is_some() =>
1308 expected_ret_ty.unwrap(),
1309 _ if is_infer => self.ty_infer(decl.output.span()),
1310 hir::Return(ref output) =>
1311 self.ast_ty_to_ty(&output),
1312 hir::DefaultReturn(..) => bug!(),
1315 debug!("ty_of_closure: output_ty={:?}", output_ty);
1317 ty::Binder(self.tcx().mk_fn_sig(
1326 /// Given the bounds on an object, determines what single region bound (if any) we can
1327 /// use to summarize this type. The basic idea is that we will use the bound the user
1328 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1329 /// for region bounds. It may be that we can derive no bound at all, in which case
1330 /// we return `None`.
1331 fn compute_object_lifetime_bound(&self,
1333 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1334 -> Option<ty::Region<'tcx>> // if None, use the default
1336 let tcx = self.tcx();
1338 debug!("compute_opt_region_bound(existential_predicates={:?})",
1339 existential_predicates);
1341 // No explicit region bound specified. Therefore, examine trait
1342 // bounds and see if we can derive region bounds from those.
1343 let derived_region_bounds =
1344 object_region_bounds(tcx, existential_predicates);
1346 // If there are no derived region bounds, then report back that we
1347 // can find no region bound. The caller will use the default.
1348 if derived_region_bounds.is_empty() {
1352 // If any of the derived region bounds are 'static, that is always
1354 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1355 return Some(tcx.types.re_static);
1358 // Determine whether there is exactly one unique region in the set
1359 // of derived region bounds. If so, use that. Otherwise, report an
1361 let r = derived_region_bounds[0];
1362 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1363 span_err!(tcx.sess, span, E0227,
1364 "ambiguous lifetime bound, explicit lifetime bound required");
1370 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1371 /// remaining general trait bounds.
1372 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1373 trait_bounds: &'b [hir::PolyTraitRef])
1374 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1376 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1377 match bound.trait_ref.path.def {
1378 Def::Trait(trait_did) => {
1379 // Checks whether `trait_did` refers to one of the builtin
1380 // traits, like `Send`, and adds it to `auto_traits` if so.
1381 if Some(trait_did) == tcx.lang_items.send_trait() ||
1382 Some(trait_did) == tcx.lang_items.sync_trait() {
1383 let segments = &bound.trait_ref.path.segments;
1384 let parameters = &segments[segments.len() - 1].parameters;
1385 if !parameters.types().is_empty() {
1386 check_type_argument_count(tcx, bound.trait_ref.path.span,
1387 parameters.types().len(), &[]);
1389 if !parameters.lifetimes().is_empty() {
1390 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1391 parameters.lifetimes().len(), 0);
1402 let auto_traits = auto_traits.into_iter().map(|tr| {
1403 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1408 }).collect::<Vec<_>>();
1410 (auto_traits, trait_bounds)
1413 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1414 ty_param_defs: &[ty::TypeParameterDef]) {
1415 let accepted = ty_param_defs.len();
1416 let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1417 if supplied < required {
1418 let expected = if required < accepted {
1423 let arguments_plural = if required == 1 { "" } else { "s" };
1425 struct_span_err!(tcx.sess, span, E0243,
1426 "wrong number of type arguments: {} {}, found {}",
1427 expected, required, supplied)
1429 format!("{} {} type argument{}",
1434 } else if supplied > accepted {
1435 let expected = if required < accepted {
1436 format!("expected at most {}", accepted)
1438 format!("expected {}", accepted)
1440 let arguments_plural = if accepted == 1 { "" } else { "s" };
1442 struct_span_err!(tcx.sess, span, E0244,
1443 "wrong number of type arguments: {}, found {}",
1447 format!("{} type argument{}",
1448 if accepted == 0 { "expected no" } else { &expected },
1455 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1456 let label = if number < expected {
1458 format!("expected {} lifetime parameter", expected)
1460 format!("expected {} lifetime parameters", expected)
1463 let additional = number - expected;
1464 if additional == 1 {
1465 "unexpected lifetime parameter".to_string()
1467 format!("{} unexpected lifetime parameters", additional)
1470 struct_span_err!(tcx.sess, span, E0107,
1471 "wrong number of lifetime parameters: expected {}, found {}",
1473 .span_label(span, label)
1477 // A helper struct for conveniently grouping a set of bounds which we pass to
1478 // and return from functions in multiple places.
1479 #[derive(PartialEq, Eq, Clone, Debug)]
1480 pub struct Bounds<'tcx> {
1481 pub region_bounds: Vec<ty::Region<'tcx>>,
1482 pub implicitly_sized: bool,
1483 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1484 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1487 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1488 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1489 -> Vec<ty::Predicate<'tcx>>
1491 let mut vec = Vec::new();
1493 // If it could be sized, and is, add the sized predicate
1494 if self.implicitly_sized {
1495 if let Some(sized) = tcx.lang_items.sized_trait() {
1496 let trait_ref = ty::TraitRef {
1498 substs: tcx.mk_substs_trait(param_ty, &[])
1500 vec.push(trait_ref.to_predicate());
1504 for ®ion_bound in &self.region_bounds {
1505 // account for the binder being introduced below; no need to shift `param_ty`
1506 // because, at present at least, it can only refer to early-bound regions
1507 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1508 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1511 for bound_trait_ref in &self.trait_bounds {
1512 vec.push(bound_trait_ref.to_predicate());
1515 for projection in &self.projection_bounds {
1516 vec.push(projection.to_predicate());
1523 pub enum ExplicitSelf<'tcx> {
1525 ByReference(ty::Region<'tcx>, hir::Mutability),
1529 impl<'tcx> ExplicitSelf<'tcx> {
1530 /// We wish to (for now) categorize an explicit self
1531 /// declaration like `self: SomeType` into either `self`,
1532 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1533 /// by some simple pattern matching. A more precise check
1534 /// is done later in `check_method_self_type()`.
1539 /// impl Foo for &T {
1540 /// // Legal declarations:
1541 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1542 /// fn method2(self: &T); // ExplicitSelf::ByValue
1543 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1545 /// // Invalid cases will be caught later by `check_method_self_type`:
1546 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1550 /// To do the check we just count the number of "modifiers"
1551 /// on each type and compare them. If they are the same or
1552 /// the impl has more, we call it "by value". Otherwise, we
1553 /// look at the outermost modifier on the method decl and
1554 /// call it by-ref, by-box as appropriate. For method1, for
1555 /// example, the impl type has one modifier, but the method
1556 /// type has two, so we end up with
1557 /// ExplicitSelf::ByReference.
1558 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1559 self_arg_ty: Ty<'tcx>)
1560 -> ExplicitSelf<'tcx> {
1561 fn count_modifiers(ty: Ty) -> usize {
1563 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1564 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1569 let impl_modifiers = count_modifiers(untransformed_self_ty);
1570 let method_modifiers = count_modifiers(self_arg_ty);
1572 if impl_modifiers >= method_modifiers {
1573 ExplicitSelf::ByValue
1575 match self_arg_ty.sty {
1576 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1577 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1578 _ => ExplicitSelf::ByValue,