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::errors::DiagnosticBuilder;
72 use syntax::feature_gate::{GateIssue, emit_feature_err};
73 use syntax::parse::token;
75 use rustc_front::print::pprust;
77 use rustc_back::slice;
79 pub trait AstConv<'tcx> {
80 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
82 /// Identify the type scheme for an item with a type, like a type
83 /// alias, fn, or struct. This allows you to figure out the set of
84 /// type parameters defined on the item.
85 fn get_item_type_scheme(&self, span: Span, id: DefId)
86 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
88 /// Returns the `TraitDef` for a given trait. This allows you to
89 /// figure out the set of type parameters defined on the trait.
90 fn get_trait_def(&self, span: Span, id: DefId)
91 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
93 /// Ensure that the super-predicates for the trait with the given
94 /// id are available and also for the transitive set of
96 fn ensure_super_predicates(&self, span: Span, id: DefId)
97 -> Result<(), ErrorReported>;
99 /// Returns the set of bounds in scope for the type parameter with
101 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
102 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
104 /// Returns true if the trait with id `trait_def_id` defines an
105 /// associated type with the name `name`.
106 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
109 /// Return an (optional) substitution to convert bound type parameters that
110 /// are in scope into free ones. This function should only return Some
111 /// within a fn body.
112 /// See ParameterEnvironment::free_substs for more information.
113 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
117 /// What type should we use when a type is omitted?
119 param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
120 substs: Option<&mut Substs<'tcx>>,
121 space: Option<ParamSpace>,
122 span: Span) -> Ty<'tcx>;
124 /// Projecting an associated type from a (potentially)
125 /// higher-ranked trait reference is more complicated, because of
126 /// the possibility of late-bound regions appearing in the
127 /// associated type binding. This is not legal in function
128 /// signatures for that reason. In a function body, we can always
129 /// handle it because we can use inference variables to remove the
130 /// late-bound regions.
131 fn projected_ty_from_poly_trait_ref(&self,
133 poly_trait_ref: ty::PolyTraitRef<'tcx>,
134 item_name: ast::Name)
137 if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
138 self.projected_ty(span, trait_ref, item_name)
140 // no late-bound regions, we can just ignore the binder
141 span_err!(self.tcx().sess, span, E0212,
142 "cannot extract an associated type from a higher-ranked trait bound \
148 /// Project an associated type from a non-higher-ranked trait reference.
149 /// This is fairly straightforward and can be accommodated in any context.
150 fn projected_ty(&self,
152 _trait_ref: ty::TraitRef<'tcx>,
153 _item_name: ast::Name)
157 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &hir::Lifetime)
159 let r = match tcx.named_region_map.get(&lifetime.id) {
161 // should have been recorded by the `resolve_lifetime` pass
162 tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
165 Some(&rl::DefStaticRegion) => {
169 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
170 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id), lifetime.name))
173 Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
174 ty::ReEarlyBound(ty::EarlyBoundRegion {
181 Some(&rl::DefFreeRegion(scope, id)) => {
182 ty::ReFree(ty::FreeRegion {
183 scope: scope.to_code_extent(&tcx.region_maps),
184 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
190 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
198 fn report_elision_failure(
199 db: &mut DiagnosticBuilder,
201 params: Vec<ElisionFailureInfo>)
203 let mut m = String::new();
204 let len = params.len();
205 let mut any_lifetimes = false;
207 for (i, info) in params.into_iter().enumerate() {
208 let ElisionFailureInfo {
209 name, lifetime_count: n, have_bound_regions
212 any_lifetimes = any_lifetimes || (n > 0);
214 let help_name = if name.is_empty() {
215 format!("argument {}", i + 1)
217 format!("`{}`", name)
220 m.push_str(&(if n == 1 {
223 format!("one of {}'s {} elided {}lifetimes", help_name, n,
224 if have_bound_regions { "free " } else { "" } )
227 if len == 2 && i == 0 {
229 } else if i + 2 == len {
231 } else if i + 1 != len {
237 fileline_help!(db, default_span,
238 "this function's return type contains a borrowed value, but \
239 there is no value for it to be borrowed from");
240 fileline_help!(db, default_span,
241 "consider giving it a 'static lifetime");
242 } else if !any_lifetimes {
243 fileline_help!(db, default_span,
244 "this function's return type contains a borrowed value with \
245 an elided lifetime, but the lifetime cannot be derived from \
247 fileline_help!(db, default_span,
248 "consider giving it an explicit bounded or 'static \
251 fileline_help!(db, default_span,
252 "this function's return type contains a borrowed value, but \
253 the signature does not say which {} it is borrowed from",
256 fileline_help!(db, default_span,
257 "this function's return type contains a borrowed value, but \
258 the signature does not say whether it is borrowed from {}",
263 pub fn opt_ast_region_to_region<'tcx>(
264 this: &AstConv<'tcx>,
265 rscope: &RegionScope,
267 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
269 let r = match *opt_lifetime {
270 Some(ref lifetime) => {
271 ast_region_to_region(this.tcx(), lifetime)
274 None => match rscope.anon_regions(default_span, 1) {
277 let mut err = struct_span_err!(this.tcx().sess, default_span, E0106,
278 "missing lifetime specifier");
279 if let Some(params) = params {
280 report_elision_failure(&mut err, default_span, params);
288 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
295 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
296 /// returns an appropriate set of substitutions for this particular reference to `I`.
297 pub fn ast_path_substs_for_ty<'tcx>(
298 this: &AstConv<'tcx>,
299 rscope: &RegionScope,
301 param_mode: PathParamMode,
302 decl_generics: &ty::Generics<'tcx>,
303 item_segment: &hir::PathSegment)
306 let tcx = this.tcx();
308 // ast_path_substs() is only called to convert paths that are
309 // known to refer to traits, types, or structs. In these cases,
310 // all type parameters defined for the item being referenced will
311 // be in the TypeSpace or SelfSpace.
313 // Note: in the case of traits, the self parameter is also
314 // defined, but we don't currently create a `type_param_def` for
315 // `Self` because it is implicit.
316 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
317 assert!(decl_generics.types.all(|d| d.space != FnSpace));
319 let (regions, types, assoc_bindings) = match item_segment.parameters {
320 hir::AngleBracketedParameters(ref data) => {
321 convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
323 hir::ParenthesizedParameters(..) => {
324 span_err!(tcx.sess, span, E0214,
325 "parenthesized parameters may only be used with a trait");
326 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
328 ty_param_defs.iter().map(|_| tcx.types.err).collect(),
333 prohibit_projections(this.tcx(), &assoc_bindings);
335 create_substs_for_ast_path(this,
344 #[derive(PartialEq, Eq)]
345 pub enum PathParamMode {
346 // Any path in a type context.
348 // The `module::Type` in `module::Type::method` in an expression.
352 fn create_region_substs<'tcx>(
353 this: &AstConv<'tcx>,
354 rscope: &RegionScope,
356 decl_generics: &ty::Generics<'tcx>,
357 regions_provided: Vec<ty::Region>)
360 let tcx = this.tcx();
362 // If the type is parameterized by this region, then replace this
363 // region with the current anon region binding (in other words,
364 // whatever & would get replaced with).
365 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
366 let supplied_num_region_params = regions_provided.len();
367 let regions = if expected_num_region_params == supplied_num_region_params {
371 rscope.anon_regions(span, expected_num_region_params);
373 if supplied_num_region_params != 0 || anon_regions.is_err() {
374 report_lifetime_number_error(tcx, span,
375 supplied_num_region_params,
376 expected_num_region_params);
380 Ok(anon_regions) => anon_regions,
381 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
384 Substs::new_type(vec![], regions)
387 /// Given the type/region arguments provided to some path (along with
388 /// an implicit Self, if this is a trait reference) returns the complete
389 /// set of substitutions. This may involve applying defaulted type parameters.
391 /// Note that the type listing given here is *exactly* what the user provided.
393 /// The `region_substs` should be the result of `create_region_substs`
394 /// -- that is, a substitution with no types but the correct number of
396 fn create_substs_for_ast_path<'tcx>(
397 this: &AstConv<'tcx>,
399 param_mode: PathParamMode,
400 decl_generics: &ty::Generics<'tcx>,
401 self_ty: Option<Ty<'tcx>>,
402 types_provided: Vec<Ty<'tcx>>,
403 region_substs: Substs<'tcx>)
406 let tcx = this.tcx();
408 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
409 types_provided={:?}, region_substs={:?})",
410 decl_generics, self_ty, types_provided,
413 assert_eq!(region_substs.regions().len(TypeSpace), decl_generics.regions.len(TypeSpace));
414 assert!(region_substs.types.is_empty());
416 // Convert the type parameters supplied by the user.
417 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
418 let formal_ty_param_count = ty_param_defs.len();
419 let required_ty_param_count = ty_param_defs.iter()
420 .take_while(|x| x.default.is_none())
423 let mut type_substs = get_type_substs_for_defs(this,
428 region_substs.clone(),
431 let supplied_ty_param_count = type_substs.len();
432 check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
433 required_ty_param_count, formal_ty_param_count);
435 if supplied_ty_param_count < required_ty_param_count {
436 while type_substs.len() < required_ty_param_count {
437 type_substs.push(tcx.types.err);
439 } else if supplied_ty_param_count > formal_ty_param_count {
440 type_substs.truncate(formal_ty_param_count);
442 assert!(type_substs.len() >= required_ty_param_count &&
443 type_substs.len() <= formal_ty_param_count);
445 let mut substs = region_substs;
446 substs.types.extend(TypeSpace, type_substs.into_iter());
450 // If no self-type is provided, it's still possible that
451 // one was declared, because this could be an object type.
454 // If a self-type is provided, one should have been
455 // "declared" (in other words, this should be a
457 assert!(decl_generics.types.get_self().is_some());
458 substs.types.push(SelfSpace, ty);
462 let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
463 for param in &ty_param_defs[actual_supplied_ty_param_count..] {
464 if let Some(default) = param.default {
465 // If we are converting an object type, then the
466 // `Self` parameter is unknown. However, some of the
467 // other type parameters may reference `Self` in their
468 // defaults. This will lead to an ICE if we are not
470 if self_ty.is_none() && default.has_self_ty() {
471 span_err!(tcx.sess, span, E0393,
472 "the type parameter `{}` must be explicitly specified \
473 in an object type because its default value `{}` references \
477 substs.types.push(TypeSpace, tcx.types.err);
479 // This is a default type parameter.
480 let default = default.subst_spanned(tcx,
483 substs.types.push(TypeSpace, default);
486 tcx.sess.span_bug(span, "extra parameter without default");
490 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
491 decl_generics, self_ty, substs);
496 /// Returns types_provided if it is not empty, otherwise populating the
497 /// type parameters with inference variables as appropriate.
498 fn get_type_substs_for_defs<'tcx>(this: &AstConv<'tcx>,
500 types_provided: Vec<Ty<'tcx>>,
501 param_mode: PathParamMode,
502 ty_param_defs: &[ty::TypeParameterDef<'tcx>],
503 mut substs: Substs<'tcx>,
504 self_ty: Option<Ty<'tcx>>)
507 fn default_type_parameter<'tcx>(p: &ty::TypeParameterDef<'tcx>, self_ty: Option<Ty<'tcx>>)
508 -> Option<ty::TypeParameterDef<'tcx>>
510 if let Some(ref default) = p.default {
511 if self_ty.is_none() && default.has_self_ty() {
512 // There is no suitable inference default for a type parameter
513 // that references self with no self-type provided.
521 if param_mode == PathParamMode::Optional && types_provided.is_empty() {
524 .map(|p| this.ty_infer(default_type_parameter(p, self_ty), Some(&mut substs),
525 Some(TypeSpace), span))
532 struct ConvertedBinding<'tcx> {
533 item_name: ast::Name,
538 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
539 rscope: &RegionScope,
541 decl_generics: &ty::Generics<'tcx>,
542 data: &hir::AngleBracketedParameterData)
545 Vec<ConvertedBinding<'tcx>>)
547 let regions: Vec<_> =
548 data.lifetimes.iter()
549 .map(|l| ast_region_to_region(this.tcx(), l))
553 create_region_substs(this, rscope, span, decl_generics, regions);
558 .map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
559 i, ®ion_substs, t))
562 let assoc_bindings: Vec<_> =
564 .map(|b| ConvertedBinding { item_name: b.name,
565 ty: ast_ty_to_ty(this, rscope, &*b.ty),
569 (region_substs, types, assoc_bindings)
572 /// Returns the appropriate lifetime to use for any output lifetimes
573 /// (if one exists) and a vector of the (pattern, number of lifetimes)
574 /// corresponding to each input type/pattern.
575 fn find_implied_output_region<'tcx>(tcx: &ty::ctxt<'tcx>,
576 input_tys: &[Ty<'tcx>],
577 input_pats: Vec<String>) -> ElidedLifetime
579 let mut lifetimes_for_params = Vec::new();
580 let mut possible_implied_output_region = None;
582 for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
583 let mut regions = FnvHashSet();
584 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
586 debug!("find_implied_output_regions: collected {:?} from {:?} \
587 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
589 if regions.len() == 1 {
590 // there's a chance that the unique lifetime of this
591 // iteration will be the appropriate lifetime for output
592 // parameters, so lets store it.
593 possible_implied_output_region = regions.iter().cloned().next();
596 lifetimes_for_params.push(ElisionFailureInfo {
598 lifetime_count: regions.len(),
599 have_bound_regions: have_bound_regions
603 if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
604 Ok(possible_implied_output_region.unwrap())
606 Err(Some(lifetimes_for_params))
610 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
611 elided_lifetime: ElidedLifetime,
615 match elided_lifetime {
616 Ok(implied_output_region) => {
617 let rb = ElidableRscope::new(implied_output_region);
618 ast_ty_to_ty(this, &rb, ty)
620 Err(param_lifetimes) => {
621 // All regions must be explicitly specified in the output
622 // if the lifetime elision rules do not apply. This saves
623 // the user from potentially-confusing errors.
624 let rb = UnelidableRscope::new(param_lifetimes);
625 ast_ty_to_ty(this, &rb, ty)
630 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
631 rscope: &RegionScope,
633 decl_generics: &ty::Generics<'tcx>,
634 data: &hir::ParenthesizedParameterData)
637 Vec<ConvertedBinding<'tcx>>)
640 create_region_substs(this, rscope, span, decl_generics, Vec::new());
642 let binding_rscope = BindingRscope::new();
645 .map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
646 0, ®ion_substs, a_t))
647 .collect::<Vec<Ty<'tcx>>>();
649 let input_params = vec![String::new(); inputs.len()];
650 let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
652 let input_ty = this.tcx().mk_tup(inputs);
654 let (output, output_span) = match data.output {
655 Some(ref output_ty) => {
656 (convert_ty_with_lifetime_elision(this,
657 implied_output_region,
662 (this.tcx().mk_nil(), data.span)
666 let output_binding = ConvertedBinding {
667 item_name: token::intern(FN_OUTPUT_NAME),
672 (region_substs, vec![input_ty], vec![output_binding])
675 pub fn instantiate_poly_trait_ref<'tcx>(
676 this: &AstConv<'tcx>,
677 rscope: &RegionScope,
678 ast_trait_ref: &hir::PolyTraitRef,
679 self_ty: Option<Ty<'tcx>>,
680 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
681 -> ty::PolyTraitRef<'tcx>
683 let trait_ref = &ast_trait_ref.trait_ref;
684 let trait_def_id = trait_def_id(this, trait_ref);
685 ast_path_to_poly_trait_ref(this,
688 PathParamMode::Explicit,
691 trait_ref.path.segments.last().unwrap(),
695 /// Instantiates the path for the given trait reference, assuming that it's
696 /// bound to a valid trait type. Returns the def_id for the defining trait.
697 /// Fails if the type is a type other than a trait type.
699 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
700 /// are disallowed. Otherwise, they are pushed onto the vector given.
701 pub fn instantiate_mono_trait_ref<'tcx>(
702 this: &AstConv<'tcx>,
703 rscope: &RegionScope,
704 trait_ref: &hir::TraitRef,
705 self_ty: Option<Ty<'tcx>>)
706 -> ty::TraitRef<'tcx>
708 let trait_def_id = trait_def_id(this, trait_ref);
709 ast_path_to_mono_trait_ref(this,
712 PathParamMode::Explicit,
715 trait_ref.path.segments.last().unwrap())
718 fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &hir::TraitRef) -> DefId {
719 let path = &trait_ref.path;
720 match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
721 def::DefTrait(trait_def_id) => trait_def_id,
723 this.tcx().sess.fatal("cannot continue compilation due to previous error");
726 span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
732 fn object_path_to_poly_trait_ref<'a,'tcx>(
733 this: &AstConv<'tcx>,
734 rscope: &RegionScope,
736 param_mode: PathParamMode,
738 trait_segment: &hir::PathSegment,
739 mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
740 -> ty::PolyTraitRef<'tcx>
742 ast_path_to_poly_trait_ref(this,
752 fn ast_path_to_poly_trait_ref<'a,'tcx>(
753 this: &AstConv<'tcx>,
754 rscope: &RegionScope,
756 param_mode: PathParamMode,
758 self_ty: Option<Ty<'tcx>>,
759 trait_segment: &hir::PathSegment,
760 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
761 -> ty::PolyTraitRef<'tcx>
763 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
764 // The trait reference introduces a binding level here, so
765 // we need to shift the `rscope`. It'd be nice if we could
766 // do away with this rscope stuff and work this knowledge
767 // into resolve_lifetimes, as we do with non-omitted
768 // lifetimes. Oh well, not there yet.
769 let shifted_rscope = &ShiftedRscope::new(rscope);
771 let (substs, assoc_bindings) =
772 create_substs_for_ast_trait_ref(this,
779 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
782 let converted_bindings =
785 .filter_map(|binding| {
786 // specify type to assert that error was already reported in Err case:
787 let predicate: Result<_, ErrorReported> =
788 ast_type_binding_to_poly_projection_predicate(this,
789 poly_trait_ref.clone(),
792 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
794 poly_projections.extend(converted_bindings);
797 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
798 trait_segment, poly_projections, poly_trait_ref);
802 fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
803 rscope: &RegionScope,
805 param_mode: PathParamMode,
807 self_ty: Option<Ty<'tcx>>,
808 trait_segment: &hir::PathSegment)
809 -> ty::TraitRef<'tcx>
811 let (substs, assoc_bindings) =
812 create_substs_for_ast_trait_ref(this,
819 prohibit_projections(this.tcx(), &assoc_bindings);
820 ty::TraitRef::new(trait_def_id, substs)
823 fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
824 rscope: &RegionScope,
826 param_mode: PathParamMode,
828 self_ty: Option<Ty<'tcx>>,
829 trait_segment: &hir::PathSegment)
830 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
832 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
835 let trait_def = match this.get_trait_def(span, trait_def_id) {
836 Ok(trait_def) => trait_def,
837 Err(ErrorReported) => {
838 // No convenient way to recover from a cycle here. Just bail. Sorry!
839 this.tcx().sess.abort_if_errors();
840 this.tcx().sess.bug("ErrorReported returned, but no errors reports?")
844 let (regions, types, assoc_bindings) = match trait_segment.parameters {
845 hir::AngleBracketedParameters(ref data) => {
846 // For now, require that parenthetical notation be used
847 // only with `Fn()` etc.
848 if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
849 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
850 "unboxed_closures", span, GateIssue::Language,
852 the precise format of `Fn`-family traits' type parameters is \
853 subject to change. Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
856 convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
858 hir::ParenthesizedParameters(ref data) => {
859 // For now, require that parenthetical notation be used
860 // only with `Fn()` etc.
861 if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
862 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
863 "unboxed_closures", span, GateIssue::Language,
865 parenthetical notation is only stable when used with `Fn`-family traits");
868 convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
872 let substs = create_substs_for_ast_path(this,
880 (this.tcx().mk_substs(substs), assoc_bindings)
883 fn ast_type_binding_to_poly_projection_predicate<'tcx>(
884 this: &AstConv<'tcx>,
885 mut trait_ref: ty::PolyTraitRef<'tcx>,
886 self_ty: Option<Ty<'tcx>>,
887 binding: &ConvertedBinding<'tcx>)
888 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
890 let tcx = this.tcx();
892 // Given something like `U : SomeTrait<T=X>`, we want to produce a
893 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
894 // subtle in the event that `T` is defined in a supertrait of
895 // `SomeTrait`, because in that case we need to upcast.
897 // That is, consider this case:
900 // trait SubTrait : SuperTrait<int> { }
901 // trait SuperTrait<A> { type T; }
903 // ... B : SubTrait<T=foo> ...
906 // We want to produce `<B as SuperTrait<int>>::T == foo`.
908 // Simple case: X is defined in the current trait.
909 if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
910 return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
911 projection_ty: ty::ProjectionTy { // |
912 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
913 item_name: binding.item_name,
919 // Otherwise, we have to walk through the supertraits to find
920 // those that do. This is complicated by the fact that, for an
921 // object type, the `Self` type is not present in the
922 // substitutions (after all, it's being constructed right now),
923 // but the `supertraits` iterator really wants one. To handle
924 // this, we currently insert a dummy type and then remove it
927 let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
928 if self_ty.is_none() { // if converting for an object type
929 let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
930 assert!(dummy_substs.self_ty().is_none()); // |
931 dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
932 trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(), // <------------+
933 tcx.mk_substs(dummy_substs)));
936 try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
938 let mut candidates: Vec<ty::PolyTraitRef> =
939 traits::supertraits(tcx, trait_ref.clone())
940 .filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
943 // If converting for an object type, then remove the dummy-ty from `Self` now.
945 if self_ty.is_none() {
946 for candidate in &mut candidates {
947 let mut dummy_substs = candidate.0.substs.clone();
948 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
949 dummy_substs.types.pop(SelfSpace);
950 *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
951 tcx.mk_substs(dummy_substs)));
955 let candidate = try!(one_bound_for_assoc_type(tcx,
957 &trait_ref.to_string(),
958 &binding.item_name.as_str(),
961 Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
962 projection_ty: ty::ProjectionTy { // |
963 trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
964 item_name: binding.item_name,
970 fn ast_path_to_ty<'tcx>(
971 this: &AstConv<'tcx>,
972 rscope: &RegionScope,
974 param_mode: PathParamMode,
976 item_segment: &hir::PathSegment)
979 let tcx = this.tcx();
980 let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
981 Ok(ty::TypeScheme { generics, ty: decl_ty }) => {
984 Err(ErrorReported) => {
985 return tcx.types.err;
989 let substs = ast_path_substs_for_ty(this,
996 // FIXME(#12938): This is a hack until we have full support for DST.
997 if Some(did) == this.tcx().lang_items.owned_box() {
998 assert_eq!(substs.types.len(TypeSpace), 1);
999 return this.tcx().mk_box(*substs.types.get(TypeSpace, 0));
1002 decl_ty.subst(this.tcx(), &substs)
1005 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
1007 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
1008 rscope: &RegionScope,
1010 bounds: &[hir::TyParamBound])
1011 -> Result<TraitAndProjections<'tcx>, ErrorReported>
1014 * In a type like `Foo + Send`, we want to wait to collect the
1015 * full set of bounds before we make the object type, because we
1016 * need them to infer a region bound. (For example, if we tried
1017 * made a type from just `Foo`, then it wouldn't be enough to
1018 * infer a 'static bound, and hence the user would get an error.)
1019 * So this function is used when we're dealing with a sum type to
1020 * convert the LHS. It only accepts a type that refers to a trait
1021 * name, and reports an error otherwise.
1025 hir::TyPath(None, ref path) => {
1026 let def = match this.tcx().def_map.borrow().get(&ty.id) {
1027 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
1031 Some(def::DefTrait(trait_def_id)) => {
1032 let mut projection_bounds = Vec::new();
1033 let trait_ref = object_path_to_poly_trait_ref(this,
1036 PathParamMode::Explicit,
1038 path.segments.last().unwrap(),
1039 &mut projection_bounds);
1040 Ok((trait_ref, projection_bounds))
1043 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
1049 let mut err = struct_span_err!(this.tcx().sess, ty.span, E0178,
1050 "expected a path on the left-hand side of `+`, not `{}`",
1051 pprust::ty_to_string(ty));
1052 let hi = bounds.iter().map(|x| match *x {
1053 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
1054 hir::RegionTyParamBound(ref r) => r.span.hi,
1055 }).max_by_key(|x| x.to_usize());
1056 let full_span = hi.map(|hi| Span {
1059 expn_id: ty.span.expn_id,
1061 match (&ty.node, full_span) {
1062 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1063 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1064 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1065 format!("&{}({} +{})",
1067 pprust::ty_to_string(&*mut_ty.ty),
1068 pprust::bounds_to_string(bounds)));
1070 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1071 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1072 err.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!(&mut err, ty.span,
1082 "perhaps you forgot parentheses? (per RFC 438)");
1091 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
1092 rscope: &RegionScope,
1094 trait_ref: ty::PolyTraitRef<'tcx>,
1095 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1096 bounds: &[hir::TyParamBound])
1099 let existential_bounds = conv_existential_bounds(this,
1106 let result = make_object_type(this, span, trait_ref, existential_bounds);
1107 debug!("trait_ref_to_object_type: result={:?}",
1113 fn make_object_type<'tcx>(this: &AstConv<'tcx>,
1115 principal: ty::PolyTraitRef<'tcx>,
1116 bounds: ty::ExistentialBounds<'tcx>)
1118 let tcx = this.tcx();
1119 let object = ty::TraitTy {
1120 principal: principal,
1123 let object_trait_ref =
1124 object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1126 // ensure the super predicates and stop if we encountered an error
1127 if this.ensure_super_predicates(span, principal.def_id()).is_err() {
1128 return tcx.types.err;
1131 // check that there are no gross object safety violations,
1132 // most importantly, that the supertraits don't contain Self,
1134 let object_safety_violations =
1135 traits::astconv_object_safety_violations(tcx, principal.def_id());
1136 if !object_safety_violations.is_empty() {
1137 traits::report_object_safety_error(
1138 tcx, span, principal.def_id(), object_safety_violations)
1140 return tcx.types.err;
1143 let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1144 traits::supertraits(tcx, object_trait_ref)
1146 let trait_def = tcx.lookup_trait_def(tr.def_id());
1147 trait_def.associated_type_names
1150 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1154 for projection_bound in &object.bounds.projection_bounds {
1155 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1156 projection_bound.0.projection_ty.item_name);
1157 associated_types.remove(&pair);
1160 for (trait_def_id, name) in associated_types {
1161 span_err!(tcx.sess, span, E0191,
1162 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1164 tcx.item_path_str(trait_def_id));
1167 tcx.mk_trait(object.principal, object.bounds)
1170 fn report_ambiguous_associated_type(tcx: &ty::ctxt,
1175 span_err!(tcx.sess, span, E0223,
1176 "ambiguous associated type; specify the type using the syntax \
1178 type_str, trait_str, name);
1181 // Search for a bound on a type parameter which includes the associated item
1182 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1183 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1184 // impl). This function will fail if there are no suitable bounds or there is
1186 fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
1187 ty_param_node_id: ast::NodeId,
1188 ty_param_name: ast::Name,
1189 assoc_name: ast::Name,
1191 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1193 let tcx = this.tcx();
1195 let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
1197 Err(ErrorReported) => {
1198 return Err(ErrorReported);
1202 // Ensure the super predicates and stop if we encountered an error.
1203 if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
1204 return Err(ErrorReported);
1207 // Check that there is exactly one way to find an associated type with the
1209 let suitable_bounds: Vec<_> =
1210 traits::transitive_bounds(tcx, &bounds)
1211 .filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
1214 one_bound_for_assoc_type(tcx,
1216 &ty_param_name.as_str(),
1217 &assoc_name.as_str(),
1222 // Checks that bounds contains exactly one element and reports appropriate
1223 // errors otherwise.
1224 fn one_bound_for_assoc_type<'tcx>(tcx: &ty::ctxt<'tcx>,
1225 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1226 ty_param_name: &str,
1229 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1231 if bounds.is_empty() {
1232 span_err!(tcx.sess, span, E0220,
1233 "associated type `{}` not found for `{}`",
1236 return Err(ErrorReported);
1239 if bounds.len() > 1 {
1240 let mut err = struct_span_err!(tcx.sess, span, E0221,
1241 "ambiguous associated type `{}` in bounds of `{}`",
1245 for bound in &bounds {
1246 span_note!(&mut err, span,
1247 "associated type `{}` could derive from `{}`",
1254 Ok(bounds[0].clone())
1257 // Create a type from a path to an associated type.
1258 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1259 // and item_segment is the path segment for D. We return a type and a def for
1261 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1262 // parameter or Self.
1263 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1266 ty_path_def: def::Def,
1267 item_segment: &hir::PathSegment)
1268 -> (Ty<'tcx>, def::Def)
1270 let tcx = this.tcx();
1271 let assoc_name = item_segment.identifier.name;
1273 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1275 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1277 // Find the type of the associated item, and the trait where the associated
1278 // item is declared.
1279 let bound = match (&ty.sty, ty_path_def) {
1280 (_, def::DefSelfTy(Some(trait_did), Some((impl_id, _)))) => {
1281 // `Self` in an impl of a trait - we have a concrete self type and a
1283 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1284 let trait_ref = if let Some(free_substs) = this.get_free_substs() {
1285 trait_ref.subst(tcx, free_substs)
1290 if this.ensure_super_predicates(span, trait_did).is_err() {
1291 return (tcx.types.err, ty_path_def);
1294 let candidates: Vec<ty::PolyTraitRef> =
1295 traits::supertraits(tcx, ty::Binder(trait_ref))
1296 .filter(|r| this.trait_defines_associated_type_named(r.def_id(),
1300 match one_bound_for_assoc_type(tcx,
1303 &assoc_name.as_str(),
1306 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1309 (&ty::TyParam(_), def::DefSelfTy(Some(trait_did), None)) => {
1310 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1311 match find_bound_for_assoc_item(this,
1313 token::special_idents::type_self.name,
1317 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1320 (&ty::TyParam(_), def::DefTyParam(_, _, param_did, param_name)) => {
1321 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1322 match find_bound_for_assoc_item(this,
1328 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1332 report_ambiguous_associated_type(tcx,
1336 &assoc_name.as_str());
1337 return (tcx.types.err, ty_path_def);
1341 let trait_did = bound.0.def_id;
1342 let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1344 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1345 // `ty::trait_items` used below requires information generated
1346 // by type collection, which may be in progress at this point.
1347 match tcx.map.expect_item(trait_id).node {
1348 hir::ItemTrait(_, _, _, ref trait_items) => {
1349 let item = trait_items.iter()
1350 .find(|i| i.name == assoc_name)
1351 .expect("missing associated type");
1352 tcx.map.local_def_id(item.id)
1357 let trait_items = tcx.trait_items(trait_did);
1358 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1359 item.expect("missing associated type").def_id()
1362 (ty, def::DefAssociatedTy(trait_did, item_did))
1365 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1366 rscope: &RegionScope,
1368 param_mode: PathParamMode,
1369 opt_self_ty: Option<Ty<'tcx>>,
1370 trait_def_id: DefId,
1371 trait_segment: &hir::PathSegment,
1372 item_segment: &hir::PathSegment)
1375 let tcx = this.tcx();
1377 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1379 let self_ty = if let Some(ty) = opt_self_ty {
1382 let path_str = tcx.item_path_str(trait_def_id);
1383 report_ambiguous_associated_type(tcx,
1387 &item_segment.identifier.name.as_str());
1388 return tcx.types.err;
1391 debug!("qpath_to_ty: self_type={:?}", self_ty);
1393 let trait_ref = ast_path_to_mono_trait_ref(this,
1401 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1403 this.projected_ty(span, trait_ref, item_segment.identifier.name)
1406 /// Convert a type supplied as value for a type argument from AST into our
1407 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1408 /// it applies the object lifetime default.
1412 /// * `this`, `rscope`: the surrounding context
1413 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1415 /// * `index`: the index of the type parameter being instantiated from the list
1416 /// (we assume it is in the `TypeSpace`)
1417 /// * `region_substs`: a partial substitution consisting of
1418 /// only the region type parameters being supplied to this type.
1419 /// * `ast_ty`: the ast representation of the type being supplied
1420 pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
1421 rscope: &RegionScope,
1422 decl_generics: &ty::Generics<'tcx>,
1424 region_substs: &Substs<'tcx>,
1428 let tcx = this.tcx();
1430 if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1431 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1432 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1433 ast_ty_to_ty(this, rscope1, ast_ty)
1435 ast_ty_to_ty(this, rscope, ast_ty)
1439 // Check the base def in a PathResolution and convert it to a Ty. If there are
1440 // associated types in the PathResolution, these will need to be separately
1442 fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1443 rscope: &RegionScope,
1445 param_mode: PathParamMode,
1447 opt_self_ty: Option<Ty<'tcx>>,
1448 base_segments: &[hir::PathSegment])
1450 let tcx = this.tcx();
1453 def::DefTrait(trait_def_id) => {
1454 // N.B. this case overlaps somewhat with
1455 // TyObjectSum, see that fn for details
1456 let mut projection_bounds = Vec::new();
1458 let trait_ref = object_path_to_poly_trait_ref(this,
1463 base_segments.last().unwrap(),
1464 &mut projection_bounds);
1466 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1467 trait_ref_to_object_type(this,
1474 def::DefTy(did, _) | def::DefStruct(did) => {
1475 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1476 ast_path_to_ty(this,
1481 base_segments.last().unwrap())
1483 def::DefTyParam(space, index, _, name) => {
1484 prohibit_type_params(tcx, base_segments);
1485 tcx.mk_param(space, index, name)
1487 def::DefSelfTy(_, Some((_, self_ty_id))) => {
1488 // Self in impl (we know the concrete type).
1489 prohibit_type_params(tcx, base_segments);
1490 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
1491 if let Some(free_substs) = this.get_free_substs() {
1492 ty.subst(tcx, free_substs)
1497 tcx.sess.span_bug(span, "self type has not been fully resolved")
1500 def::DefSelfTy(Some(_), None) => {
1502 prohibit_type_params(tcx, base_segments);
1505 def::DefAssociatedTy(trait_did, _) => {
1506 prohibit_type_params(tcx, &base_segments[..base_segments.len()-2]);
1513 &base_segments[base_segments.len()-2],
1514 base_segments.last().unwrap())
1516 def::DefMod(id) => {
1517 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1518 // FIXME(#22519) This part of the resolution logic should be
1519 // avoided entirely for that form, once we stop needed a Def
1520 // for `associated_path_def_to_ty`.
1521 // Fixing this will also let use resolve <Self>::Foo the same way we
1522 // resolve Self::Foo, at the moment we can't resolve the former because
1523 // we don't have the trait information around, which is just sad.
1525 if !base_segments.is_empty() {
1526 let id_node = tcx.map.as_local_node_id(id).unwrap();
1530 "found module name used as a type: {}",
1531 tcx.map.node_to_user_string(id_node));
1532 return this.tcx().types.err;
1535 opt_self_ty.expect("missing T in <T>::a::b::c")
1537 def::DefPrimTy(prim_ty) => {
1538 prim_ty_to_ty(tcx, base_segments, prim_ty)
1541 return this.tcx().types.err;
1544 let id_node = tcx.map.as_local_node_id(def.def_id()).unwrap();
1545 span_err!(tcx.sess, span, E0248,
1546 "found value `{}` used as a type",
1547 tcx.map.path_to_string(id_node));
1548 return this.tcx().types.err;
1553 // Note that both base_segments and assoc_segments may be empty, although not at
1555 pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1556 rscope: &RegionScope,
1558 param_mode: PathParamMode,
1560 opt_self_ty: Option<Ty<'tcx>>,
1561 base_segments: &[hir::PathSegment],
1562 assoc_segments: &[hir::PathSegment])
1564 let mut ty = base_def_to_ty(this,
1572 // If any associated type segments remain, attempt to resolve them.
1573 for segment in assoc_segments {
1574 if ty.sty == ty::TyError {
1577 // This is pretty bad (it will fail except for T::A and Self::A).
1578 let (a_ty, a_def) = associated_path_def_to_ty(this,
1589 /// Parses the programmer's textual representation of a type into our
1590 /// internal notion of a type.
1591 pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
1592 rscope: &RegionScope,
1596 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1599 let tcx = this.tcx();
1601 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
1602 debug!("ast_ty_to_ty: id={:?} ty={:?} (cached)", ast_ty.id, ty);
1606 let typ = match ast_ty.node {
1607 hir::TyVec(ref ty) => {
1608 tcx.mk_slice(ast_ty_to_ty(this, rscope, &**ty))
1610 hir::TyObjectSum(ref ty, ref bounds) => {
1611 match ast_ty_to_trait_ref(this, rscope, &**ty, bounds) {
1612 Ok((trait_ref, projection_bounds)) => {
1613 trait_ref_to_object_type(this,
1620 Err(ErrorReported) => {
1621 this.tcx().types.err
1625 hir::TyPtr(ref mt) => {
1626 tcx.mk_ptr(ty::TypeAndMut {
1627 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1631 hir::TyRptr(ref region, ref mt) => {
1632 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1633 debug!("TyRef r={:?}", r);
1635 &ObjectLifetimeDefaultRscope::new(
1637 ty::ObjectLifetimeDefault::Specific(r));
1638 let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
1639 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1641 hir::TyTup(ref fields) => {
1642 let flds = fields.iter()
1643 .map(|t| ast_ty_to_ty(this, rscope, &**t))
1647 hir::TyBareFn(ref bf) => {
1648 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1649 let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1650 tcx.mk_fn(None, tcx.mk_bare_fn(bare_fn))
1652 hir::TyPolyTraitRef(ref bounds) => {
1653 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds)
1655 hir::TyPath(ref maybe_qself, ref path) => {
1656 let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
1658 } else if let Some(hir::QSelf { position: 0, .. }) = *maybe_qself {
1659 // Create some fake resolution that can't possibly be a type.
1660 def::PathResolution {
1661 base_def: def::DefMod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
1662 last_private: LastMod(AllPublic),
1663 depth: path.segments.len()
1666 tcx.sess.span_bug(ast_ty.span, &format!("unbound path {:?}", ast_ty))
1668 let def = path_res.base_def;
1669 let base_ty_end = path.segments.len() - path_res.depth;
1670 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1671 ast_ty_to_ty(this, rscope, &qself.ty)
1673 let ty = finish_resolving_def_to_ty(this,
1676 PathParamMode::Explicit,
1679 &path.segments[..base_ty_end],
1680 &path.segments[base_ty_end..]);
1682 if path_res.depth != 0 && ty.sty != ty::TyError {
1683 // Write back the new resolution.
1684 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1686 last_private: path_res.last_private,
1693 hir::TyFixedLengthVec(ref ty, ref e) => {
1694 let hint = UncheckedExprHint(tcx.types.usize);
1695 match const_eval::eval_const_expr_partial(tcx, &e, hint, None) {
1699 tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1701 ConstVal::Uint(i) =>
1702 tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1705 span_err!(tcx.sess, ast_ty.span, E0249,
1706 "expected constant integer expression \
1708 this.tcx().types.err
1713 let mut err = struct_span_err!(tcx.sess, r.span, E0250,
1714 "array length constant evaluation error: {}",
1716 if !ast_ty.span.contains(r.span) {
1717 span_note!(&mut err, ast_ty.span, "for array length here")
1720 this.tcx().types.err
1724 hir::TyTypeof(ref _e) => {
1725 span_err!(tcx.sess, ast_ty.span, E0516,
1726 "`typeof` is a reserved keyword but unimplemented");
1730 // TyInfer also appears as the type of arguments or return
1731 // values in a ExprClosure, or as
1732 // the type of local variables. Both of these cases are
1733 // handled specially and will not descend into this routine.
1734 this.ty_infer(None, None, None, ast_ty.span)
1738 debug!("ast_ty_to_ty: id={:?} ty={:?}", ast_ty.id, typ);
1739 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
1743 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1744 rscope: &RegionScope,
1746 expected_ty: Option<Ty<'tcx>>)
1750 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1751 hir::TyInfer => this.ty_infer(None, None, None, a.ty.span),
1752 _ => ast_ty_to_ty(this, rscope, &*a.ty),
1756 struct SelfInfo<'a, 'tcx> {
1757 untransformed_self_ty: Ty<'tcx>,
1758 explicit_self: &'a hir::ExplicitSelf,
1761 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1762 sig: &hir::MethodSig,
1763 untransformed_self_ty: Ty<'tcx>)
1764 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1765 let self_info = Some(SelfInfo {
1766 untransformed_self_ty: untransformed_self_ty,
1767 explicit_self: &sig.explicit_self,
1769 let (bare_fn_ty, optional_explicit_self_category) =
1770 ty_of_method_or_bare_fn(this,
1775 (bare_fn_ty, optional_explicit_self_category.unwrap())
1778 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: hir::Unsafety, abi: abi::Abi,
1779 decl: &hir::FnDecl) -> ty::BareFnTy<'tcx> {
1780 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1784 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1785 unsafety: hir::Unsafety,
1787 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1789 -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1791 debug!("ty_of_method_or_bare_fn");
1793 // New region names that appear inside of the arguments of the function
1794 // declaration are bound to that function type.
1795 let rb = rscope::BindingRscope::new();
1797 // `implied_output_region` is the region that will be assumed for any
1798 // region parameters in the return type. In accordance with the rules for
1799 // lifetime elision, we can determine it in two ways. First (determined
1800 // here), if self is by-reference, then the implied output region is the
1801 // region of the self parameter.
1802 let (self_ty, explicit_self_category) = match opt_self_info {
1803 None => (None, None),
1804 Some(self_info) => determine_self_type(this, &rb, self_info)
1807 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1808 let arg_params = if self_ty.is_some() {
1813 let arg_tys: Vec<Ty> =
1814 arg_params.iter().map(|a| ty_of_arg(this, &rb, a, None)).collect();
1815 let arg_pats: Vec<String> =
1816 arg_params.iter().map(|a| pprust::pat_to_string(&*a.pat)).collect();
1818 // Second, if there was exactly one lifetime (either a substitution or a
1819 // reference) in the arguments, then any anonymous regions in the output
1820 // have that lifetime.
1821 let implied_output_region = match explicit_self_category {
1822 Some(ty::ExplicitSelfCategory::ByReference(region, _)) => Ok(region),
1823 _ => find_implied_output_region(this.tcx(), &arg_tys, arg_pats)
1826 let output_ty = match decl.output {
1827 hir::Return(ref output) =>
1828 ty::FnConverging(convert_ty_with_lifetime_elision(this,
1829 implied_output_region,
1831 hir::DefaultReturn(..) => ty::FnConverging(this.tcx().mk_nil()),
1832 hir::NoReturn(..) => ty::FnDiverging
1838 sig: ty::Binder(ty::FnSig {
1839 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1841 variadic: decl.variadic
1843 }, explicit_self_category)
1846 fn determine_self_type<'a, 'tcx>(this: &AstConv<'tcx>,
1847 rscope: &RegionScope,
1848 self_info: SelfInfo<'a, 'tcx>)
1849 -> (Option<Ty<'tcx>>, Option<ty::ExplicitSelfCategory>)
1851 let self_ty = self_info.untransformed_self_ty;
1852 return match self_info.explicit_self.node {
1853 hir::SelfStatic => (None, Some(ty::ExplicitSelfCategory::Static)),
1854 hir::SelfValue(_) => {
1855 (Some(self_ty), Some(ty::ExplicitSelfCategory::ByValue))
1857 hir::SelfRegion(ref lifetime, mutability, _) => {
1859 opt_ast_region_to_region(this,
1861 self_info.explicit_self.span,
1863 (Some(this.tcx().mk_ref(
1864 this.tcx().mk_region(region),
1869 Some(ty::ExplicitSelfCategory::ByReference(region, mutability)))
1871 hir::SelfExplicit(ref ast_type, _) => {
1872 let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1874 // We wish to (for now) categorize an explicit self
1875 // declaration like `self: SomeType` into either `self`,
1876 // `&self`, `&mut self`, or `Box<self>`. We do this here
1877 // by some simple pattern matching. A more precise check
1878 // is done later in `check_method_self_type()`.
1883 // impl Foo for &T {
1884 // // Legal declarations:
1885 // fn method1(self: &&T); // ExplicitSelfCategory::ByReference
1886 // fn method2(self: &T); // ExplicitSelfCategory::ByValue
1887 // fn method3(self: Box<&T>); // ExplicitSelfCategory::ByBox
1889 // // Invalid cases will be caught later by `check_method_self_type`:
1890 // fn method_err1(self: &mut T); // ExplicitSelfCategory::ByReference
1894 // To do the check we just count the number of "modifiers"
1895 // on each type and compare them. If they are the same or
1896 // the impl has more, we call it "by value". Otherwise, we
1897 // look at the outermost modifier on the method decl and
1898 // call it by-ref, by-box as appropriate. For method1, for
1899 // example, the impl type has one modifier, but the method
1900 // type has two, so we end up with
1901 // ExplicitSelfCategory::ByReference.
1903 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1904 let method_modifiers = count_modifiers(explicit_type);
1906 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1907 explicit_type={:?} \
1909 self_info.untransformed_self_ty,
1914 let category = if impl_modifiers >= method_modifiers {
1915 ty::ExplicitSelfCategory::ByValue
1917 match explicit_type.sty {
1918 ty::TyRef(r, mt) => ty::ExplicitSelfCategory::ByReference(*r, mt.mutbl),
1919 ty::TyBox(_) => ty::ExplicitSelfCategory::ByBox,
1920 _ => ty::ExplicitSelfCategory::ByValue,
1924 (Some(explicit_type), Some(category))
1928 fn count_modifiers(ty: Ty) -> usize {
1930 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1931 ty::TyBox(t) => count_modifiers(t) + 1,
1937 pub fn ty_of_closure<'tcx>(
1938 this: &AstConv<'tcx>,
1939 unsafety: hir::Unsafety,
1942 expected_sig: Option<ty::FnSig<'tcx>>)
1943 -> ty::ClosureTy<'tcx>
1945 debug!("ty_of_closure(expected_sig={:?})",
1948 // new region names that appear inside of the fn decl are bound to
1949 // that function type
1950 let rb = rscope::BindingRscope::new();
1952 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1953 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1954 // no guarantee that the correct number of expected args
1956 if i < e.inputs.len() {
1962 ty_of_arg(this, &rb, a, expected_arg_ty)
1965 let expected_ret_ty = expected_sig.map(|e| e.output);
1967 let is_infer = match decl.output {
1968 hir::Return(ref output) if output.node == hir::TyInfer => true,
1969 hir::DefaultReturn(..) => true,
1973 let output_ty = match decl.output {
1974 _ if is_infer && expected_ret_ty.is_some() =>
1975 expected_ret_ty.unwrap(),
1977 ty::FnConverging(this.ty_infer(None, None, None, decl.output.span())),
1978 hir::Return(ref output) =>
1979 ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1980 hir::DefaultReturn(..) => unreachable!(),
1981 hir::NoReturn(..) => ty::FnDiverging
1984 debug!("ty_of_closure: input_tys={:?}", input_tys);
1985 debug!("ty_of_closure: output_ty={:?}", output_ty);
1990 sig: ty::Binder(ty::FnSig {inputs: input_tys,
1992 variadic: decl.variadic}),
1996 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1997 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1998 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1999 /// trait ref" and instead we just have a flat list of bounds as the existential type.
2000 fn conv_existential_bounds<'tcx>(
2001 this: &AstConv<'tcx>,
2002 rscope: &RegionScope,
2004 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2005 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2006 ast_bounds: &[hir::TyParamBound])
2007 -> ty::ExistentialBounds<'tcx>
2009 let partitioned_bounds =
2010 partition_bounds(this.tcx(), span, ast_bounds);
2012 conv_existential_bounds_from_partitioned_bounds(
2013 this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2016 fn conv_ty_poly_trait_ref<'tcx>(
2017 this: &AstConv<'tcx>,
2018 rscope: &RegionScope,
2020 ast_bounds: &[hir::TyParamBound])
2023 let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
2025 let mut projection_bounds = Vec::new();
2026 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2027 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2028 instantiate_poly_trait_ref(this,
2032 &mut projection_bounds)
2034 span_err!(this.tcx().sess, span, E0224,
2035 "at least one non-builtin trait is required for an object type");
2036 return this.tcx().types.err;
2040 conv_existential_bounds_from_partitioned_bounds(this,
2043 main_trait_bound.clone(),
2045 partitioned_bounds);
2047 make_object_type(this, span, main_trait_bound, bounds)
2050 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
2051 this: &AstConv<'tcx>,
2052 rscope: &RegionScope,
2054 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2055 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2056 partitioned_bounds: PartitionedBounds)
2057 -> ty::ExistentialBounds<'tcx>
2059 let PartitionedBounds { builtin_bounds,
2064 if !trait_bounds.is_empty() {
2065 let b = &trait_bounds[0];
2066 span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
2067 "only the builtin traits can be used as closure or object bounds");
2071 compute_object_lifetime_bound(this,
2074 principal_trait_ref,
2077 let region_bound = match region_bound {
2080 match rscope.object_lifetime_default(span) {
2083 span_err!(this.tcx().sess, span, E0228,
2084 "the lifetime bound for this object type cannot be deduced \
2085 from context; please supply an explicit bound");
2092 debug!("region_bound: {:?}", region_bound);
2094 ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2097 /// Given the bounds on an object, determines what single region bound
2098 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
2099 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
2100 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
2101 fn compute_object_lifetime_bound<'tcx>(
2102 this: &AstConv<'tcx>,
2104 explicit_region_bounds: &[&hir::Lifetime],
2105 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2106 builtin_bounds: ty::BuiltinBounds)
2107 -> Option<ty::Region> // if None, use the default
2109 let tcx = this.tcx();
2111 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2112 principal_trait_ref={:?}, builtin_bounds={:?})",
2113 explicit_region_bounds,
2114 principal_trait_ref,
2117 if explicit_region_bounds.len() > 1 {
2118 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2119 "only a single explicit lifetime bound is permitted");
2122 if !explicit_region_bounds.is_empty() {
2123 // Explicitly specified region bound. Use that.
2124 let r = explicit_region_bounds[0];
2125 return Some(ast_region_to_region(tcx, r));
2128 if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
2129 return Some(ty::ReStatic);
2132 // No explicit region bound specified. Therefore, examine trait
2133 // bounds and see if we can derive region bounds from those.
2134 let derived_region_bounds =
2135 object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2137 // If there are no derived region bounds, then report back that we
2138 // can find no region bound. The caller will use the default.
2139 if derived_region_bounds.is_empty() {
2143 // If any of the derived region bounds are 'static, that is always
2145 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2146 return Some(ty::ReStatic);
2149 // Determine whether there is exactly one unique region in the set
2150 // of derived region bounds. If so, use that. Otherwise, report an
2152 let r = derived_region_bounds[0];
2153 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2154 span_err!(tcx.sess, span, E0227,
2155 "ambiguous lifetime bound, explicit lifetime bound required");
2160 pub struct PartitionedBounds<'a> {
2161 pub builtin_bounds: ty::BuiltinBounds,
2162 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2163 pub region_bounds: Vec<&'a hir::Lifetime>,
2166 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2167 /// general trait bounds, and region bounds.
2168 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
2170 ast_bounds: &'a [hir::TyParamBound])
2171 -> PartitionedBounds<'a>
2173 let mut builtin_bounds = ty::BuiltinBounds::empty();
2174 let mut region_bounds = Vec::new();
2175 let mut trait_bounds = Vec::new();
2176 for ast_bound in ast_bounds {
2178 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2179 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2180 def::DefTrait(trait_did) => {
2181 if tcx.try_add_builtin_trait(trait_did,
2182 &mut builtin_bounds) {
2183 let segments = &b.trait_ref.path.segments;
2184 let parameters = &segments[segments.len() - 1].parameters;
2185 if !parameters.types().is_empty() {
2186 check_type_argument_count(tcx, b.trait_ref.path.span,
2187 parameters.types().len(), 0, 0);
2189 if !parameters.lifetimes().is_empty() {
2190 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2191 parameters.lifetimes().len(), 0);
2193 continue; // success
2197 // Not a trait? that's an error, but it'll get
2201 trait_bounds.push(b);
2203 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2204 hir::RegionTyParamBound(ref l) => {
2205 region_bounds.push(l);
2211 builtin_bounds: builtin_bounds,
2212 trait_bounds: trait_bounds,
2213 region_bounds: region_bounds,
2217 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
2218 bindings: &[ConvertedBinding<'tcx>])
2220 for binding in bindings.iter().take(1) {
2221 prohibit_projection(tcx, binding.span);
2225 fn check_type_argument_count(tcx: &ty::ctxt, span: Span, supplied: usize,
2226 required: usize, accepted: usize) {
2227 if supplied < required {
2228 let expected = if required < accepted {
2233 span_err!(tcx.sess, span, E0243,
2234 "wrong number of type arguments: {} {}, found {}",
2235 expected, required, supplied);
2236 } else if supplied > accepted {
2237 let expected = if required < accepted {
2242 span_err!(tcx.sess, span, E0244,
2243 "wrong number of type arguments: {} {}, found {}",
2250 fn report_lifetime_number_error(tcx: &ty::ctxt, span: Span, number: usize, expected: usize) {
2251 span_err!(tcx.sess, span, E0107,
2252 "wrong number of lifetime parameters: expected {}, found {}",
2256 // A helper struct for conveniently grouping a set of bounds which we pass to
2257 // and return from functions in multiple places.
2258 #[derive(PartialEq, Eq, Clone, Debug)]
2259 pub struct Bounds<'tcx> {
2260 pub region_bounds: Vec<ty::Region>,
2261 pub builtin_bounds: ty::BuiltinBounds,
2262 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2263 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2266 impl<'tcx> Bounds<'tcx> {
2267 pub fn predicates(&self,
2268 tcx: &ty::ctxt<'tcx>,
2270 -> Vec<ty::Predicate<'tcx>>
2272 let mut vec = Vec::new();
2274 for builtin_bound in &self.builtin_bounds {
2275 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
2276 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2277 Err(ErrorReported) => { }
2281 for ®ion_bound in &self.region_bounds {
2282 // account for the binder being introduced below; no need to shift `param_ty`
2283 // because, at present at least, it can only refer to early-bound regions
2284 let region_bound = ty::fold::shift_region(region_bound, 1);
2285 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2288 for bound_trait_ref in &self.trait_bounds {
2289 vec.push(bound_trait_ref.to_predicate());
2292 for projection in &self.projection_bounds {
2293 vec.push(projection.to_predicate());