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;
28 use util::nodemap::FxHashSet;
31 use syntax::{abi, ast};
32 use syntax::feature_gate::{GateIssue, emit_feature_err};
35 pub trait AstConv<'gcx, 'tcx> {
36 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
38 /// Returns the set of bounds in scope for the type parameter with
40 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
41 -> ty::GenericPredicates<'tcx>;
43 /// What lifetime should we use when a lifetime is omitted (and not elided)?
44 fn re_infer(&self, span: Span, _def: Option<&ty::RegionParameterDef>)
45 -> Option<ty::Region<'tcx>>;
47 /// What type should we use when a type is omitted?
48 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
50 /// Same as ty_infer, but with a known type parameter definition.
51 fn ty_infer_for_def(&self,
52 _def: &ty::TypeParameterDef,
53 _substs: &[Kind<'tcx>],
54 span: Span) -> Ty<'tcx> {
58 /// Projecting an associated type from a (potentially)
59 /// higher-ranked trait reference is more complicated, because of
60 /// the possibility of late-bound regions appearing in the
61 /// associated type binding. This is not legal in function
62 /// signatures for that reason. In a function body, we can always
63 /// handle it because we can use inference variables to remove the
64 /// late-bound regions.
65 fn projected_ty_from_poly_trait_ref(&self,
68 poly_trait_ref: ty::PolyTraitRef<'tcx>)
71 /// Normalize an associated type coming from the user.
72 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
74 /// Invoked when we encounter an error from some prior pass
75 /// (e.g. resolve) that is translated into a ty-error. This is
76 /// used to help suppress derived errors typeck might otherwise
78 fn set_tainted_by_errors(&self);
81 struct ConvertedBinding<'tcx> {
87 /// Dummy type used for the `Self` of a `TraitRef` created for converting
88 /// a trait object, and which gets removed in `ExistentialTraitRef`.
89 /// This type must not appear anywhere in other converted types.
90 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
92 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
93 pub fn ast_region_to_region(&self,
94 lifetime: &hir::Lifetime,
95 def: Option<&ty::RegionParameterDef>)
99 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
100 Some(&rl::Region::Static) => {
104 Some(&rl::Region::LateBound(debruijn, id)) => {
105 let name = tcx.hir.name(id);
106 tcx.mk_region(ty::ReLateBound(debruijn,
107 ty::BrNamed(tcx.hir.local_def_id(id), name)))
110 Some(&rl::Region::LateBoundAnon(debruijn, index)) => {
111 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
114 Some(&rl::Region::EarlyBound(index, id)) => {
115 let name = tcx.hir.name(id);
116 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
117 def_id: tcx.hir.local_def_id(id),
123 Some(&rl::Region::Free(scope, id)) => {
124 let name = tcx.hir.name(id);
125 tcx.mk_region(ty::ReFree(ty::FreeRegion {
127 bound_region: ty::BrNamed(tcx.hir.local_def_id(id), name)
130 // (*) -- not late-bound, won't change
134 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
138 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
145 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
146 /// returns an appropriate set of substitutions for this particular reference to `I`.
147 pub fn ast_path_substs_for_ty(&self,
150 item_segment: &hir::PathSegment)
151 -> &'tcx Substs<'tcx>
153 let (substs, assoc_bindings) =
154 self.create_substs_for_ast_path(span,
156 &item_segment.parameters,
159 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
164 /// Given the type/region arguments provided to some path (along with
165 /// an implicit Self, if this is a trait reference) returns the complete
166 /// set of substitutions. This may involve applying defaulted type parameters.
168 /// Note that the type listing given here is *exactly* what the user provided.
169 fn create_substs_for_ast_path(&self,
172 parameters: &hir::PathParameters,
173 self_ty: Option<Ty<'tcx>>)
174 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
176 let tcx = self.tcx();
178 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
180 def_id, self_ty, parameters);
182 // If the type is parameterized by this region, then replace this
183 // region with the current anon region binding (in other words,
184 // whatever & would get replaced with).
185 let decl_generics = tcx.generics_of(def_id);
186 let num_types_provided = parameters.types.len();
187 let expected_num_region_params = decl_generics.regions.len();
188 let supplied_num_region_params = parameters.lifetimes.len();
189 if expected_num_region_params != supplied_num_region_params {
190 report_lifetime_number_error(tcx, span,
191 supplied_num_region_params,
192 expected_num_region_params);
195 // If a self-type was declared, one should be provided.
196 assert_eq!(decl_generics.has_self, self_ty.is_some());
198 // Check the number of type parameters supplied by the user.
199 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
200 if !parameters.infer_types || num_types_provided > ty_param_defs.len() {
201 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
204 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
205 let default_needs_object_self = |p: &ty::TypeParameterDef| {
206 if is_object && p.has_default {
207 if tcx.at(span).type_of(p.def_id).has_self_ty() {
208 // There is no suitable inference default for a type parameter
209 // that references self, in an object type.
217 let substs = Substs::for_item(tcx, def_id, |def, _| {
218 let i = def.index as usize - self_ty.is_some() as usize;
219 if let Some(lifetime) = parameters.lifetimes.get(i) {
220 self.ast_region_to_region(lifetime, Some(def))
225 let i = def.index as usize;
227 // Handle Self first, so we can adjust the index to match the AST.
228 if let (0, Some(ty)) = (i, self_ty) {
232 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
233 if i < num_types_provided {
234 // A provided type parameter.
235 self.ast_ty_to_ty(¶meters.types[i])
236 } else if parameters.infer_types {
237 // No type parameters were provided, we can infer all.
238 let ty_var = if !default_needs_object_self(def) {
239 self.ty_infer_for_def(def, substs, span)
244 } else if def.has_default {
245 // No type parameter provided, but a default exists.
247 // If we are converting an object type, then the
248 // `Self` parameter is unknown. However, some of the
249 // other type parameters may reference `Self` in their
250 // defaults. This will lead to an ICE if we are not
252 if default_needs_object_self(def) {
253 struct_span_err!(tcx.sess, span, E0393,
254 "the type parameter `{}` must be explicitly specified",
256 .span_label(span, format!("missing reference to `{}`", def.name))
257 .note(&format!("because of the default `Self` reference, \
258 type parameters must be specified on object types"))
262 // This is a default type parameter.
265 tcx.at(span).type_of(def.def_id)
266 .subst_spanned(tcx, substs, Some(span))
270 // We've already errored above about the mismatch.
275 let assoc_bindings = parameters.bindings.iter().map(|binding| {
277 item_name: binding.name,
278 ty: self.ast_ty_to_ty(&binding.ty),
283 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
284 decl_generics, self_ty, substs);
286 (substs, assoc_bindings)
289 /// Instantiates the path for the given trait reference, assuming that it's
290 /// bound to a valid trait type. Returns the def_id for the defining trait.
291 /// Fails if the type is a type other than a trait type.
293 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
294 /// are disallowed. Otherwise, they are pushed onto the vector given.
295 pub fn instantiate_mono_trait_ref(&self,
296 trait_ref: &hir::TraitRef,
298 -> ty::TraitRef<'tcx>
300 self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
302 let trait_def_id = self.trait_def_id(trait_ref);
303 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
306 trait_ref.path.segments.last().unwrap())
309 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
310 let path = &trait_ref.path;
312 Def::Trait(trait_def_id) => trait_def_id,
314 self.tcx().sess.fatal("cannot continue compilation due to previous error");
317 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
318 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
323 pub fn instantiate_poly_trait_ref(&self,
324 ast_trait_ref: &hir::PolyTraitRef,
326 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
327 -> ty::PolyTraitRef<'tcx>
329 let trait_ref = &ast_trait_ref.trait_ref;
330 let trait_def_id = self.trait_def_id(trait_ref);
332 debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
334 self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
336 let (substs, assoc_bindings) =
337 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
340 trait_ref.path.segments.last().unwrap());
341 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
343 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
344 // specify type to assert that error was already reported in Err case:
345 let predicate: Result<_, ErrorReported> =
346 self.ast_type_binding_to_poly_projection_predicate(trait_ref.ref_id,
349 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
352 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
353 trait_ref, poly_projections, poly_trait_ref);
357 fn ast_path_to_mono_trait_ref(&self,
361 trait_segment: &hir::PathSegment)
362 -> ty::TraitRef<'tcx>
364 let (substs, assoc_bindings) =
365 self.create_substs_for_ast_trait_ref(span,
369 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
370 ty::TraitRef::new(trait_def_id, substs)
373 fn create_substs_for_ast_trait_ref(&self,
377 trait_segment: &hir::PathSegment)
378 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
380 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
383 let trait_def = self.tcx().trait_def(trait_def_id);
385 if !self.tcx().sess.features.borrow().unboxed_closures &&
386 trait_segment.parameters.parenthesized != trait_def.paren_sugar {
387 // For now, require that parenthetical notation be used only with `Fn()` etc.
388 let msg = if trait_def.paren_sugar {
389 "the precise format of `Fn`-family traits' type parameters is subject to change. \
390 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
392 "parenthetical notation is only stable when used with `Fn`-family traits"
394 emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
395 span, GateIssue::Language, msg);
398 self.create_substs_for_ast_path(span,
400 &trait_segment.parameters,
404 fn trait_defines_associated_type_named(&self,
406 assoc_name: ast::Name)
409 self.tcx().associated_items(trait_def_id).any(|item| {
410 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
414 fn ast_type_binding_to_poly_projection_predicate(
416 _path_id: ast::NodeId,
417 trait_ref: ty::PolyTraitRef<'tcx>,
418 binding: &ConvertedBinding<'tcx>)
419 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
421 let tcx = self.tcx();
423 // Given something like `U : SomeTrait<T=X>`, we want to produce a
424 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
425 // subtle in the event that `T` is defined in a supertrait of
426 // `SomeTrait`, because in that case we need to upcast.
428 // That is, consider this case:
431 // trait SubTrait : SuperTrait<int> { }
432 // trait SuperTrait<A> { type T; }
434 // ... B : SubTrait<T=foo> ...
437 // We want to produce `<B as SuperTrait<int>>::T == foo`.
439 // Find any late-bound regions declared in `ty` that are not
440 // declared in the trait-ref. These are not wellformed.
444 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
445 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
446 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
447 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
448 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
449 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
450 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
451 let br_name = match *br {
452 ty::BrNamed(_, name) => name,
456 "anonymous bound region {:?} in binding but not trait ref",
460 struct_span_err!(tcx.sess,
463 "binding for associated type `{}` references lifetime `{}`, \
464 which does not appear in the trait input types",
465 binding.item_name, br_name)
469 // Simple case: X is defined in the current trait.
470 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
471 return Ok(trait_ref.map_bound(|trait_ref| {
472 ty::ProjectionPredicate {
473 projection_ty: ty::ProjectionTy::from_ref_and_name(
483 // Otherwise, we have to walk through the supertraits to find
486 traits::supertraits(tcx, trait_ref.clone())
487 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
489 let candidate = self.one_bound_for_assoc_type(candidates,
490 &trait_ref.to_string(),
491 &binding.item_name.as_str(),
494 Ok(candidate.map_bound(|trait_ref| {
495 ty::ProjectionPredicate {
496 projection_ty: ty::ProjectionTy::from_ref_and_name(
506 fn ast_path_to_ty(&self,
509 item_segment: &hir::PathSegment)
512 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
515 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
519 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
520 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
521 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
522 -> ty::ExistentialTraitRef<'tcx> {
523 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
524 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
527 fn conv_object_ty_poly_trait_ref(&self,
529 trait_bounds: &[hir::PolyTraitRef],
530 lifetime: &hir::Lifetime)
533 let tcx = self.tcx();
535 if trait_bounds.is_empty() {
536 span_err!(tcx.sess, span, E0224,
537 "at least one non-builtin trait is required for an object type");
538 return tcx.types.err;
541 let mut projection_bounds = vec![];
542 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
543 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
545 &mut projection_bounds);
547 for trait_bound in trait_bounds[1..].iter() {
548 // Sanity check for non-principal trait bounds
549 self.instantiate_poly_trait_ref(trait_bound,
554 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
556 if !trait_bounds.is_empty() {
557 let b = &trait_bounds[0];
558 let span = b.trait_ref.path.span;
559 struct_span_err!(self.tcx().sess, span, E0225,
560 "only Send/Sync traits can be used as additional traits in a trait object")
561 .span_label(span, "non-Send/Sync additional trait")
565 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
566 let existential_principal = principal.map_bound(|trait_ref| {
567 self.trait_ref_to_existential(trait_ref)
569 let existential_projections = projection_bounds.iter().map(|bound| {
570 bound.map_bound(|b| {
571 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
572 ty::ExistentialProjection {
574 item_def_id: b.projection_ty.item_def_id,
575 substs: trait_ref.substs,
580 // check that there are no gross object safety violations,
581 // most importantly, that the supertraits don't contain Self,
583 let object_safety_violations =
584 tcx.astconv_object_safety_violations(principal.def_id());
585 if !object_safety_violations.is_empty() {
586 tcx.report_object_safety_error(
587 span, principal.def_id(), object_safety_violations)
589 return tcx.types.err;
592 let mut associated_types = FxHashSet::default();
593 for tr in traits::supertraits(tcx, principal) {
594 associated_types.extend(tcx.associated_items(tr.def_id())
595 .filter(|item| item.kind == ty::AssociatedKind::Type)
596 .map(|item| item.def_id));
599 for projection_bound in &projection_bounds {
600 associated_types.remove(&projection_bound.0.projection_ty.item_def_id);
603 for item_def_id in associated_types {
604 let assoc_item = tcx.associated_item(item_def_id);
605 let trait_def_id = assoc_item.container.id();
606 struct_span_err!(tcx.sess, span, E0191,
607 "the value of the associated type `{}` (from the trait `{}`) must be specified",
609 tcx.item_path_str(trait_def_id))
610 .span_label(span, format!(
611 "missing associated type `{}` value", assoc_item.name))
616 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
617 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
618 .chain(existential_projections
619 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
620 .collect::<AccumulateVec<[_; 8]>>();
621 v.sort_by(|a, b| a.cmp(tcx, b));
622 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
625 // Explicitly specified region bound. Use that.
626 let region_bound = if !lifetime.is_elided() {
627 self.ast_region_to_region(lifetime, None)
629 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
630 if tcx.named_region_map.defs.contains_key(&lifetime.id) {
631 self.ast_region_to_region(lifetime, None)
633 self.re_infer(span, None).unwrap_or_else(|| {
634 span_err!(tcx.sess, span, E0228,
635 "the lifetime bound for this object type cannot be deduced \
636 from context; please supply an explicit bound");
643 debug!("region_bound: {:?}", region_bound);
645 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
646 debug!("trait_object_type: {:?}", ty);
650 fn report_ambiguous_associated_type(&self,
655 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
656 .span_label(span, "ambiguous associated type")
657 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
658 type_str, trait_str, name))
663 // Search for a bound on a type parameter which includes the associated item
664 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
665 // This function will fail if there are no suitable bounds or there is
667 fn find_bound_for_assoc_item(&self,
668 ty_param_def_id: DefId,
669 assoc_name: ast::Name,
671 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
673 let tcx = self.tcx();
675 let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
676 .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
678 // Check that there is exactly one way to find an associated type with the
680 let suitable_bounds =
681 traits::transitive_bounds(tcx, &bounds)
682 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
684 let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
685 let param_name = tcx.hir.ty_param_name(param_node_id);
686 self.one_bound_for_assoc_type(suitable_bounds,
687 ¶m_name.as_str(),
688 &assoc_name.as_str(),
693 // Checks that bounds contains exactly one element and reports appropriate
695 fn one_bound_for_assoc_type<I>(&self,
700 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
701 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
703 let bound = match bounds.next() {
704 Some(bound) => bound,
706 struct_span_err!(self.tcx().sess, span, E0220,
707 "associated type `{}` not found for `{}`",
710 .span_label(span, format!("associated type `{}` not found", assoc_name))
712 return Err(ErrorReported);
716 if let Some(bound2) = bounds.next() {
717 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
718 let mut err = struct_span_err!(
719 self.tcx().sess, span, E0221,
720 "ambiguous associated type `{}` in bounds of `{}`",
723 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
725 for bound in bounds {
726 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
727 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
729 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
731 if let Some(span) = bound_span {
732 err.span_label(span, format!("ambiguous `{}` from `{}`",
736 span_note!(&mut err, span,
737 "associated type `{}` could derive from `{}`",
748 // Create a type from a path to an associated type.
749 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
750 // and item_segment is the path segment for D. We return a type and a def for
752 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
753 // parameter or Self.
754 pub fn associated_path_def_to_ty(&self,
759 item_segment: &hir::PathSegment)
762 let tcx = self.tcx();
763 let assoc_name = item_segment.name;
765 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
767 self.prohibit_type_params(slice::ref_slice(item_segment));
769 // Find the type of the associated item, and the trait where the associated
771 let bound = match (&ty.sty, ty_path_def) {
772 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
773 // `Self` in an impl of a trait - we have a concrete self type and a
775 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
776 Some(trait_ref) => trait_ref,
778 // A cycle error occurred, most likely.
779 return (tcx.types.err, Def::Err);
784 traits::supertraits(tcx, ty::Binder(trait_ref))
785 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
788 match self.one_bound_for_assoc_type(candidates,
790 &assoc_name.as_str(),
793 Err(ErrorReported) => return (tcx.types.err, Def::Err),
796 (&ty::TyParam(_), Def::SelfTy(Some(param_did), None)) |
797 (&ty::TyParam(_), Def::TyParam(param_did)) => {
798 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
800 Err(ErrorReported) => return (tcx.types.err, Def::Err),
804 // Don't print TyErr to the user.
805 if !ty.references_error() {
806 self.report_ambiguous_associated_type(span,
809 &assoc_name.as_str());
811 return (tcx.types.err, Def::Err);
815 let trait_did = bound.0.def_id;
816 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name)
817 .expect("missing associated type");
819 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
820 let ty = self.normalize_ty(span, ty);
822 let def = Def::AssociatedTy(item.def_id);
823 let def_scope = tcx.adjust(assoc_name, item.container.id(), ref_id).1;
824 if !item.vis.is_accessible_from(def_scope, tcx) {
825 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
826 tcx.sess.span_err(span, &msg);
828 tcx.check_stability(item.def_id, ref_id, span);
833 fn qpath_to_ty(&self,
835 opt_self_ty: Option<Ty<'tcx>>,
837 trait_segment: &hir::PathSegment,
838 item_segment: &hir::PathSegment)
841 let tcx = self.tcx();
842 let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
844 self.prohibit_type_params(slice::ref_slice(item_segment));
846 let self_ty = if let Some(ty) = opt_self_ty {
849 let path_str = tcx.item_path_str(trait_def_id);
850 self.report_ambiguous_associated_type(span,
853 &item_segment.name.as_str());
854 return tcx.types.err;
857 debug!("qpath_to_ty: self_type={:?}", self_ty);
859 let trait_ref = self.ast_path_to_mono_trait_ref(span,
864 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
866 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
869 pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
870 for segment in segments {
871 for typ in &segment.parameters.types {
872 struct_span_err!(self.tcx().sess, typ.span, E0109,
873 "type parameters are not allowed on this type")
874 .span_label(typ.span, "type parameter not allowed")
878 for lifetime in &segment.parameters.lifetimes {
879 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
880 "lifetime parameters are not allowed on this type")
881 .span_label(lifetime.span,
882 "lifetime parameter not allowed on this type")
886 for binding in &segment.parameters.bindings {
887 self.prohibit_projection(binding.span);
893 pub fn prohibit_projection(&self, span: Span) {
894 let mut err = struct_span_err!(self.tcx().sess, span, E0229,
895 "associated type bindings are not allowed here");
896 err.span_label(span, "associated type not allowed here").emit();
899 // Check a type Path and convert it to a Ty.
900 pub fn def_to_ty(&self,
901 opt_self_ty: Option<Ty<'tcx>>,
903 permit_variants: bool)
905 let tcx = self.tcx();
907 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
908 path.def, opt_self_ty, path.segments);
910 let span = path.span;
912 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
913 assert_eq!(opt_self_ty, None);
914 self.prohibit_type_params(path.segments.split_last().unwrap().1);
915 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
917 Def::Variant(did) if permit_variants => {
918 // Convert "variant type" as if it were a real type.
919 // The resulting `Ty` is type of the variant's enum for now.
920 assert_eq!(opt_self_ty, None);
921 self.prohibit_type_params(path.segments.split_last().unwrap().1);
922 self.ast_path_to_ty(span,
923 tcx.parent_def_id(did).unwrap(),
924 path.segments.last().unwrap())
926 Def::TyParam(did) => {
927 assert_eq!(opt_self_ty, None);
928 self.prohibit_type_params(&path.segments);
930 let node_id = tcx.hir.as_local_node_id(did).unwrap();
931 let item_id = tcx.hir.get_parent_node(node_id);
932 let item_def_id = tcx.hir.local_def_id(item_id);
933 let generics = tcx.generics_of(item_def_id);
934 let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id).index];
935 tcx.mk_param(index, tcx.hir.name(node_id))
937 Def::SelfTy(_, Some(def_id)) => {
938 // Self in impl (we know the concrete type).
940 assert_eq!(opt_self_ty, None);
941 self.prohibit_type_params(&path.segments);
943 tcx.at(span).type_of(def_id)
945 Def::SelfTy(Some(_), None) => {
947 assert_eq!(opt_self_ty, None);
948 self.prohibit_type_params(&path.segments);
951 Def::AssociatedTy(def_id) => {
952 self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
953 self.qpath_to_ty(span,
956 &path.segments[path.segments.len()-2],
957 path.segments.last().unwrap())
959 Def::PrimTy(prim_ty) => {
960 assert_eq!(opt_self_ty, None);
961 self.prohibit_type_params(&path.segments);
963 hir::TyBool => tcx.types.bool,
964 hir::TyChar => tcx.types.char,
965 hir::TyInt(it) => tcx.mk_mach_int(it),
966 hir::TyUint(uit) => tcx.mk_mach_uint(uit),
967 hir::TyFloat(ft) => tcx.mk_mach_float(ft),
968 hir::TyStr => tcx.mk_str()
972 self.set_tainted_by_errors();
973 return self.tcx().types.err;
975 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
979 /// Parses the programmer's textual representation of a type into our
980 /// internal notion of a type.
981 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
982 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
985 let tcx = self.tcx();
987 let result_ty = match ast_ty.node {
988 hir::TySlice(ref ty) => {
989 tcx.mk_slice(self.ast_ty_to_ty(&ty))
991 hir::TyPtr(ref mt) => {
992 tcx.mk_ptr(ty::TypeAndMut {
993 ty: self.ast_ty_to_ty(&mt.ty),
997 hir::TyRptr(ref region, ref mt) => {
998 let r = self.ast_region_to_region(region, None);
999 debug!("TyRef r={:?}", r);
1000 let t = self.ast_ty_to_ty(&mt.ty);
1001 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1006 hir::TyTup(ref fields) => {
1007 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1009 hir::TyBareFn(ref bf) => {
1010 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1011 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1013 hir::TyTraitObject(ref bounds, ref lifetime) => {
1014 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1016 hir::TyImplTrait(_) => {
1017 // Figure out if we can allow an `impl Trait` here, by walking up
1018 // to a `fn` or inherent `impl` method, going only through `Ty`
1019 // or `TraitRef` nodes (as nothing else should be in types) and
1020 // ensuring that we reach the `fn`/method signature's return type.
1021 let mut node_id = ast_ty.id;
1022 let fn_decl = loop {
1023 let parent = tcx.hir.get_parent_node(node_id);
1024 match tcx.hir.get(parent) {
1025 hir::map::NodeItem(&hir::Item {
1026 node: hir::ItemFn(ref fn_decl, ..), ..
1027 }) => break Some(fn_decl),
1029 hir::map::NodeImplItem(&hir::ImplItem {
1030 node: hir::ImplItemKind::Method(ref sig, _), ..
1032 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1033 hir::ItemImpl(.., None, _, _) => {
1034 break Some(&sig.decl)
1040 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1046 let allow = fn_decl.map_or(false, |fd| {
1048 hir::DefaultReturn(_) => false,
1049 hir::Return(ref ty) => ty.id == node_id
1053 // Create the anonymized type.
1055 let def_id = tcx.hir.local_def_id(ast_ty.id);
1056 tcx.mk_anon(def_id, Substs::identity_for_item(tcx, def_id))
1058 span_err!(tcx.sess, ast_ty.span, E0562,
1059 "`impl Trait` not allowed outside of function \
1060 and inherent method return types");
1064 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1065 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1066 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1067 self.ast_ty_to_ty(qself)
1069 self.def_to_ty(opt_self_ty, path, false)
1071 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1072 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1073 let ty = self.ast_ty_to_ty(qself);
1075 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1080 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1082 hir::TyArray(ref ty, length) => {
1083 if let Ok(length) = eval_length(tcx, length, "array length") {
1084 tcx.mk_array(self.ast_ty_to_ty(&ty), length)
1086 self.tcx().types.err
1089 hir::TyTypeof(ref _e) => {
1090 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1091 "`typeof` is a reserved keyword but unimplemented")
1092 .span_label(ast_ty.span, "reserved keyword")
1098 // TyInfer also appears as the type of arguments or return
1099 // values in a ExprClosure, or as
1100 // the type of local variables. Both of these cases are
1101 // handled specially and will not descend into this routine.
1102 self.ty_infer(ast_ty.span)
1112 pub fn ty_of_arg(&self,
1114 expected_ty: Option<Ty<'tcx>>)
1118 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1119 hir::TyInfer => self.ty_infer(ty.span),
1120 _ => self.ast_ty_to_ty(ty),
1124 pub fn ty_of_fn(&self,
1125 unsafety: hir::Unsafety,
1128 -> ty::PolyFnSig<'tcx> {
1131 let tcx = self.tcx();
1132 let input_tys: Vec<Ty> =
1133 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1135 let output_ty = match decl.output {
1136 hir::Return(ref output) => self.ast_ty_to_ty(output),
1137 hir::DefaultReturn(..) => tcx.mk_nil(),
1140 debug!("ty_of_fn: output_ty={:?}", output_ty);
1142 let bare_fn_ty = ty::Binder(tcx.mk_fn_sig(
1143 input_tys.into_iter(),
1150 // Find any late-bound regions declared in return type that do
1151 // not appear in the arguments. These are not wellformed.
1154 // for<'a> fn() -> &'a str <-- 'a is bad
1155 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1156 let inputs = bare_fn_ty.inputs();
1157 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1158 &inputs.map_bound(|i| i.to_owned()));
1159 let output = bare_fn_ty.output();
1160 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1161 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1162 let br_name = match *br {
1163 ty::BrNamed(_, name) => name,
1167 "anonymous bound region {:?} in return but not args",
1171 struct_span_err!(tcx.sess,
1174 "return type references lifetime `{}`, \
1175 which does not appear in the fn input types",
1183 pub fn ty_of_closure(&self,
1184 unsafety: hir::Unsafety,
1187 expected_sig: Option<ty::FnSig<'tcx>>)
1188 -> ty::PolyFnSig<'tcx>
1190 debug!("ty_of_closure(expected_sig={:?})",
1193 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1194 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1195 // no guarantee that the correct number of expected args
1197 if i < e.inputs().len() {
1203 self.ty_of_arg(a, expected_arg_ty)
1206 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1208 let is_infer = match decl.output {
1209 hir::Return(ref output) if output.node == hir::TyInfer => true,
1210 hir::DefaultReturn(..) => true,
1214 let output_ty = match decl.output {
1215 _ if is_infer && expected_ret_ty.is_some() =>
1216 expected_ret_ty.unwrap(),
1217 _ if is_infer => self.ty_infer(decl.output.span()),
1218 hir::Return(ref output) =>
1219 self.ast_ty_to_ty(&output),
1220 hir::DefaultReturn(..) => bug!(),
1223 debug!("ty_of_closure: output_ty={:?}", output_ty);
1225 ty::Binder(self.tcx().mk_fn_sig(
1234 /// Given the bounds on an object, determines what single region bound (if any) we can
1235 /// use to summarize this type. The basic idea is that we will use the bound the user
1236 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1237 /// for region bounds. It may be that we can derive no bound at all, in which case
1238 /// we return `None`.
1239 fn compute_object_lifetime_bound(&self,
1241 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1242 -> Option<ty::Region<'tcx>> // if None, use the default
1244 let tcx = self.tcx();
1246 debug!("compute_opt_region_bound(existential_predicates={:?})",
1247 existential_predicates);
1249 // No explicit region bound specified. Therefore, examine trait
1250 // bounds and see if we can derive region bounds from those.
1251 let derived_region_bounds =
1252 object_region_bounds(tcx, existential_predicates);
1254 // If there are no derived region bounds, then report back that we
1255 // can find no region bound. The caller will use the default.
1256 if derived_region_bounds.is_empty() {
1260 // If any of the derived region bounds are 'static, that is always
1262 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1263 return Some(tcx.types.re_static);
1266 // Determine whether there is exactly one unique region in the set
1267 // of derived region bounds. If so, use that. Otherwise, report an
1269 let r = derived_region_bounds[0];
1270 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1271 span_err!(tcx.sess, span, E0227,
1272 "ambiguous lifetime bound, explicit lifetime bound required");
1278 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1279 /// remaining general trait bounds.
1280 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1281 trait_bounds: &'b [hir::PolyTraitRef])
1282 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1284 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1285 match bound.trait_ref.path.def {
1286 Def::Trait(trait_did) => {
1287 // Checks whether `trait_did` refers to one of the builtin
1288 // traits, like `Send`, and adds it to `auto_traits` if so.
1289 if Some(trait_did) == tcx.lang_items.send_trait() ||
1290 Some(trait_did) == tcx.lang_items.sync_trait() {
1291 let segments = &bound.trait_ref.path.segments;
1292 let parameters = &segments[segments.len() - 1].parameters;
1293 if !parameters.types.is_empty() {
1294 check_type_argument_count(tcx, bound.trait_ref.path.span,
1295 parameters.types.len(), &[]);
1297 if !parameters.lifetimes.is_empty() {
1298 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1299 parameters.lifetimes.len(), 0);
1310 let auto_traits = auto_traits.into_iter().map(|tr| {
1311 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1316 }).collect::<Vec<_>>();
1318 (auto_traits, trait_bounds)
1321 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1322 ty_param_defs: &[ty::TypeParameterDef]) {
1323 let accepted = ty_param_defs.len();
1324 let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1325 if supplied < required {
1326 let expected = if required < accepted {
1331 let arguments_plural = if required == 1 { "" } else { "s" };
1333 struct_span_err!(tcx.sess, span, E0243,
1334 "wrong number of type arguments: {} {}, found {}",
1335 expected, required, supplied)
1337 format!("{} {} type argument{}",
1342 } else if supplied > accepted {
1343 let expected = if required < accepted {
1344 format!("expected at most {}", accepted)
1346 format!("expected {}", accepted)
1348 let arguments_plural = if accepted == 1 { "" } else { "s" };
1350 struct_span_err!(tcx.sess, span, E0244,
1351 "wrong number of type arguments: {}, found {}",
1355 format!("{} type argument{}",
1356 if accepted == 0 { "expected no" } else { &expected },
1363 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1364 let label = if number < expected {
1366 format!("expected {} lifetime parameter", expected)
1368 format!("expected {} lifetime parameters", expected)
1371 let additional = number - expected;
1372 if additional == 1 {
1373 "unexpected lifetime parameter".to_string()
1375 format!("{} unexpected lifetime parameters", additional)
1378 struct_span_err!(tcx.sess, span, E0107,
1379 "wrong number of lifetime parameters: expected {}, found {}",
1381 .span_label(span, label)
1385 // A helper struct for conveniently grouping a set of bounds which we pass to
1386 // and return from functions in multiple places.
1387 #[derive(PartialEq, Eq, Clone, Debug)]
1388 pub struct Bounds<'tcx> {
1389 pub region_bounds: Vec<ty::Region<'tcx>>,
1390 pub implicitly_sized: bool,
1391 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1392 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1395 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1396 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1397 -> Vec<ty::Predicate<'tcx>>
1399 let mut vec = Vec::new();
1401 // If it could be sized, and is, add the sized predicate
1402 if self.implicitly_sized {
1403 if let Some(sized) = tcx.lang_items.sized_trait() {
1404 let trait_ref = ty::TraitRef {
1406 substs: tcx.mk_substs_trait(param_ty, &[])
1408 vec.push(trait_ref.to_predicate());
1412 for ®ion_bound in &self.region_bounds {
1413 // account for the binder being introduced below; no need to shift `param_ty`
1414 // because, at present at least, it can only refer to early-bound regions
1415 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1416 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1419 for bound_trait_ref in &self.trait_bounds {
1420 vec.push(bound_trait_ref.to_predicate());
1423 for projection in &self.projection_bounds {
1424 vec.push(projection.to_predicate());
1431 pub enum ExplicitSelf<'tcx> {
1433 ByReference(ty::Region<'tcx>, hir::Mutability),
1437 impl<'tcx> ExplicitSelf<'tcx> {
1438 /// We wish to (for now) categorize an explicit self
1439 /// declaration like `self: SomeType` into either `self`,
1440 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1441 /// by some simple pattern matching. A more precise check
1442 /// is done later in `check_method_self_type()`.
1447 /// impl Foo for &T {
1448 /// // Legal declarations:
1449 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1450 /// fn method2(self: &T); // ExplicitSelf::ByValue
1451 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1453 /// // Invalid cases will be caught later by `check_method_self_type`:
1454 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1458 /// To do the check we just count the number of "modifiers"
1459 /// on each type and compare them. If they are the same or
1460 /// the impl has more, we call it "by value". Otherwise, we
1461 /// look at the outermost modifier on the method decl and
1462 /// call it by-ref, by-box as appropriate. For method1, for
1463 /// example, the impl type has one modifier, but the method
1464 /// type has two, so we end up with
1465 /// ExplicitSelf::ByReference.
1466 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1467 self_arg_ty: Ty<'tcx>)
1468 -> ExplicitSelf<'tcx> {
1469 fn count_modifiers(ty: Ty) -> usize {
1471 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1472 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1477 let impl_modifiers = count_modifiers(untransformed_self_ty);
1478 let method_modifiers = count_modifiers(self_arg_ty);
1480 if impl_modifiers >= method_modifiers {
1481 ExplicitSelf::ByValue
1483 match self_arg_ty.sty {
1484 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1485 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1486 _ => ExplicitSelf::ByValue,