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::ConstVal;
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);
80 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
83 struct ConvertedBinding<'tcx> {
89 /// Dummy type used for the `Self` of a `TraitRef` created for converting
90 /// a trait object, and which gets removed in `ExistentialTraitRef`.
91 /// This type must not appear anywhere in other converted types.
92 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
94 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
95 pub fn ast_region_to_region(&self,
96 lifetime: &hir::Lifetime,
97 def: Option<&ty::RegionParameterDef>)
100 let tcx = self.tcx();
101 let lifetime_name = |def_id| {
102 tcx.hir.name(tcx.hir.as_local_node_id(def_id).unwrap())
105 let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
106 let r = match tcx.named_region(hir_id) {
107 Some(rl::Region::Static) => {
111 Some(rl::Region::LateBound(debruijn, id)) => {
112 let name = lifetime_name(id);
113 tcx.mk_region(ty::ReLateBound(debruijn,
114 ty::BrNamed(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 = lifetime_name(id);
123 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
130 Some(rl::Region::Free(scope, id)) => {
131 let name = lifetime_name(id);
132 tcx.mk_region(ty::ReFree(ty::FreeRegion {
134 bound_region: ty::BrNamed(id, name)
137 // (*) -- not late-bound, won't change
141 self.re_infer(lifetime.span, def).expect("unelided lifetime in signature")
145 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
152 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
153 /// returns an appropriate set of substitutions for this particular reference to `I`.
154 pub fn ast_path_substs_for_ty(&self,
157 item_segment: &hir::PathSegment)
158 -> &'tcx Substs<'tcx>
161 let (substs, assoc_bindings) =
162 item_segment.with_parameters(|parameters| {
163 self.create_substs_for_ast_path(
167 item_segment.infer_types,
171 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
176 /// Given the type/region arguments provided to some path (along with
177 /// an implicit Self, if this is a trait reference) returns the complete
178 /// set of substitutions. This may involve applying defaulted type parameters.
180 /// Note that the type listing given here is *exactly* what the user provided.
181 fn create_substs_for_ast_path(&self,
184 parameters: &hir::PathParameters,
186 self_ty: Option<Ty<'tcx>>)
187 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
189 let tcx = self.tcx();
191 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
193 def_id, self_ty, parameters);
195 // If the type is parameterized by this region, then replace this
196 // region with the current anon region binding (in other words,
197 // whatever & would get replaced with).
198 let decl_generics = tcx.generics_of(def_id);
199 let num_types_provided = parameters.types.len();
200 let expected_num_region_params = decl_generics.regions.len();
201 let supplied_num_region_params = parameters.lifetimes.len();
202 if expected_num_region_params != supplied_num_region_params {
203 report_lifetime_number_error(tcx, span,
204 supplied_num_region_params,
205 expected_num_region_params);
208 // If a self-type was declared, one should be provided.
209 assert_eq!(decl_generics.has_self, self_ty.is_some());
211 // Check the number of type parameters supplied by the user.
212 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
213 if !infer_types || num_types_provided > ty_param_defs.len() {
214 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
217 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
218 let default_needs_object_self = |p: &ty::TypeParameterDef| {
219 if is_object && p.has_default {
220 if tcx.at(span).type_of(p.def_id).has_self_ty() {
221 // There is no suitable inference default for a type parameter
222 // that references self, in an object type.
230 let substs = Substs::for_item(tcx, def_id, |def, _| {
231 let i = def.index as usize - self_ty.is_some() as usize;
232 if let Some(lifetime) = parameters.lifetimes.get(i) {
233 self.ast_region_to_region(lifetime, Some(def))
238 let i = def.index as usize;
240 // Handle Self first, so we can adjust the index to match the AST.
241 if let (0, Some(ty)) = (i, self_ty) {
245 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
246 if i < num_types_provided {
247 // A provided type parameter.
248 self.ast_ty_to_ty(¶meters.types[i])
249 } else if infer_types {
250 // No type parameters were provided, we can infer all.
251 let ty_var = if !default_needs_object_self(def) {
252 self.ty_infer_for_def(def, substs, span)
257 } else if def.has_default {
258 // No type parameter provided, but a default exists.
260 // If we are converting an object type, then the
261 // `Self` parameter is unknown. However, some of the
262 // other type parameters may reference `Self` in their
263 // defaults. This will lead to an ICE if we are not
265 if default_needs_object_self(def) {
266 struct_span_err!(tcx.sess, span, E0393,
267 "the type parameter `{}` must be explicitly specified",
269 .span_label(span, format!("missing reference to `{}`", def.name))
270 .note(&format!("because of the default `Self` reference, \
271 type parameters must be specified on object types"))
275 // This is a default type parameter.
278 tcx.at(span).type_of(def.def_id)
279 .subst_spanned(tcx, substs, Some(span))
283 // We've already errored above about the mismatch.
288 let assoc_bindings = parameters.bindings.iter().map(|binding| {
290 item_name: binding.name,
291 ty: self.ast_ty_to_ty(&binding.ty),
296 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
297 decl_generics, self_ty, substs);
299 (substs, assoc_bindings)
302 /// Instantiates the path for the given trait reference, assuming that it's
303 /// bound to a valid trait type. Returns the def_id for the defining trait.
304 /// Fails if the type is a type other than a trait type.
306 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
307 /// are disallowed. Otherwise, they are pushed onto the vector given.
308 pub fn instantiate_mono_trait_ref(&self,
309 trait_ref: &hir::TraitRef,
311 -> ty::TraitRef<'tcx>
313 self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
315 let trait_def_id = self.trait_def_id(trait_ref);
316 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
319 trait_ref.path.segments.last().unwrap())
322 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
323 let path = &trait_ref.path;
325 Def::Trait(trait_def_id) => trait_def_id,
327 self.tcx().sess.fatal("cannot continue compilation due to previous error");
330 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
331 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
336 pub fn instantiate_poly_trait_ref(&self,
337 ast_trait_ref: &hir::PolyTraitRef,
339 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
340 -> ty::PolyTraitRef<'tcx>
342 let trait_ref = &ast_trait_ref.trait_ref;
343 let trait_def_id = self.trait_def_id(trait_ref);
345 debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
347 self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
349 let (substs, assoc_bindings) =
350 self.create_substs_for_ast_trait_ref(trait_ref.path.span,
353 trait_ref.path.segments.last().unwrap());
354 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
356 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
357 // specify type to assert that error was already reported in Err case:
358 let predicate: Result<_, ErrorReported> =
359 self.ast_type_binding_to_poly_projection_predicate(poly_trait_ref, binding);
360 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
363 debug!("ast_path_to_poly_trait_ref({:?}, projections={:?}) -> {:?}",
364 trait_ref, poly_projections, poly_trait_ref);
368 fn ast_path_to_mono_trait_ref(&self,
372 trait_segment: &hir::PathSegment)
373 -> ty::TraitRef<'tcx>
375 let (substs, assoc_bindings) =
376 self.create_substs_for_ast_trait_ref(span,
380 assoc_bindings.first().map(|b| self.prohibit_projection(b.span));
381 ty::TraitRef::new(trait_def_id, substs)
384 fn create_substs_for_ast_trait_ref(&self,
388 trait_segment: &hir::PathSegment)
389 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
391 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
394 let trait_def = self.tcx().trait_def(trait_def_id);
396 if !self.tcx().sess.features.borrow().unboxed_closures &&
397 trait_segment.with_parameters(|p| p.parenthesized) != trait_def.paren_sugar {
398 // For now, require that parenthetical notation be used only with `Fn()` etc.
399 let msg = if trait_def.paren_sugar {
400 "the precise format of `Fn`-family traits' type parameters is subject to change. \
401 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
403 "parenthetical notation is only stable when used with `Fn`-family traits"
405 emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
406 span, GateIssue::Language, msg);
409 trait_segment.with_parameters(|parameters| {
410 self.create_substs_for_ast_path(span,
413 trait_segment.infer_types,
418 fn trait_defines_associated_type_named(&self,
420 assoc_name: ast::Name)
423 self.tcx().associated_items(trait_def_id).any(|item| {
424 item.kind == ty::AssociatedKind::Type &&
425 self.tcx().hygienic_eq(assoc_name, item.name, trait_def_id)
429 fn ast_type_binding_to_poly_projection_predicate(
431 trait_ref: ty::PolyTraitRef<'tcx>,
432 binding: &ConvertedBinding<'tcx>)
433 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
435 let tcx = self.tcx();
437 // Given something like `U : SomeTrait<T=X>`, we want to produce a
438 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
439 // subtle in the event that `T` is defined in a supertrait of
440 // `SomeTrait`, because in that case we need to upcast.
442 // That is, consider this case:
445 // trait SubTrait : SuperTrait<int> { }
446 // trait SuperTrait<A> { type T; }
448 // ... B : SubTrait<T=foo> ...
451 // We want to produce `<B as SuperTrait<int>>::T == foo`.
453 // Find any late-bound regions declared in `ty` that are not
454 // declared in the trait-ref. These are not wellformed.
458 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
459 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
460 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
461 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
462 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
463 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
464 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
465 let br_name = match *br {
466 ty::BrNamed(_, name) => name,
470 "anonymous bound region {:?} in binding but not trait ref",
474 struct_span_err!(tcx.sess,
477 "binding for associated type `{}` references lifetime `{}`, \
478 which does not appear in the trait input types",
479 binding.item_name, br_name)
483 // Simple case: X is defined in the current trait.
484 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
485 return Ok(trait_ref.map_bound(|trait_ref| {
486 ty::ProjectionPredicate {
487 projection_ty: ty::ProjectionTy::from_ref_and_name(
497 // Otherwise, we have to walk through the supertraits to find
500 traits::supertraits(tcx, trait_ref.clone())
501 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
503 let candidate = self.one_bound_for_assoc_type(candidates,
504 &trait_ref.to_string(),
508 Ok(candidate.map_bound(|trait_ref| {
509 ty::ProjectionPredicate {
510 projection_ty: ty::ProjectionTy::from_ref_and_name(
520 fn ast_path_to_ty(&self,
523 item_segment: &hir::PathSegment)
526 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
529 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
533 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
534 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
535 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
536 -> ty::ExistentialTraitRef<'tcx> {
537 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
538 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
541 fn conv_object_ty_poly_trait_ref(&self,
543 trait_bounds: &[hir::PolyTraitRef],
544 lifetime: &hir::Lifetime)
547 let tcx = self.tcx();
549 if trait_bounds.is_empty() {
550 span_err!(tcx.sess, span, E0224,
551 "at least one non-builtin trait is required for an object type");
552 return tcx.types.err;
555 let mut projection_bounds = vec![];
556 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
557 let principal = self.instantiate_poly_trait_ref(&trait_bounds[0],
559 &mut projection_bounds);
561 for trait_bound in trait_bounds[1..].iter() {
562 // Sanity check for non-principal trait bounds
563 self.instantiate_poly_trait_ref(trait_bound,
568 let (auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
570 if !trait_bounds.is_empty() {
571 let b = &trait_bounds[0];
572 let span = b.trait_ref.path.span;
573 struct_span_err!(self.tcx().sess, span, E0225,
574 "only Send/Sync traits can be used as additional traits in a trait object")
575 .span_label(span, "non-Send/Sync additional trait")
579 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
580 let existential_principal = principal.map_bound(|trait_ref| {
581 self.trait_ref_to_existential(trait_ref)
583 let existential_projections = projection_bounds.iter().map(|bound| {
584 bound.map_bound(|b| {
585 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
586 ty::ExistentialProjection {
588 item_def_id: b.projection_ty.item_def_id,
589 substs: trait_ref.substs,
594 // check that there are no gross object safety violations,
595 // most importantly, that the supertraits don't contain Self,
597 let object_safety_violations =
598 tcx.astconv_object_safety_violations(principal.def_id());
599 if !object_safety_violations.is_empty() {
600 tcx.report_object_safety_error(
601 span, principal.def_id(), object_safety_violations)
603 return tcx.types.err;
606 let mut associated_types = FxHashSet::default();
607 for tr in traits::supertraits(tcx, principal) {
608 associated_types.extend(tcx.associated_items(tr.def_id())
609 .filter(|item| item.kind == ty::AssociatedKind::Type)
610 .map(|item| item.def_id));
613 for projection_bound in &projection_bounds {
614 associated_types.remove(&projection_bound.0.projection_ty.item_def_id);
617 for item_def_id in associated_types {
618 let assoc_item = tcx.associated_item(item_def_id);
619 let trait_def_id = assoc_item.container.id();
620 struct_span_err!(tcx.sess, span, E0191,
621 "the value of the associated type `{}` (from the trait `{}`) must be specified",
623 tcx.item_path_str(trait_def_id))
624 .span_label(span, format!(
625 "missing associated type `{}` value", assoc_item.name))
630 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
631 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
632 .chain(existential_projections
633 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
634 .collect::<AccumulateVec<[_; 8]>>();
635 v.sort_by(|a, b| a.cmp(tcx, b));
636 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
639 // Explicitly specified region bound. Use that.
640 let region_bound = if !lifetime.is_elided() {
641 self.ast_region_to_region(lifetime, None)
643 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
644 let hir_id = tcx.hir.node_to_hir_id(lifetime.id);
645 if tcx.named_region(hir_id).is_some() {
646 self.ast_region_to_region(lifetime, None)
648 self.re_infer(span, None).unwrap_or_else(|| {
649 span_err!(tcx.sess, span, E0228,
650 "the lifetime bound for this object type cannot be deduced \
651 from context; please supply an explicit bound");
658 debug!("region_bound: {:?}", region_bound);
660 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
661 debug!("trait_object_type: {:?}", ty);
665 fn report_ambiguous_associated_type(&self,
670 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
671 .span_label(span, "ambiguous associated type")
672 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
673 type_str, trait_str, name))
678 // Search for a bound on a type parameter which includes the associated item
679 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
680 // This function will fail if there are no suitable bounds or there is
682 fn find_bound_for_assoc_item(&self,
683 ty_param_def_id: DefId,
684 assoc_name: ast::Name,
686 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
688 let tcx = self.tcx();
690 let bounds: Vec<_> = self.get_type_parameter_bounds(span, ty_param_def_id)
691 .predicates.into_iter().filter_map(|p| p.to_opt_poly_trait_ref()).collect();
693 // Check that there is exactly one way to find an associated type with the
695 let suitable_bounds =
696 traits::transitive_bounds(tcx, &bounds)
697 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
699 let param_node_id = tcx.hir.as_local_node_id(ty_param_def_id).unwrap();
700 let param_name = tcx.hir.ty_param_name(param_node_id);
701 self.one_bound_for_assoc_type(suitable_bounds,
702 ¶m_name.as_str(),
708 // Checks that bounds contains exactly one element and reports appropriate
710 fn one_bound_for_assoc_type<I>(&self,
713 assoc_name: ast::Name,
715 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
716 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
718 let bound = match bounds.next() {
719 Some(bound) => bound,
721 struct_span_err!(self.tcx().sess, span, E0220,
722 "associated type `{}` not found for `{}`",
725 .span_label(span, format!("associated type `{}` not found", assoc_name))
727 return Err(ErrorReported);
731 if let Some(bound2) = bounds.next() {
732 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
733 let mut err = struct_span_err!(
734 self.tcx().sess, span, E0221,
735 "ambiguous associated type `{}` in bounds of `{}`",
738 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
740 for bound in bounds {
741 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
742 item.kind == ty::AssociatedKind::Type &&
743 self.tcx().hygienic_eq(assoc_name, item.name, bound.def_id())
745 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
747 if let Some(span) = bound_span {
748 err.span_label(span, format!("ambiguous `{}` from `{}`",
752 span_note!(&mut err, span,
753 "associated type `{}` could derive from `{}`",
764 // Create a type from a path to an associated type.
765 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
766 // and item_segment is the path segment for D. We return a type and a def for
768 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
769 // parameter or Self.
770 pub fn associated_path_def_to_ty(&self,
775 item_segment: &hir::PathSegment)
778 let tcx = self.tcx();
779 let assoc_name = item_segment.name;
781 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
783 self.prohibit_type_params(slice::ref_slice(item_segment));
785 // Find the type of the associated item, and the trait where the associated
787 let bound = match (&ty.sty, ty_path_def) {
788 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
789 // `Self` in an impl of a trait - we have a concrete self type and a
791 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
792 Some(trait_ref) => trait_ref,
794 // A cycle error occurred, most likely.
795 return (tcx.types.err, Def::Err);
800 traits::supertraits(tcx, ty::Binder(trait_ref))
801 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
804 match self.one_bound_for_assoc_type(candidates, "Self", assoc_name, span) {
806 Err(ErrorReported) => return (tcx.types.err, Def::Err),
809 (&ty::TyParam(_), Def::SelfTy(Some(param_did), None)) |
810 (&ty::TyParam(_), Def::TyParam(param_did)) => {
811 match self.find_bound_for_assoc_item(param_did, assoc_name, span) {
813 Err(ErrorReported) => return (tcx.types.err, Def::Err),
817 // Don't print TyErr to the user.
818 if !ty.references_error() {
819 self.report_ambiguous_associated_type(span,
822 &assoc_name.as_str());
824 return (tcx.types.err, Def::Err);
828 let trait_did = bound.0.def_id;
829 let (assoc_ident, def_scope) = tcx.adjust(assoc_name, trait_did, ref_id);
830 let item = tcx.associated_items(trait_did).find(|i| i.name.to_ident() == assoc_ident)
831 .expect("missing associated type");
833 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
834 let ty = self.normalize_ty(span, ty);
836 let def = Def::AssociatedTy(item.def_id);
837 if !item.vis.is_accessible_from(def_scope, tcx) {
838 let msg = format!("{} `{}` is private", def.kind_name(), assoc_name);
839 tcx.sess.span_err(span, &msg);
841 tcx.check_stability(item.def_id, ref_id, span);
846 fn qpath_to_ty(&self,
848 opt_self_ty: Option<Ty<'tcx>>,
850 trait_segment: &hir::PathSegment,
851 item_segment: &hir::PathSegment)
854 let tcx = self.tcx();
855 let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
857 self.prohibit_type_params(slice::ref_slice(item_segment));
859 let self_ty = if let Some(ty) = opt_self_ty {
862 let path_str = tcx.item_path_str(trait_def_id);
863 self.report_ambiguous_associated_type(span,
866 &item_segment.name.as_str());
867 return tcx.types.err;
870 debug!("qpath_to_ty: self_type={:?}", self_ty);
872 let trait_ref = self.ast_path_to_mono_trait_ref(span,
877 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
879 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
882 pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
883 for segment in segments {
884 segment.with_parameters(|parameters| {
885 for typ in ¶meters.types {
886 struct_span_err!(self.tcx().sess, typ.span, E0109,
887 "type parameters are not allowed on this type")
888 .span_label(typ.span, "type parameter not allowed")
892 for lifetime in ¶meters.lifetimes {
893 struct_span_err!(self.tcx().sess, lifetime.span, E0110,
894 "lifetime parameters are not allowed on this type")
895 .span_label(lifetime.span,
896 "lifetime parameter not allowed on this type")
900 for binding in ¶meters.bindings {
901 self.prohibit_projection(binding.span);
908 pub fn prohibit_projection(&self, span: Span) {
909 let mut err = struct_span_err!(self.tcx().sess, span, E0229,
910 "associated type bindings are not allowed here");
911 err.span_label(span, "associated type not allowed here").emit();
914 // Check a type Path and convert it to a Ty.
915 pub fn def_to_ty(&self,
916 opt_self_ty: Option<Ty<'tcx>>,
918 permit_variants: bool)
920 let tcx = self.tcx();
922 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
923 path.def, opt_self_ty, path.segments);
925 let span = path.span;
927 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
928 assert_eq!(opt_self_ty, None);
929 self.prohibit_type_params(path.segments.split_last().unwrap().1);
930 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
932 Def::Variant(did) if permit_variants => {
933 // Convert "variant type" as if it were a real type.
934 // The resulting `Ty` is type of the variant's enum for now.
935 assert_eq!(opt_self_ty, None);
936 self.prohibit_type_params(path.segments.split_last().unwrap().1);
937 self.ast_path_to_ty(span,
938 tcx.parent_def_id(did).unwrap(),
939 path.segments.last().unwrap())
941 Def::TyParam(did) => {
942 assert_eq!(opt_self_ty, None);
943 self.prohibit_type_params(&path.segments);
945 let node_id = tcx.hir.as_local_node_id(did).unwrap();
946 let item_id = tcx.hir.get_parent_node(node_id);
947 let item_def_id = tcx.hir.local_def_id(item_id);
948 let generics = tcx.generics_of(item_def_id);
949 let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id).index];
950 tcx.mk_param(index, tcx.hir.name(node_id))
952 Def::SelfTy(_, Some(def_id)) => {
953 // Self in impl (we know the concrete type).
955 assert_eq!(opt_self_ty, None);
956 self.prohibit_type_params(&path.segments);
958 tcx.at(span).type_of(def_id)
960 Def::SelfTy(Some(_), None) => {
962 assert_eq!(opt_self_ty, None);
963 self.prohibit_type_params(&path.segments);
966 Def::AssociatedTy(def_id) => {
967 self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
968 self.qpath_to_ty(span,
971 &path.segments[path.segments.len()-2],
972 path.segments.last().unwrap())
974 Def::PrimTy(prim_ty) => {
975 assert_eq!(opt_self_ty, None);
976 self.prohibit_type_params(&path.segments);
978 hir::TyBool => tcx.types.bool,
979 hir::TyChar => tcx.types.char,
980 hir::TyInt(it) => tcx.mk_mach_int(it),
981 hir::TyUint(uit) => tcx.mk_mach_uint(uit),
982 hir::TyFloat(ft) => tcx.mk_mach_float(ft),
983 hir::TyStr => tcx.mk_str()
987 self.set_tainted_by_errors();
988 return self.tcx().types.err;
990 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
994 /// Parses the programmer's textual representation of a type into our
995 /// internal notion of a type.
996 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
997 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1000 let tcx = self.tcx();
1002 let result_ty = match ast_ty.node {
1003 hir::TySlice(ref ty) => {
1004 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1006 hir::TyPtr(ref mt) => {
1007 tcx.mk_ptr(ty::TypeAndMut {
1008 ty: self.ast_ty_to_ty(&mt.ty),
1012 hir::TyRptr(ref region, ref mt) => {
1013 let r = self.ast_region_to_region(region, None);
1014 debug!("TyRef r={:?}", r);
1015 let t = self.ast_ty_to_ty(&mt.ty);
1016 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1021 hir::TyTup(ref fields) => {
1022 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)), false)
1024 hir::TyBareFn(ref bf) => {
1025 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1026 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1028 hir::TyTraitObject(ref bounds, ref lifetime) => {
1029 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1031 hir::TyImplTrait(_) => {
1032 // Figure out if we can allow an `impl Trait` here, by walking up
1033 // to a `fn` or inherent `impl` method, going only through `Ty`
1034 // or `TraitRef` nodes (as nothing else should be in types) and
1035 // ensuring that we reach the `fn`/method signature's return type.
1036 let mut node_id = ast_ty.id;
1037 let fn_decl = loop {
1038 let parent = tcx.hir.get_parent_node(node_id);
1039 match tcx.hir.get(parent) {
1040 hir::map::NodeItem(&hir::Item {
1041 node: hir::ItemFn(ref fn_decl, ..), ..
1042 }) => break Some(fn_decl),
1044 hir::map::NodeImplItem(&hir::ImplItem {
1045 node: hir::ImplItemKind::Method(ref sig, _), ..
1047 match tcx.hir.expect_item(tcx.hir.get_parent(parent)).node {
1048 hir::ItemImpl(.., None, _, _) => {
1049 break Some(&sig.decl)
1055 hir::map::NodeTy(_) | hir::map::NodeTraitRef(_) => {}
1061 let allow = fn_decl.map_or(false, |fd| {
1063 hir::DefaultReturn(_) => false,
1064 hir::Return(ref ty) => ty.id == node_id
1068 // Create the anonymized type.
1070 let def_id = tcx.hir.local_def_id(ast_ty.id);
1071 tcx.mk_anon(def_id, Substs::identity_for_item(tcx, def_id))
1073 span_err!(tcx.sess, ast_ty.span, E0562,
1074 "`impl Trait` not allowed outside of function \
1075 and inherent method return types");
1079 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1080 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1081 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1082 self.ast_ty_to_ty(qself)
1084 self.def_to_ty(opt_self_ty, path, false)
1086 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1087 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1088 let ty = self.ast_ty_to_ty(qself);
1090 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1095 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1097 hir::TyArray(ref ty, length) => {
1098 let length_def_id = tcx.hir.body_owner_def_id(length);
1099 let substs = Substs::identity_for_item(tcx, length_def_id);
1100 let length = tcx.mk_const(ty::Const {
1101 val: ConstVal::Unevaluated(length_def_id, substs),
1104 let array_ty = tcx.mk_ty(ty::TyArray(self.ast_ty_to_ty(&ty), length));
1105 self.normalize_ty(ast_ty.span, array_ty)
1107 hir::TyTypeof(ref _e) => {
1108 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1109 "`typeof` is a reserved keyword but unimplemented")
1110 .span_label(ast_ty.span, "reserved keyword")
1116 // TyInfer also appears as the type of arguments or return
1117 // values in a ExprClosure, or as
1118 // the type of local variables. Both of these cases are
1119 // handled specially and will not descend into this routine.
1120 self.ty_infer(ast_ty.span)
1127 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1131 pub fn ty_of_arg(&self,
1133 expected_ty: Option<Ty<'tcx>>)
1137 hir::TyInfer if expected_ty.is_some() => {
1138 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1139 expected_ty.unwrap()
1141 _ => self.ast_ty_to_ty(ty),
1145 pub fn ty_of_fn(&self,
1146 unsafety: hir::Unsafety,
1149 -> ty::PolyFnSig<'tcx> {
1152 let tcx = self.tcx();
1153 let input_tys: Vec<Ty> =
1154 decl.inputs.iter().map(|a| self.ty_of_arg(a, None)).collect();
1156 let output_ty = match decl.output {
1157 hir::Return(ref output) => self.ast_ty_to_ty(output),
1158 hir::DefaultReturn(..) => tcx.mk_nil(),
1161 debug!("ty_of_fn: output_ty={:?}", output_ty);
1163 let bare_fn_ty = ty::Binder(tcx.mk_fn_sig(
1164 input_tys.into_iter(),
1171 // Find any late-bound regions declared in return type that do
1172 // not appear in the arguments. These are not wellformed.
1175 // for<'a> fn() -> &'a str <-- 'a is bad
1176 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1177 let inputs = bare_fn_ty.inputs();
1178 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1179 &inputs.map_bound(|i| i.to_owned()));
1180 let output = bare_fn_ty.output();
1181 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1182 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1183 let br_name = match *br {
1184 ty::BrNamed(_, name) => name,
1188 "anonymous bound region {:?} in return but not args",
1192 struct_span_err!(tcx.sess,
1195 "return type references lifetime `{}`, \
1196 which does not appear in the fn input types",
1204 pub fn ty_of_closure(&self,
1205 unsafety: hir::Unsafety,
1208 expected_sig: Option<ty::FnSig<'tcx>>)
1209 -> ty::PolyFnSig<'tcx>
1211 debug!("ty_of_closure(expected_sig={:?})",
1214 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1215 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1216 // no guarantee that the correct number of expected args
1218 if i < e.inputs().len() {
1224 self.ty_of_arg(a, expected_arg_ty)
1227 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1229 let output_ty = match decl.output {
1230 hir::Return(ref output) => {
1231 if let (&hir::TyInfer, Some(expected_ret_ty)) = (&output.node, expected_ret_ty) {
1232 self.record_ty(output.hir_id, expected_ret_ty, output.span);
1235 self.ast_ty_to_ty(&output)
1238 hir::DefaultReturn(span) => {
1239 if let Some(expected_ret_ty) = expected_ret_ty {
1247 debug!("ty_of_closure: output_ty={:?}", output_ty);
1249 ty::Binder(self.tcx().mk_fn_sig(
1258 /// Given the bounds on an object, determines what single region bound (if any) we can
1259 /// use to summarize this type. The basic idea is that we will use the bound the user
1260 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1261 /// for region bounds. It may be that we can derive no bound at all, in which case
1262 /// we return `None`.
1263 fn compute_object_lifetime_bound(&self,
1265 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1266 -> Option<ty::Region<'tcx>> // if None, use the default
1268 let tcx = self.tcx();
1270 debug!("compute_opt_region_bound(existential_predicates={:?})",
1271 existential_predicates);
1273 // No explicit region bound specified. Therefore, examine trait
1274 // bounds and see if we can derive region bounds from those.
1275 let derived_region_bounds =
1276 object_region_bounds(tcx, existential_predicates);
1278 // If there are no derived region bounds, then report back that we
1279 // can find no region bound. The caller will use the default.
1280 if derived_region_bounds.is_empty() {
1284 // If any of the derived region bounds are 'static, that is always
1286 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1287 return Some(tcx.types.re_static);
1290 // Determine whether there is exactly one unique region in the set
1291 // of derived region bounds. If so, use that. Otherwise, report an
1293 let r = derived_region_bounds[0];
1294 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1295 span_err!(tcx.sess, span, E0227,
1296 "ambiguous lifetime bound, explicit lifetime bound required");
1302 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1303 /// remaining general trait bounds.
1304 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1305 trait_bounds: &'b [hir::PolyTraitRef])
1306 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1308 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1309 match bound.trait_ref.path.def {
1310 Def::Trait(trait_did) => {
1311 // Checks whether `trait_did` refers to one of the builtin
1312 // traits, like `Send`, and adds it to `auto_traits` if so.
1313 if Some(trait_did) == tcx.lang_items().send_trait() ||
1314 Some(trait_did) == tcx.lang_items().sync_trait() {
1315 let segments = &bound.trait_ref.path.segments;
1316 segments[segments.len() - 1].with_parameters(|parameters| {
1317 if !parameters.types.is_empty() {
1318 check_type_argument_count(tcx, bound.trait_ref.path.span,
1319 parameters.types.len(), &[]);
1321 if !parameters.lifetimes.is_empty() {
1322 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1323 parameters.lifetimes.len(), 0);
1335 let auto_traits = auto_traits.into_iter().map(|tr| {
1336 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1341 }).collect::<Vec<_>>();
1343 (auto_traits, trait_bounds)
1346 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1347 ty_param_defs: &[ty::TypeParameterDef]) {
1348 let accepted = ty_param_defs.len();
1349 let required = ty_param_defs.iter().take_while(|x| !x.has_default).count();
1350 if supplied < required {
1351 let expected = if required < accepted {
1356 let arguments_plural = if required == 1 { "" } else { "s" };
1358 struct_span_err!(tcx.sess, span, E0243,
1359 "wrong number of type arguments: {} {}, found {}",
1360 expected, required, supplied)
1362 format!("{} {} type argument{}",
1367 } else if supplied > accepted {
1368 let expected = if required < accepted {
1369 format!("expected at most {}", accepted)
1371 format!("expected {}", accepted)
1373 let arguments_plural = if accepted == 1 { "" } else { "s" };
1375 struct_span_err!(tcx.sess, span, E0244,
1376 "wrong number of type arguments: {}, found {}",
1380 format!("{} type argument{}",
1381 if accepted == 0 { "expected no" } else { &expected },
1388 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1389 let label = if number < expected {
1391 format!("expected {} lifetime parameter", expected)
1393 format!("expected {} lifetime parameters", expected)
1396 let additional = number - expected;
1397 if additional == 1 {
1398 "unexpected lifetime parameter".to_string()
1400 format!("{} unexpected lifetime parameters", additional)
1403 struct_span_err!(tcx.sess, span, E0107,
1404 "wrong number of lifetime parameters: expected {}, found {}",
1406 .span_label(span, label)
1410 // A helper struct for conveniently grouping a set of bounds which we pass to
1411 // and return from functions in multiple places.
1412 #[derive(PartialEq, Eq, Clone, Debug)]
1413 pub struct Bounds<'tcx> {
1414 pub region_bounds: Vec<ty::Region<'tcx>>,
1415 pub implicitly_sized: bool,
1416 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1417 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1420 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1421 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
1422 -> Vec<ty::Predicate<'tcx>>
1424 let mut vec = Vec::new();
1426 // If it could be sized, and is, add the sized predicate
1427 if self.implicitly_sized {
1428 if let Some(sized) = tcx.lang_items().sized_trait() {
1429 let trait_ref = ty::TraitRef {
1431 substs: tcx.mk_substs_trait(param_ty, &[])
1433 vec.push(trait_ref.to_predicate());
1437 for ®ion_bound in &self.region_bounds {
1438 // account for the binder being introduced below; no need to shift `param_ty`
1439 // because, at present at least, it can only refer to early-bound regions
1440 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
1441 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
1444 for bound_trait_ref in &self.trait_bounds {
1445 vec.push(bound_trait_ref.to_predicate());
1448 for projection in &self.projection_bounds {
1449 vec.push(projection.to_predicate());
1456 pub enum ExplicitSelf<'tcx> {
1458 ByReference(ty::Region<'tcx>, hir::Mutability),
1462 impl<'tcx> ExplicitSelf<'tcx> {
1463 /// We wish to (for now) categorize an explicit self
1464 /// declaration like `self: SomeType` into either `self`,
1465 /// `&self`, `&mut self`, or `Box<self>`. We do this here
1466 /// by some simple pattern matching. A more precise check
1467 /// is done later in `check_method_receiver()`.
1472 /// impl Foo for &T {
1473 /// // Legal declarations:
1474 /// fn method1(self: &&T); // ExplicitSelf::ByReference
1475 /// fn method2(self: &T); // ExplicitSelf::ByValue
1476 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
1478 /// // Invalid cases will be caught later by `check_method_receiver`:
1479 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
1483 /// To do the check we just count the number of "modifiers"
1484 /// on each type and compare them. If they are the same or
1485 /// the impl has more, we call it "by value". Otherwise, we
1486 /// look at the outermost modifier on the method decl and
1487 /// call it by-ref, by-box as appropriate. For method1, for
1488 /// example, the impl type has one modifier, but the method
1489 /// type has two, so we end up with
1490 /// ExplicitSelf::ByReference.
1491 pub fn determine(untransformed_self_ty: Ty<'tcx>,
1492 self_arg_ty: Ty<'tcx>)
1493 -> ExplicitSelf<'tcx> {
1494 fn count_modifiers(ty: Ty) -> usize {
1496 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1497 ty::TyAdt(def, _) if def.is_box() => count_modifiers(ty.boxed_ty()) + 1,
1502 let impl_modifiers = count_modifiers(untransformed_self_ty);
1503 let method_modifiers = count_modifiers(self_arg_ty);
1505 if impl_modifiers >= method_modifiers {
1506 ExplicitSelf::ByValue
1508 match self_arg_ty.sty {
1509 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
1510 ty::TyAdt(def, _) if def.is_box() => ExplicitSelf::ByBox,
1511 _ => ExplicitSelf::ByValue,