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` and a `RegionScope`.
15 //! The parameterization of `ast_ty_to_ty()` is because it behaves
16 //! somewhat differently during the collect and check phases,
17 //! particularly with respect to looking up the types of top-level
18 //! items. In the collect phase, the crate context is used as the
19 //! `AstConv` instance; in this phase, the `get_item_type_scheme()`
20 //! function triggers a recursive call to `type_scheme_of_item()`
21 //! (note that `ast_ty_to_ty()` will detect recursive types and report
22 //! an error). In the check phase, when the FnCtxt is used as the
23 //! `AstConv`, `get_item_type_scheme()` just looks up the item type in
24 //! `tcx.tcache` (using `ty::lookup_item_type`).
26 //! The `RegionScope` trait controls what happens when the user does
27 //! not specify a region in some location where a region is required
28 //! (e.g., if the user writes `&Foo` as a type rather than `&'a Foo`).
29 //! See the `rscope` module for more details.
31 //! Unlike the `AstConv` trait, the region scope can change as we descend
32 //! the type. This is to accommodate the fact that (a) fn types are binding
33 //! scopes and (b) the default region may change. To understand case (a),
34 //! consider something like:
36 //! type foo = { x: &a.int, y: |&a.int| }
38 //! The type of `x` is an error because there is no region `a` in scope.
39 //! In the type of `y`, however, region `a` is considered a bound region
40 //! as it does not already appear in scope.
42 //! Case (b) says that if you have a type:
43 //! type foo<'a> = ...;
44 //! type bar = fn(&foo, &a.foo)
45 //! The fully expanded version of type bar is:
46 //! type bar = fn(&'foo &, &a.foo<'a>)
47 //! Note that the self region for the `foo` defaulted to `&` in the first
48 //! case but `&a` in the second. Basically, defaults that appear inside
49 //! an rptr (`&r.T`) use the region `r` that appears in the rptr.
51 use middle::astconv_util::{prim_ty_to_ty, prohibit_type_params, prohibit_projection};
52 use middle::const_eval::{self, ConstVal};
53 use middle::const_eval::EvalHint::UncheckedExprHint;
55 use middle::def_id::DefId;
56 use middle::resolve_lifetime as rl;
57 use middle::privacy::{AllPublic, LastMod};
58 use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
60 use middle::ty::{self, Ty, ToPredicate, HasTypeFlags};
61 use middle::ty::wf::object_region_bounds;
62 use require_c_abi_if_variadic;
63 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
64 ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
65 ElisionFailureInfo, ElidedLifetime};
66 use util::common::{ErrorReported, FN_OUTPUT_NAME};
67 use util::nodemap::FnvHashSet;
69 use syntax::{abi, ast};
70 use syntax::codemap::{Span, Pos};
71 use syntax::feature_gate::{GateIssue, emit_feature_err};
72 use syntax::parse::token;
74 use rustc_front::print::pprust;
76 use rustc_back::slice;
78 pub trait AstConv<'tcx> {
79 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
81 /// Identify the type scheme for an item with a type, like a type
82 /// alias, fn, or struct. This allows you to figure out the set of
83 /// type parameters defined on the item.
84 fn get_item_type_scheme(&self, span: Span, id: DefId)
85 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
87 /// Returns the `TraitDef` for a given trait. This allows you to
88 /// figure out the set of type parameters defined on the trait.
89 fn get_trait_def(&self, span: Span, id: DefId)
90 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
92 /// Ensure that the super-predicates for the trait with the given
93 /// id are available and also for the transitive set of
95 fn ensure_super_predicates(&self, span: Span, id: DefId)
96 -> Result<(), ErrorReported>;
98 /// Returns the set of bounds in scope for the type parameter with
100 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
101 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
103 /// Returns true if the trait with id `trait_def_id` defines an
104 /// associated type with the name `name`.
105 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
108 /// Return an (optional) substitution to convert bound type parameters that
109 /// are in scope into free ones. This function should only return Some
110 /// within a fn body.
111 /// See ParameterEnvironment::free_substs for more information.
112 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
116 /// What type should we use when a type is omitted?
118 param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
119 substs: Option<&mut Substs<'tcx>>,
120 space: Option<ParamSpace>,
121 span: Span) -> Ty<'tcx>;
123 /// Projecting an associated type from a (potentially)
124 /// higher-ranked trait reference is more complicated, because of
125 /// the possibility of late-bound regions appearing in the
126 /// associated type binding. This is not legal in function
127 /// signatures for that reason. In a function body, we can always
128 /// handle it because we can use inference variables to remove the
129 /// late-bound regions.
130 fn projected_ty_from_poly_trait_ref(&self,
132 poly_trait_ref: ty::PolyTraitRef<'tcx>,
133 item_name: ast::Name)
136 if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
137 self.projected_ty(span, trait_ref, item_name)
139 // no late-bound regions, we can just ignore the binder
140 span_err!(self.tcx().sess, span, E0212,
141 "cannot extract an associated type from a higher-ranked trait bound \
147 /// Project an associated type from a non-higher-ranked trait reference.
148 /// This is fairly straightforward and can be accommodated in any context.
149 fn projected_ty(&self,
151 _trait_ref: ty::TraitRef<'tcx>,
152 _item_name: ast::Name)
156 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &hir::Lifetime)
158 let r = match tcx.named_region_map.get(&lifetime.id) {
160 // should have been recorded by the `resolve_lifetime` pass
161 tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
164 Some(&rl::DefStaticRegion) => {
168 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
169 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id), lifetime.name))
172 Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
173 ty::ReEarlyBound(ty::EarlyBoundRegion {
180 Some(&rl::DefFreeRegion(scope, id)) => {
181 ty::ReFree(ty::FreeRegion {
182 scope: scope.to_code_extent(&tcx.region_maps),
183 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
189 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
197 fn report_elision_failure(
200 params: Vec<ElisionFailureInfo>)
202 let mut m = String::new();
203 let len = params.len();
204 let mut any_lifetimes = false;
206 for (i, info) in params.into_iter().enumerate() {
207 let ElisionFailureInfo {
208 name, lifetime_count: n, have_bound_regions
211 any_lifetimes = any_lifetimes || (n > 0);
213 let help_name = if name.is_empty() {
214 format!("argument {}", i + 1)
216 format!("`{}`", name)
219 m.push_str(&(if n == 1 {
222 format!("one of {}'s {} elided {}lifetimes", help_name, n,
223 if have_bound_regions { "free " } else { "" } )
226 if len == 2 && i == 0 {
228 } else if i + 2 == len {
230 } else if i + 1 != len {
236 fileline_help!(tcx.sess, default_span,
237 "this function's return type contains a borrowed value, but \
238 there is no value for it to be borrowed from");
239 fileline_help!(tcx.sess, default_span,
240 "consider giving it a 'static lifetime");
241 } else if !any_lifetimes {
242 fileline_help!(tcx.sess, default_span,
243 "this function's return type contains a borrowed value with \
244 an elided lifetime, but the lifetime cannot be derived from \
246 fileline_help!(tcx.sess, default_span,
247 "consider giving it an explicit bounded or 'static \
250 fileline_help!(tcx.sess, default_span,
251 "this function's return type contains a borrowed value, but \
252 the signature does not say which {} it is borrowed from",
255 fileline_help!(tcx.sess, default_span,
256 "this function's return type contains a borrowed value, but \
257 the signature does not say whether it is borrowed from {}",
262 pub fn opt_ast_region_to_region<'tcx>(
263 this: &AstConv<'tcx>,
264 rscope: &RegionScope,
266 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
268 let r = match *opt_lifetime {
269 Some(ref lifetime) => {
270 ast_region_to_region(this.tcx(), lifetime)
273 None => match rscope.anon_regions(default_span, 1) {
276 span_err!(this.tcx().sess, default_span, E0106,
277 "missing lifetime specifier");
278 if let Some(params) = params {
279 report_elision_failure(this.tcx(), default_span, params);
286 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
293 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
294 /// returns an appropriate set of substitutions for this particular reference to `I`.
295 pub fn ast_path_substs_for_ty<'tcx>(
296 this: &AstConv<'tcx>,
297 rscope: &RegionScope,
299 param_mode: PathParamMode,
300 decl_generics: &ty::Generics<'tcx>,
301 item_segment: &hir::PathSegment)
304 let tcx = this.tcx();
306 // ast_path_substs() is only called to convert paths that are
307 // known to refer to traits, types, or structs. In these cases,
308 // all type parameters defined for the item being referenced will
309 // be in the TypeSpace or SelfSpace.
311 // Note: in the case of traits, the self parameter is also
312 // defined, but we don't currently create a `type_param_def` for
313 // `Self` because it is implicit.
314 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
315 assert!(decl_generics.types.all(|d| d.space != FnSpace));
317 let (regions, types, assoc_bindings) = match item_segment.parameters {
318 hir::AngleBracketedParameters(ref data) => {
319 convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
321 hir::ParenthesizedParameters(..) => {
322 span_err!(tcx.sess, span, E0214,
323 "parenthesized parameters may only be used with a trait");
324 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
326 ty_param_defs.iter().map(|_| tcx.types.err).collect(),
331 prohibit_projections(this.tcx(), &assoc_bindings);
333 create_substs_for_ast_path(this,
342 #[derive(PartialEq, Eq)]
343 pub enum PathParamMode {
344 // Any path in a type context.
346 // The `module::Type` in `module::Type::method` in an expression.
350 fn create_region_substs<'tcx>(
351 this: &AstConv<'tcx>,
352 rscope: &RegionScope,
354 decl_generics: &ty::Generics<'tcx>,
355 regions_provided: Vec<ty::Region>)
358 let tcx = this.tcx();
360 // If the type is parameterized by this region, then replace this
361 // region with the current anon region binding (in other words,
362 // whatever & would get replaced with).
363 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
364 let supplied_num_region_params = regions_provided.len();
365 let regions = if expected_num_region_params == supplied_num_region_params {
369 rscope.anon_regions(span, expected_num_region_params);
371 if supplied_num_region_params != 0 || anon_regions.is_err() {
372 report_lifetime_number_error(tcx, span,
373 supplied_num_region_params,
374 expected_num_region_params);
378 Ok(anon_regions) => anon_regions,
379 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
382 Substs::new_type(vec![], regions)
385 /// Given the type/region arguments provided to some path (along with
386 /// an implicit Self, if this is a trait reference) returns the complete
387 /// set of substitutions. This may involve applying defaulted type parameters.
389 /// Note that the type listing given here is *exactly* what the user provided.
391 /// The `region_substs` should be the result of `create_region_substs`
392 /// -- that is, a substitution with no types but the correct number of
394 fn create_substs_for_ast_path<'tcx>(
395 this: &AstConv<'tcx>,
397 param_mode: PathParamMode,
398 decl_generics: &ty::Generics<'tcx>,
399 self_ty: Option<Ty<'tcx>>,
400 types_provided: Vec<Ty<'tcx>>,
401 region_substs: Substs<'tcx>)
404 let tcx = this.tcx();
406 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
407 types_provided={:?}, region_substs={:?})",
408 decl_generics, self_ty, types_provided,
411 assert_eq!(region_substs.regions().len(TypeSpace), decl_generics.regions.len(TypeSpace));
412 assert!(region_substs.types.is_empty());
414 // Convert the type parameters supplied by the user.
415 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
416 let formal_ty_param_count = ty_param_defs.len();
417 let required_ty_param_count = ty_param_defs.iter()
418 .take_while(|x| x.default.is_none())
421 let mut type_substs = get_type_substs_for_defs(this,
426 region_substs.clone(),
429 let supplied_ty_param_count = type_substs.len();
430 check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
431 required_ty_param_count, formal_ty_param_count);
433 if supplied_ty_param_count < required_ty_param_count {
434 while type_substs.len() < required_ty_param_count {
435 type_substs.push(tcx.types.err);
437 } else if supplied_ty_param_count > formal_ty_param_count {
438 type_substs.truncate(formal_ty_param_count);
440 assert!(type_substs.len() >= required_ty_param_count &&
441 type_substs.len() <= formal_ty_param_count);
443 let mut substs = region_substs;
444 substs.types.extend(TypeSpace, type_substs.into_iter());
448 // If no self-type is provided, it's still possible that
449 // one was declared, because this could be an object type.
452 // If a self-type is provided, one should have been
453 // "declared" (in other words, this should be a
455 assert!(decl_generics.types.get_self().is_some());
456 substs.types.push(SelfSpace, ty);
460 let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
461 for param in &ty_param_defs[actual_supplied_ty_param_count..] {
462 if let Some(default) = param.default {
463 // If we are converting an object type, then the
464 // `Self` parameter is unknown. However, some of the
465 // other type parameters may reference `Self` in their
466 // defaults. This will lead to an ICE if we are not
468 if self_ty.is_none() && default.has_self_ty() {
469 span_err!(tcx.sess, span, E0393,
470 "the type parameter `{}` must be explicitly specified \
471 in an object type because its default value `{}` references \
475 substs.types.push(TypeSpace, tcx.types.err);
477 // This is a default type parameter.
478 let default = default.subst_spanned(tcx,
481 substs.types.push(TypeSpace, default);
484 tcx.sess.span_bug(span, "extra parameter without default");
488 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
489 decl_generics, self_ty, substs);
494 /// Returns types_provided if it is not empty, otherwise populating the
495 /// type parameters with inference variables as appropriate.
496 fn get_type_substs_for_defs<'tcx>(this: &AstConv<'tcx>,
498 types_provided: Vec<Ty<'tcx>>,
499 param_mode: PathParamMode,
500 ty_param_defs: &[ty::TypeParameterDef<'tcx>],
501 mut substs: Substs<'tcx>,
502 self_ty: Option<Ty<'tcx>>)
505 fn default_type_parameter<'tcx>(p: &ty::TypeParameterDef<'tcx>, self_ty: Option<Ty<'tcx>>)
506 -> Option<ty::TypeParameterDef<'tcx>>
508 if let Some(ref default) = p.default {
509 if self_ty.is_none() && default.has_self_ty() {
510 // There is no suitable inference default for a type parameter
511 // that references self with no self-type provided.
519 if param_mode == PathParamMode::Optional && types_provided.is_empty() {
522 .map(|p| this.ty_infer(default_type_parameter(p, self_ty), Some(&mut substs),
523 Some(TypeSpace), span))
530 struct ConvertedBinding<'tcx> {
531 item_name: ast::Name,
536 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
537 rscope: &RegionScope,
539 decl_generics: &ty::Generics<'tcx>,
540 data: &hir::AngleBracketedParameterData)
543 Vec<ConvertedBinding<'tcx>>)
545 let regions: Vec<_> =
546 data.lifetimes.iter()
547 .map(|l| ast_region_to_region(this.tcx(), l))
551 create_region_substs(this, rscope, span, decl_generics, regions);
556 .map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
557 i, ®ion_substs, t))
560 let assoc_bindings: Vec<_> =
562 .map(|b| ConvertedBinding { item_name: b.name,
563 ty: ast_ty_to_ty(this, rscope, &*b.ty),
567 (region_substs, types, assoc_bindings)
570 /// Returns the appropriate lifetime to use for any output lifetimes
571 /// (if one exists) and a vector of the (pattern, number of lifetimes)
572 /// corresponding to each input type/pattern.
573 fn find_implied_output_region<'tcx>(tcx: &ty::ctxt<'tcx>,
574 input_tys: &[Ty<'tcx>],
575 input_pats: Vec<String>) -> ElidedLifetime
577 let mut lifetimes_for_params = Vec::new();
578 let mut possible_implied_output_region = None;
580 for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
581 let mut regions = FnvHashSet();
582 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
584 debug!("find_implied_output_regions: collected {:?} from {:?} \
585 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
587 if regions.len() == 1 {
588 // there's a chance that the unique lifetime of this
589 // iteration will be the appropriate lifetime for output
590 // parameters, so lets store it.
591 possible_implied_output_region = regions.iter().cloned().next();
594 lifetimes_for_params.push(ElisionFailureInfo {
596 lifetime_count: regions.len(),
597 have_bound_regions: have_bound_regions
601 if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
602 Ok(possible_implied_output_region.unwrap())
604 Err(Some(lifetimes_for_params))
608 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
609 elided_lifetime: ElidedLifetime,
613 match elided_lifetime {
614 Ok(implied_output_region) => {
615 let rb = ElidableRscope::new(implied_output_region);
616 ast_ty_to_ty(this, &rb, ty)
618 Err(param_lifetimes) => {
619 // All regions must be explicitly specified in the output
620 // if the lifetime elision rules do not apply. This saves
621 // the user from potentially-confusing errors.
622 let rb = UnelidableRscope::new(param_lifetimes);
623 ast_ty_to_ty(this, &rb, ty)
628 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
629 rscope: &RegionScope,
631 decl_generics: &ty::Generics<'tcx>,
632 data: &hir::ParenthesizedParameterData)
635 Vec<ConvertedBinding<'tcx>>)
638 create_region_substs(this, rscope, span, decl_generics, Vec::new());
640 let binding_rscope = BindingRscope::new();
643 .map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
644 0, ®ion_substs, a_t))
645 .collect::<Vec<Ty<'tcx>>>();
647 let input_params = vec![String::new(); inputs.len()];
648 let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
650 let input_ty = this.tcx().mk_tup(inputs);
652 let (output, output_span) = match data.output {
653 Some(ref output_ty) => {
654 (convert_ty_with_lifetime_elision(this,
655 implied_output_region,
660 (this.tcx().mk_nil(), data.span)
664 let output_binding = ConvertedBinding {
665 item_name: token::intern(FN_OUTPUT_NAME),
670 (region_substs, vec![input_ty], vec![output_binding])
673 pub fn instantiate_poly_trait_ref<'tcx>(
674 this: &AstConv<'tcx>,
675 rscope: &RegionScope,
676 ast_trait_ref: &hir::PolyTraitRef,
677 self_ty: Option<Ty<'tcx>>,
678 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
679 -> ty::PolyTraitRef<'tcx>
681 let trait_ref = &ast_trait_ref.trait_ref;
682 let trait_def_id = trait_def_id(this, trait_ref);
683 ast_path_to_poly_trait_ref(this,
686 PathParamMode::Explicit,
689 trait_ref.path.segments.last().unwrap(),
693 /// Instantiates the path for the given trait reference, assuming that it's
694 /// bound to a valid trait type. Returns the def_id for the defining trait.
695 /// Fails if the type is a type other than a trait type.
697 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
698 /// are disallowed. Otherwise, they are pushed onto the vector given.
699 pub fn instantiate_mono_trait_ref<'tcx>(
700 this: &AstConv<'tcx>,
701 rscope: &RegionScope,
702 trait_ref: &hir::TraitRef,
703 self_ty: Option<Ty<'tcx>>)
704 -> ty::TraitRef<'tcx>
706 let trait_def_id = trait_def_id(this, trait_ref);
707 ast_path_to_mono_trait_ref(this,
710 PathParamMode::Explicit,
713 trait_ref.path.segments.last().unwrap())
716 fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &hir::TraitRef) -> DefId {
717 let path = &trait_ref.path;
718 match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
719 def::DefTrait(trait_def_id) => trait_def_id,
721 this.tcx().sess.fatal("cannot continue compilation due to previous error");
724 span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
730 fn object_path_to_poly_trait_ref<'a,'tcx>(
731 this: &AstConv<'tcx>,
732 rscope: &RegionScope,
734 param_mode: PathParamMode,
736 trait_segment: &hir::PathSegment,
737 mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
738 -> ty::PolyTraitRef<'tcx>
740 ast_path_to_poly_trait_ref(this,
750 fn ast_path_to_poly_trait_ref<'a,'tcx>(
751 this: &AstConv<'tcx>,
752 rscope: &RegionScope,
754 param_mode: PathParamMode,
756 self_ty: Option<Ty<'tcx>>,
757 trait_segment: &hir::PathSegment,
758 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
759 -> ty::PolyTraitRef<'tcx>
761 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
762 // The trait reference introduces a binding level here, so
763 // we need to shift the `rscope`. It'd be nice if we could
764 // do away with this rscope stuff and work this knowledge
765 // into resolve_lifetimes, as we do with non-omitted
766 // lifetimes. Oh well, not there yet.
767 let shifted_rscope = &ShiftedRscope::new(rscope);
769 let (substs, assoc_bindings) =
770 create_substs_for_ast_trait_ref(this,
777 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
780 let converted_bindings =
783 .filter_map(|binding| {
784 // specify type to assert that error was already reported in Err case:
785 let predicate: Result<_, ErrorReported> =
786 ast_type_binding_to_poly_projection_predicate(this,
787 poly_trait_ref.clone(),
790 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
792 poly_projections.extend(converted_bindings);
795 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
796 trait_segment, poly_projections, poly_trait_ref);
800 fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
801 rscope: &RegionScope,
803 param_mode: PathParamMode,
805 self_ty: Option<Ty<'tcx>>,
806 trait_segment: &hir::PathSegment)
807 -> ty::TraitRef<'tcx>
809 let (substs, assoc_bindings) =
810 create_substs_for_ast_trait_ref(this,
817 prohibit_projections(this.tcx(), &assoc_bindings);
818 ty::TraitRef::new(trait_def_id, substs)
821 fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
822 rscope: &RegionScope,
824 param_mode: PathParamMode,
826 self_ty: Option<Ty<'tcx>>,
827 trait_segment: &hir::PathSegment)
828 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
830 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
833 let trait_def = match this.get_trait_def(span, trait_def_id) {
834 Ok(trait_def) => trait_def,
835 Err(ErrorReported) => {
836 // No convenient way to recover from a cycle here. Just bail. Sorry!
837 this.tcx().sess.abort_if_errors();
838 this.tcx().sess.bug("ErrorReported returned, but no errors reports?")
842 let (regions, types, assoc_bindings) = match trait_segment.parameters {
843 hir::AngleBracketedParameters(ref data) => {
844 // For now, require that parenthetical notation be used
845 // only with `Fn()` etc.
846 if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
847 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
848 "unboxed_closures", span, GateIssue::Language,
850 the precise format of `Fn`-family traits' type parameters is \
851 subject to change. Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
854 convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
856 hir::ParenthesizedParameters(ref data) => {
857 // For now, require that parenthetical notation be used
858 // only with `Fn()` etc.
859 if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
860 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
861 "unboxed_closures", span, GateIssue::Language,
863 parenthetical notation is only stable when used with `Fn`-family traits");
866 convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
870 let substs = create_substs_for_ast_path(this,
878 (this.tcx().mk_substs(substs), assoc_bindings)
881 fn ast_type_binding_to_poly_projection_predicate<'tcx>(
882 this: &AstConv<'tcx>,
883 mut trait_ref: ty::PolyTraitRef<'tcx>,
884 self_ty: Option<Ty<'tcx>>,
885 binding: &ConvertedBinding<'tcx>)
886 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
888 let tcx = this.tcx();
890 // Given something like `U : SomeTrait<T=X>`, we want to produce a
891 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
892 // subtle in the event that `T` is defined in a supertrait of
893 // `SomeTrait`, because in that case we need to upcast.
895 // That is, consider this case:
898 // trait SubTrait : SuperTrait<int> { }
899 // trait SuperTrait<A> { type T; }
901 // ... B : SubTrait<T=foo> ...
904 // We want to produce `<B as SuperTrait<int>>::T == foo`.
906 // Simple case: X is defined in the current trait.
907 if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
908 return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
909 projection_ty: ty::ProjectionTy { // |
910 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
911 item_name: binding.item_name,
917 // Otherwise, we have to walk through the supertraits to find
918 // those that do. This is complicated by the fact that, for an
919 // object type, the `Self` type is not present in the
920 // substitutions (after all, it's being constructed right now),
921 // but the `supertraits` iterator really wants one. To handle
922 // this, we currently insert a dummy type and then remove it
925 let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
926 if self_ty.is_none() { // if converting for an object type
927 let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
928 assert!(dummy_substs.self_ty().is_none()); // |
929 dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
930 trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(), // <------------+
931 tcx.mk_substs(dummy_substs)));
934 try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
936 let mut candidates: Vec<ty::PolyTraitRef> =
937 traits::supertraits(tcx, trait_ref.clone())
938 .filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
941 // If converting for an object type, then remove the dummy-ty from `Self` now.
943 if self_ty.is_none() {
944 for candidate in &mut candidates {
945 let mut dummy_substs = candidate.0.substs.clone();
946 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
947 dummy_substs.types.pop(SelfSpace);
948 *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
949 tcx.mk_substs(dummy_substs)));
953 let candidate = try!(one_bound_for_assoc_type(tcx,
955 &trait_ref.to_string(),
956 &binding.item_name.as_str(),
959 Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
960 projection_ty: ty::ProjectionTy { // |
961 trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
962 item_name: binding.item_name,
968 fn ast_path_to_ty<'tcx>(
969 this: &AstConv<'tcx>,
970 rscope: &RegionScope,
972 param_mode: PathParamMode,
974 item_segment: &hir::PathSegment)
977 let tcx = this.tcx();
978 let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
979 Ok(ty::TypeScheme { generics, ty: decl_ty }) => {
982 Err(ErrorReported) => {
983 return tcx.types.err;
987 let substs = ast_path_substs_for_ty(this,
994 // FIXME(#12938): This is a hack until we have full support for DST.
995 if Some(did) == this.tcx().lang_items.owned_box() {
996 assert_eq!(substs.types.len(TypeSpace), 1);
997 return this.tcx().mk_box(*substs.types.get(TypeSpace, 0));
1000 decl_ty.subst(this.tcx(), &substs)
1003 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
1005 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
1006 rscope: &RegionScope,
1008 bounds: &[hir::TyParamBound])
1009 -> Result<TraitAndProjections<'tcx>, ErrorReported>
1012 * In a type like `Foo + Send`, we want to wait to collect the
1013 * full set of bounds before we make the object type, because we
1014 * need them to infer a region bound. (For example, if we tried
1015 * made a type from just `Foo`, then it wouldn't be enough to
1016 * infer a 'static bound, and hence the user would get an error.)
1017 * So this function is used when we're dealing with a sum type to
1018 * convert the LHS. It only accepts a type that refers to a trait
1019 * name, and reports an error otherwise.
1023 hir::TyPath(None, ref path) => {
1024 let def = match this.tcx().def_map.borrow().get(&ty.id) {
1025 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
1029 Some(def::DefTrait(trait_def_id)) => {
1030 let mut projection_bounds = Vec::new();
1031 let trait_ref = object_path_to_poly_trait_ref(this,
1034 PathParamMode::Explicit,
1036 path.segments.last().unwrap(),
1037 &mut projection_bounds);
1038 Ok((trait_ref, projection_bounds))
1041 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
1047 span_err!(this.tcx().sess, ty.span, E0178,
1048 "expected a path on the left-hand side of `+`, not `{}`",
1049 pprust::ty_to_string(ty));
1050 let hi = bounds.iter().map(|x| match *x {
1051 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
1052 hir::RegionTyParamBound(ref r) => r.span.hi,
1053 }).max_by_key(|x| x.to_usize());
1054 let full_span = hi.map(|hi| Span {
1057 expn_id: ty.span.expn_id,
1059 match (&ty.node, full_span) {
1060 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1061 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1063 .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1064 format!("&{}({} +{})",
1066 pprust::ty_to_string(&*mut_ty.ty),
1067 pprust::bounds_to_string(bounds)));
1069 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1070 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1072 .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1073 format!("&{} {}({} +{})",
1074 pprust::lifetime_to_string(lt),
1076 pprust::ty_to_string(&*mut_ty.ty),
1077 pprust::bounds_to_string(bounds)));
1081 fileline_help!(this.tcx().sess, ty.span,
1082 "perhaps you forgot parentheses? (per RFC 438)");
1090 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
1091 rscope: &RegionScope,
1093 trait_ref: ty::PolyTraitRef<'tcx>,
1094 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1095 bounds: &[hir::TyParamBound])
1098 let existential_bounds = conv_existential_bounds(this,
1105 let result = make_object_type(this, span, trait_ref, existential_bounds);
1106 debug!("trait_ref_to_object_type: result={:?}",
1112 fn make_object_type<'tcx>(this: &AstConv<'tcx>,
1114 principal: ty::PolyTraitRef<'tcx>,
1115 bounds: ty::ExistentialBounds<'tcx>)
1117 let tcx = this.tcx();
1118 let object = ty::TraitTy {
1119 principal: principal,
1122 let object_trait_ref =
1123 object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1125 // ensure the super predicates and stop if we encountered an error
1126 if this.ensure_super_predicates(span, principal.def_id()).is_err() {
1127 return tcx.types.err;
1130 // check that there are no gross object safety violations,
1131 // most importantly, that the supertraits don't contain Self,
1133 let object_safety_violations =
1134 traits::astconv_object_safety_violations(tcx, principal.def_id());
1135 if !object_safety_violations.is_empty() {
1136 traits::report_object_safety_error(
1137 tcx, span, principal.def_id(), object_safety_violations);
1138 return tcx.types.err;
1141 let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1142 traits::supertraits(tcx, object_trait_ref)
1144 let trait_def = tcx.lookup_trait_def(tr.def_id());
1145 trait_def.associated_type_names
1148 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1152 for projection_bound in &object.bounds.projection_bounds {
1153 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1154 projection_bound.0.projection_ty.item_name);
1155 associated_types.remove(&pair);
1158 for (trait_def_id, name) in associated_types {
1159 span_err!(tcx.sess, span, E0191,
1160 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1162 tcx.item_path_str(trait_def_id));
1165 tcx.mk_trait(object.principal, object.bounds)
1168 fn report_ambiguous_associated_type(tcx: &ty::ctxt,
1173 span_err!(tcx.sess, span, E0223,
1174 "ambiguous associated type; specify the type using the syntax \
1176 type_str, trait_str, name);
1179 // Search for a bound on a type parameter which includes the associated item
1180 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1181 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1182 // impl). This function will fail if there are no suitable bounds or there is
1184 fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
1185 ty_param_node_id: ast::NodeId,
1186 ty_param_name: ast::Name,
1187 assoc_name: ast::Name,
1189 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1191 let tcx = this.tcx();
1193 let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
1195 Err(ErrorReported) => {
1196 return Err(ErrorReported);
1200 // Ensure the super predicates and stop if we encountered an error.
1201 if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
1202 return Err(ErrorReported);
1205 // Check that there is exactly one way to find an associated type with the
1207 let suitable_bounds: Vec<_> =
1208 traits::transitive_bounds(tcx, &bounds)
1209 .filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
1212 one_bound_for_assoc_type(tcx,
1214 &ty_param_name.as_str(),
1215 &assoc_name.as_str(),
1220 // Checks that bounds contains exactly one element and reports appropriate
1221 // errors otherwise.
1222 fn one_bound_for_assoc_type<'tcx>(tcx: &ty::ctxt<'tcx>,
1223 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1224 ty_param_name: &str,
1227 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1229 if bounds.is_empty() {
1230 span_err!(tcx.sess, span, E0220,
1231 "associated type `{}` not found for `{}`",
1234 return Err(ErrorReported);
1237 if bounds.len() > 1 {
1238 span_err!(tcx.sess, span, E0221,
1239 "ambiguous associated type `{}` in bounds of `{}`",
1243 for bound in &bounds {
1244 span_note!(tcx.sess, span,
1245 "associated type `{}` could derive from `{}`",
1251 Ok(bounds[0].clone())
1254 // Create a type from a path to an associated type.
1255 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1256 // and item_segment is the path segment for D. We return a type and a def for
1258 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1259 // parameter or Self.
1260 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1263 ty_path_def: def::Def,
1264 item_segment: &hir::PathSegment)
1265 -> (Ty<'tcx>, def::Def)
1267 let tcx = this.tcx();
1268 let assoc_name = item_segment.identifier.name;
1270 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1272 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1274 // Find the type of the associated item, and the trait where the associated
1275 // item is declared.
1276 let bound = match (&ty.sty, ty_path_def) {
1277 (_, def::DefSelfTy(Some(trait_did), Some((impl_id, _)))) => {
1278 // `Self` in an impl of a trait - we have a concrete self type and a
1280 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1281 let trait_ref = if let Some(free_substs) = this.get_free_substs() {
1282 trait_ref.subst(tcx, free_substs)
1287 if this.ensure_super_predicates(span, trait_did).is_err() {
1288 return (tcx.types.err, ty_path_def);
1291 let candidates: Vec<ty::PolyTraitRef> =
1292 traits::supertraits(tcx, ty::Binder(trait_ref))
1293 .filter(|r| this.trait_defines_associated_type_named(r.def_id(),
1297 match one_bound_for_assoc_type(tcx,
1300 &assoc_name.as_str(),
1303 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1306 (&ty::TyParam(_), def::DefSelfTy(Some(trait_did), None)) => {
1307 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1308 match find_bound_for_assoc_item(this,
1310 token::special_idents::type_self.name,
1314 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1317 (&ty::TyParam(_), def::DefTyParam(_, _, param_did, param_name)) => {
1318 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1319 match find_bound_for_assoc_item(this,
1325 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1329 report_ambiguous_associated_type(tcx,
1333 &assoc_name.as_str());
1334 return (tcx.types.err, ty_path_def);
1338 let trait_did = bound.0.def_id;
1339 let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1341 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1342 // `ty::trait_items` used below requires information generated
1343 // by type collection, which may be in progress at this point.
1344 match tcx.map.expect_item(trait_id).node {
1345 hir::ItemTrait(_, _, _, ref trait_items) => {
1346 let item = trait_items.iter()
1347 .find(|i| i.name == assoc_name)
1348 .expect("missing associated type");
1349 tcx.map.local_def_id(item.id)
1354 let trait_items = tcx.trait_items(trait_did);
1355 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1356 item.expect("missing associated type").def_id()
1359 (ty, def::DefAssociatedTy(trait_did, item_did))
1362 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1363 rscope: &RegionScope,
1365 param_mode: PathParamMode,
1366 opt_self_ty: Option<Ty<'tcx>>,
1367 trait_def_id: DefId,
1368 trait_segment: &hir::PathSegment,
1369 item_segment: &hir::PathSegment)
1372 let tcx = this.tcx();
1374 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1376 let self_ty = if let Some(ty) = opt_self_ty {
1379 let path_str = tcx.item_path_str(trait_def_id);
1380 report_ambiguous_associated_type(tcx,
1384 &item_segment.identifier.name.as_str());
1385 return tcx.types.err;
1388 debug!("qpath_to_ty: self_type={:?}", self_ty);
1390 let trait_ref = ast_path_to_mono_trait_ref(this,
1398 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1400 this.projected_ty(span, trait_ref, item_segment.identifier.name)
1403 /// Convert a type supplied as value for a type argument from AST into our
1404 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1405 /// it applies the object lifetime default.
1409 /// * `this`, `rscope`: the surrounding context
1410 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1412 /// * `index`: the index of the type parameter being instantiated from the list
1413 /// (we assume it is in the `TypeSpace`)
1414 /// * `region_substs`: a partial substitution consisting of
1415 /// only the region type parameters being supplied to this type.
1416 /// * `ast_ty`: the ast representation of the type being supplied
1417 pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
1418 rscope: &RegionScope,
1419 decl_generics: &ty::Generics<'tcx>,
1421 region_substs: &Substs<'tcx>,
1425 let tcx = this.tcx();
1427 if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1428 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1429 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1430 ast_ty_to_ty(this, rscope1, ast_ty)
1432 ast_ty_to_ty(this, rscope, ast_ty)
1436 // Check the base def in a PathResolution and convert it to a Ty. If there are
1437 // associated types in the PathResolution, these will need to be separately
1439 fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1440 rscope: &RegionScope,
1442 param_mode: PathParamMode,
1444 opt_self_ty: Option<Ty<'tcx>>,
1445 base_segments: &[hir::PathSegment])
1447 let tcx = this.tcx();
1450 def::DefTrait(trait_def_id) => {
1451 // N.B. this case overlaps somewhat with
1452 // TyObjectSum, see that fn for details
1453 let mut projection_bounds = Vec::new();
1455 let trait_ref = object_path_to_poly_trait_ref(this,
1460 base_segments.last().unwrap(),
1461 &mut projection_bounds);
1463 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1464 trait_ref_to_object_type(this,
1471 def::DefTy(did, _) | def::DefStruct(did) => {
1472 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1473 ast_path_to_ty(this,
1478 base_segments.last().unwrap())
1480 def::DefTyParam(space, index, _, name) => {
1481 prohibit_type_params(tcx, base_segments);
1482 tcx.mk_param(space, index, name)
1484 def::DefSelfTy(_, Some((_, self_ty_id))) => {
1485 // Self in impl (we know the concrete type).
1486 prohibit_type_params(tcx, base_segments);
1487 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
1488 if let Some(free_substs) = this.get_free_substs() {
1489 ty.subst(tcx, free_substs)
1494 tcx.sess.span_bug(span, "self type has not been fully resolved")
1497 def::DefSelfTy(Some(_), None) => {
1499 prohibit_type_params(tcx, base_segments);
1502 def::DefAssociatedTy(trait_did, _) => {
1503 prohibit_type_params(tcx, &base_segments[..base_segments.len()-2]);
1510 &base_segments[base_segments.len()-2],
1511 base_segments.last().unwrap())
1513 def::DefMod(id) => {
1514 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1515 // FIXME(#22519) This part of the resolution logic should be
1516 // avoided entirely for that form, once we stop needed a Def
1517 // for `associated_path_def_to_ty`.
1518 // Fixing this will also let use resolve <Self>::Foo the same way we
1519 // resolve Self::Foo, at the moment we can't resolve the former because
1520 // we don't have the trait information around, which is just sad.
1522 if !base_segments.is_empty() {
1523 let id_node = tcx.map.as_local_node_id(id).unwrap();
1527 "found module name used as a type: {}",
1528 tcx.map.node_to_user_string(id_node));
1529 return this.tcx().types.err;
1532 opt_self_ty.expect("missing T in <T>::a::b::c")
1534 def::DefPrimTy(prim_ty) => {
1535 prim_ty_to_ty(tcx, base_segments, prim_ty)
1538 return this.tcx().types.err;
1541 let id_node = tcx.map.as_local_node_id(def.def_id()).unwrap();
1542 span_err!(tcx.sess, span, E0248,
1543 "found value `{}` used as a type",
1544 tcx.map.path_to_string(id_node));
1545 return this.tcx().types.err;
1550 // Note that both base_segments and assoc_segments may be empty, although not at
1552 pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1553 rscope: &RegionScope,
1555 param_mode: PathParamMode,
1557 opt_self_ty: Option<Ty<'tcx>>,
1558 base_segments: &[hir::PathSegment],
1559 assoc_segments: &[hir::PathSegment])
1561 let mut ty = base_def_to_ty(this,
1569 // If any associated type segments remain, attempt to resolve them.
1570 for segment in assoc_segments {
1571 if ty.sty == ty::TyError {
1574 // This is pretty bad (it will fail except for T::A and Self::A).
1575 let (a_ty, a_def) = associated_path_def_to_ty(this,
1586 /// Parses the programmer's textual representation of a type into our
1587 /// internal notion of a type.
1588 pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
1589 rscope: &RegionScope,
1593 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1596 let tcx = this.tcx();
1598 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
1599 debug!("ast_ty_to_ty: id={:?} ty={:?} (cached)", ast_ty.id, ty);
1603 let typ = match ast_ty.node {
1604 hir::TyVec(ref ty) => {
1605 tcx.mk_slice(ast_ty_to_ty(this, rscope, &**ty))
1607 hir::TyObjectSum(ref ty, ref bounds) => {
1608 match ast_ty_to_trait_ref(this, rscope, &**ty, bounds) {
1609 Ok((trait_ref, projection_bounds)) => {
1610 trait_ref_to_object_type(this,
1617 Err(ErrorReported) => {
1618 this.tcx().types.err
1622 hir::TyPtr(ref mt) => {
1623 tcx.mk_ptr(ty::TypeAndMut {
1624 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1628 hir::TyRptr(ref region, ref mt) => {
1629 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1630 debug!("TyRef r={:?}", r);
1632 &ObjectLifetimeDefaultRscope::new(
1634 ty::ObjectLifetimeDefault::Specific(r));
1635 let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
1636 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1638 hir::TyTup(ref fields) => {
1639 let flds = fields.iter()
1640 .map(|t| ast_ty_to_ty(this, rscope, &**t))
1644 hir::TyBareFn(ref bf) => {
1645 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1646 let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1647 tcx.mk_fn(None, tcx.mk_bare_fn(bare_fn))
1649 hir::TyPolyTraitRef(ref bounds) => {
1650 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds)
1652 hir::TyPath(ref maybe_qself, ref path) => {
1653 let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
1655 } else if let Some(hir::QSelf { position: 0, .. }) = *maybe_qself {
1656 // Create some fake resolution that can't possibly be a type.
1657 def::PathResolution {
1658 base_def: def::DefMod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
1659 last_private: LastMod(AllPublic),
1660 depth: path.segments.len()
1663 tcx.sess.span_bug(ast_ty.span, &format!("unbound path {:?}", ast_ty))
1665 let def = path_res.base_def;
1666 let base_ty_end = path.segments.len() - path_res.depth;
1667 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1668 ast_ty_to_ty(this, rscope, &qself.ty)
1670 let ty = finish_resolving_def_to_ty(this,
1673 PathParamMode::Explicit,
1676 &path.segments[..base_ty_end],
1677 &path.segments[base_ty_end..]);
1679 if path_res.depth != 0 && ty.sty != ty::TyError {
1680 // Write back the new resolution.
1681 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1683 last_private: path_res.last_private,
1690 hir::TyFixedLengthVec(ref ty, ref e) => {
1691 let hint = UncheckedExprHint(tcx.types.usize);
1692 match const_eval::eval_const_expr_partial(tcx, &e, hint, None) {
1696 tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1698 ConstVal::Uint(i) =>
1699 tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1702 span_err!(tcx.sess, ast_ty.span, E0249,
1703 "expected constant integer expression \
1705 this.tcx().types.err
1710 span_err!(tcx.sess, r.span, E0250,
1711 "array length constant evaluation error: {}",
1713 if !ast_ty.span.contains(r.span) {
1714 span_note!(tcx.sess, ast_ty.span, "for array length here")
1716 this.tcx().types.err
1720 hir::TyTypeof(ref _e) => {
1721 span_err!(tcx.sess, ast_ty.span, E0516,
1722 "`typeof` is a reserved keyword but unimplemented");
1726 // TyInfer also appears as the type of arguments or return
1727 // values in a ExprClosure, or as
1728 // the type of local variables. Both of these cases are
1729 // handled specially and will not descend into this routine.
1730 this.ty_infer(None, None, None, ast_ty.span)
1734 debug!("ast_ty_to_ty: id={:?} ty={:?}", ast_ty.id, typ);
1735 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
1739 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1740 rscope: &RegionScope,
1742 expected_ty: Option<Ty<'tcx>>)
1746 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1747 hir::TyInfer => this.ty_infer(None, None, None, a.ty.span),
1748 _ => ast_ty_to_ty(this, rscope, &*a.ty),
1752 struct SelfInfo<'a, 'tcx> {
1753 untransformed_self_ty: Ty<'tcx>,
1754 explicit_self: &'a hir::ExplicitSelf,
1757 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1758 sig: &hir::MethodSig,
1759 untransformed_self_ty: Ty<'tcx>)
1760 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1761 let self_info = Some(SelfInfo {
1762 untransformed_self_ty: untransformed_self_ty,
1763 explicit_self: &sig.explicit_self,
1765 let (bare_fn_ty, optional_explicit_self_category) =
1766 ty_of_method_or_bare_fn(this,
1771 (bare_fn_ty, optional_explicit_self_category.unwrap())
1774 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: hir::Unsafety, abi: abi::Abi,
1775 decl: &hir::FnDecl) -> ty::BareFnTy<'tcx> {
1776 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1780 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1781 unsafety: hir::Unsafety,
1783 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1785 -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1787 debug!("ty_of_method_or_bare_fn");
1789 // New region names that appear inside of the arguments of the function
1790 // declaration are bound to that function type.
1791 let rb = rscope::BindingRscope::new();
1793 // `implied_output_region` is the region that will be assumed for any
1794 // region parameters in the return type. In accordance with the rules for
1795 // lifetime elision, we can determine it in two ways. First (determined
1796 // here), if self is by-reference, then the implied output region is the
1797 // region of the self parameter.
1798 let (self_ty, explicit_self_category) = match opt_self_info {
1799 None => (None, None),
1800 Some(self_info) => determine_self_type(this, &rb, self_info)
1803 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1804 let arg_params = if self_ty.is_some() {
1809 let arg_tys: Vec<Ty> =
1810 arg_params.iter().map(|a| ty_of_arg(this, &rb, a, None)).collect();
1811 let arg_pats: Vec<String> =
1812 arg_params.iter().map(|a| pprust::pat_to_string(&*a.pat)).collect();
1814 // Second, if there was exactly one lifetime (either a substitution or a
1815 // reference) in the arguments, then any anonymous regions in the output
1816 // have that lifetime.
1817 let implied_output_region = match explicit_self_category {
1818 Some(ty::ByReferenceExplicitSelfCategory(region, _)) => Ok(region),
1819 _ => find_implied_output_region(this.tcx(), &arg_tys, arg_pats)
1822 let output_ty = match decl.output {
1823 hir::Return(ref output) =>
1824 ty::FnConverging(convert_ty_with_lifetime_elision(this,
1825 implied_output_region,
1827 hir::DefaultReturn(..) => ty::FnConverging(this.tcx().mk_nil()),
1828 hir::NoReturn(..) => ty::FnDiverging
1834 sig: ty::Binder(ty::FnSig {
1835 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1837 variadic: decl.variadic
1839 }, explicit_self_category)
1842 fn determine_self_type<'a, 'tcx>(this: &AstConv<'tcx>,
1843 rscope: &RegionScope,
1844 self_info: SelfInfo<'a, 'tcx>)
1845 -> (Option<Ty<'tcx>>, Option<ty::ExplicitSelfCategory>)
1847 let self_ty = self_info.untransformed_self_ty;
1848 return match self_info.explicit_self.node {
1849 hir::SelfStatic => (None, Some(ty::StaticExplicitSelfCategory)),
1850 hir::SelfValue(_) => {
1851 (Some(self_ty), Some(ty::ByValueExplicitSelfCategory))
1853 hir::SelfRegion(ref lifetime, mutability, _) => {
1855 opt_ast_region_to_region(this,
1857 self_info.explicit_self.span,
1859 (Some(this.tcx().mk_ref(
1860 this.tcx().mk_region(region),
1865 Some(ty::ByReferenceExplicitSelfCategory(region, mutability)))
1867 hir::SelfExplicit(ref ast_type, _) => {
1868 let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1870 // We wish to (for now) categorize an explicit self
1871 // declaration like `self: SomeType` into either `self`,
1872 // `&self`, `&mut self`, or `Box<self>`. We do this here
1873 // by some simple pattern matching. A more precise check
1874 // is done later in `check_method_self_type()`.
1879 // impl Foo for &T {
1880 // // Legal declarations:
1881 // fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1882 // fn method2(self: &T); // ByValueExplicitSelfCategory
1883 // fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1885 // // Invalid cases will be caught later by `check_method_self_type`:
1886 // fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1890 // To do the check we just count the number of "modifiers"
1891 // on each type and compare them. If they are the same or
1892 // the impl has more, we call it "by value". Otherwise, we
1893 // look at the outermost modifier on the method decl and
1894 // call it by-ref, by-box as appropriate. For method1, for
1895 // example, the impl type has one modifier, but the method
1896 // type has two, so we end up with
1897 // ByReferenceExplicitSelfCategory.
1899 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1900 let method_modifiers = count_modifiers(explicit_type);
1902 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1903 explicit_type={:?} \
1905 self_info.untransformed_self_ty,
1910 let category = if impl_modifiers >= method_modifiers {
1911 ty::ByValueExplicitSelfCategory
1913 match explicit_type.sty {
1914 ty::TyRef(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
1915 ty::TyBox(_) => ty::ByBoxExplicitSelfCategory,
1916 _ => ty::ByValueExplicitSelfCategory,
1920 (Some(explicit_type), Some(category))
1924 fn count_modifiers(ty: Ty) -> usize {
1926 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1927 ty::TyBox(t) => count_modifiers(t) + 1,
1933 pub fn ty_of_closure<'tcx>(
1934 this: &AstConv<'tcx>,
1935 unsafety: hir::Unsafety,
1938 expected_sig: Option<ty::FnSig<'tcx>>)
1939 -> ty::ClosureTy<'tcx>
1941 debug!("ty_of_closure(expected_sig={:?})",
1944 // new region names that appear inside of the fn decl are bound to
1945 // that function type
1946 let rb = rscope::BindingRscope::new();
1948 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1949 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1950 // no guarantee that the correct number of expected args
1952 if i < e.inputs.len() {
1958 ty_of_arg(this, &rb, a, expected_arg_ty)
1961 let expected_ret_ty = expected_sig.map(|e| e.output);
1963 let is_infer = match decl.output {
1964 hir::Return(ref output) if output.node == hir::TyInfer => true,
1965 hir::DefaultReturn(..) => true,
1969 let output_ty = match decl.output {
1970 _ if is_infer && expected_ret_ty.is_some() =>
1971 expected_ret_ty.unwrap(),
1973 ty::FnConverging(this.ty_infer(None, None, None, decl.output.span())),
1974 hir::Return(ref output) =>
1975 ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1976 hir::DefaultReturn(..) => unreachable!(),
1977 hir::NoReturn(..) => ty::FnDiverging
1980 debug!("ty_of_closure: input_tys={:?}", input_tys);
1981 debug!("ty_of_closure: output_ty={:?}", output_ty);
1986 sig: ty::Binder(ty::FnSig {inputs: input_tys,
1988 variadic: decl.variadic}),
1992 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1993 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1994 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1995 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1996 fn conv_existential_bounds<'tcx>(
1997 this: &AstConv<'tcx>,
1998 rscope: &RegionScope,
2000 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2001 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2002 ast_bounds: &[hir::TyParamBound])
2003 -> ty::ExistentialBounds<'tcx>
2005 let partitioned_bounds =
2006 partition_bounds(this.tcx(), span, ast_bounds);
2008 conv_existential_bounds_from_partitioned_bounds(
2009 this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2012 fn conv_ty_poly_trait_ref<'tcx>(
2013 this: &AstConv<'tcx>,
2014 rscope: &RegionScope,
2016 ast_bounds: &[hir::TyParamBound])
2019 let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
2021 let mut projection_bounds = Vec::new();
2022 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2023 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2024 instantiate_poly_trait_ref(this,
2028 &mut projection_bounds)
2030 span_err!(this.tcx().sess, span, E0224,
2031 "at least one non-builtin trait is required for an object type");
2032 return this.tcx().types.err;
2036 conv_existential_bounds_from_partitioned_bounds(this,
2039 main_trait_bound.clone(),
2041 partitioned_bounds);
2043 make_object_type(this, span, main_trait_bound, bounds)
2046 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
2047 this: &AstConv<'tcx>,
2048 rscope: &RegionScope,
2050 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2051 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2052 partitioned_bounds: PartitionedBounds)
2053 -> ty::ExistentialBounds<'tcx>
2055 let PartitionedBounds { builtin_bounds,
2060 if !trait_bounds.is_empty() {
2061 let b = &trait_bounds[0];
2062 span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
2063 "only the builtin traits can be used as closure or object bounds");
2067 compute_object_lifetime_bound(this,
2070 principal_trait_ref,
2073 let region_bound = match region_bound {
2076 match rscope.object_lifetime_default(span) {
2079 span_err!(this.tcx().sess, span, E0228,
2080 "the lifetime bound for this object type cannot be deduced \
2081 from context; please supply an explicit bound");
2088 debug!("region_bound: {:?}", region_bound);
2090 ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2093 /// Given the bounds on an object, determines what single region bound
2094 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
2095 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
2096 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
2097 fn compute_object_lifetime_bound<'tcx>(
2098 this: &AstConv<'tcx>,
2100 explicit_region_bounds: &[&hir::Lifetime],
2101 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2102 builtin_bounds: ty::BuiltinBounds)
2103 -> Option<ty::Region> // if None, use the default
2105 let tcx = this.tcx();
2107 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2108 principal_trait_ref={:?}, builtin_bounds={:?})",
2109 explicit_region_bounds,
2110 principal_trait_ref,
2113 if explicit_region_bounds.len() > 1 {
2114 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2115 "only a single explicit lifetime bound is permitted");
2118 if !explicit_region_bounds.is_empty() {
2119 // Explicitly specified region bound. Use that.
2120 let r = explicit_region_bounds[0];
2121 return Some(ast_region_to_region(tcx, r));
2124 if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
2125 return Some(ty::ReStatic);
2128 // No explicit region bound specified. Therefore, examine trait
2129 // bounds and see if we can derive region bounds from those.
2130 let derived_region_bounds =
2131 object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2133 // If there are no derived region bounds, then report back that we
2134 // can find no region bound. The caller will use the default.
2135 if derived_region_bounds.is_empty() {
2139 // If any of the derived region bounds are 'static, that is always
2141 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2142 return Some(ty::ReStatic);
2145 // Determine whether there is exactly one unique region in the set
2146 // of derived region bounds. If so, use that. Otherwise, report an
2148 let r = derived_region_bounds[0];
2149 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2150 span_err!(tcx.sess, span, E0227,
2151 "ambiguous lifetime bound, explicit lifetime bound required");
2156 pub struct PartitionedBounds<'a> {
2157 pub builtin_bounds: ty::BuiltinBounds,
2158 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2159 pub region_bounds: Vec<&'a hir::Lifetime>,
2162 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2163 /// general trait bounds, and region bounds.
2164 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
2166 ast_bounds: &'a [hir::TyParamBound])
2167 -> PartitionedBounds<'a>
2169 let mut builtin_bounds = ty::BuiltinBounds::empty();
2170 let mut region_bounds = Vec::new();
2171 let mut trait_bounds = Vec::new();
2172 for ast_bound in ast_bounds {
2174 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2175 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2176 def::DefTrait(trait_did) => {
2177 if tcx.try_add_builtin_trait(trait_did,
2178 &mut builtin_bounds) {
2179 let segments = &b.trait_ref.path.segments;
2180 let parameters = &segments[segments.len() - 1].parameters;
2181 if !parameters.types().is_empty() {
2182 check_type_argument_count(tcx, b.trait_ref.path.span,
2183 parameters.types().len(), 0, 0);
2185 if !parameters.lifetimes().is_empty() {
2186 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2187 parameters.lifetimes().len(), 0);
2189 continue; // success
2193 // Not a trait? that's an error, but it'll get
2197 trait_bounds.push(b);
2199 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2200 hir::RegionTyParamBound(ref l) => {
2201 region_bounds.push(l);
2207 builtin_bounds: builtin_bounds,
2208 trait_bounds: trait_bounds,
2209 region_bounds: region_bounds,
2213 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
2214 bindings: &[ConvertedBinding<'tcx>])
2216 for binding in bindings.iter().take(1) {
2217 prohibit_projection(tcx, binding.span);
2221 fn check_type_argument_count(tcx: &ty::ctxt, span: Span, supplied: usize,
2222 required: usize, accepted: usize) {
2223 if supplied < required {
2224 let expected = if required < accepted {
2229 span_err!(tcx.sess, span, E0243,
2230 "wrong number of type arguments: {} {}, found {}",
2231 expected, required, supplied);
2232 } else if supplied > accepted {
2233 let expected = if required < accepted {
2238 span_err!(tcx.sess, span, E0244,
2239 "wrong number of type arguments: {} {}, found {}",
2246 fn report_lifetime_number_error(tcx: &ty::ctxt, span: Span, number: usize, expected: usize) {
2247 span_err!(tcx.sess, span, E0107,
2248 "wrong number of lifetime parameters: expected {}, found {}",
2252 // A helper struct for conveniently grouping a set of bounds which we pass to
2253 // and return from functions in multiple places.
2254 #[derive(PartialEq, Eq, Clone, Debug)]
2255 pub struct Bounds<'tcx> {
2256 pub region_bounds: Vec<ty::Region>,
2257 pub builtin_bounds: ty::BuiltinBounds,
2258 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2259 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2262 impl<'tcx> Bounds<'tcx> {
2263 pub fn predicates(&self,
2264 tcx: &ty::ctxt<'tcx>,
2266 -> Vec<ty::Predicate<'tcx>>
2268 let mut vec = Vec::new();
2270 for builtin_bound in &self.builtin_bounds {
2271 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
2272 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2273 Err(ErrorReported) => { }
2277 for ®ion_bound in &self.region_bounds {
2278 // account for the binder being introduced below; no need to shift `param_ty`
2279 // because, at present at least, it can only refer to early-bound regions
2280 let region_bound = ty::fold::shift_region(region_bound, 1);
2281 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2284 for bound_trait_ref in &self.trait_bounds {
2285 vec.push(bound_trait_ref.to_predicate());
2288 for projection in &self.projection_bounds {
2289 vec.push(projection.to_predicate());