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_val::ConstVal;
53 use rustc_const_eval::{eval_const_expr_partial, ConstEvalErr};
54 use rustc_const_eval::EvalHint::UncheckedExprHint;
55 use rustc_const_eval::ErrKind::ErroneousReferencedConstant;
56 use hir::def::{self, Def};
57 use hir::def_id::DefId;
58 use middle::resolve_lifetime as rl;
59 use rustc::ty::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
61 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
62 use rustc::ty::wf::object_region_bounds;
63 use require_c_abi_if_variadic;
64 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
65 ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
66 ElisionFailureInfo, ElidedLifetime};
67 use util::common::{ErrorReported, FN_OUTPUT_NAME};
68 use util::nodemap::FnvHashSet;
70 use rustc_const_math::ConstInt;
72 use syntax::{abi, ast};
73 use syntax::codemap::{Span, Pos};
74 use syntax::errors::DiagnosticBuilder;
75 use syntax::feature_gate::{GateIssue, emit_feature_err};
76 use syntax::parse::token::{self, keywords};
78 use rustc::hir::print as pprust;
80 use rustc_back::slice;
82 pub trait AstConv<'tcx> {
83 fn tcx<'a>(&'a self) -> &'a TyCtxt<'tcx>;
85 /// Identify the type scheme for an item with a type, like a type
86 /// alias, fn, or struct. This allows you to figure out the set of
87 /// type parameters defined on the item.
88 fn get_item_type_scheme(&self, span: Span, id: DefId)
89 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
91 /// Returns the `TraitDef` for a given trait. This allows you to
92 /// figure out the set of type parameters defined on the trait.
93 fn get_trait_def(&self, span: Span, id: DefId)
94 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
96 /// Ensure that the super-predicates for the trait with the given
97 /// id are available and also for the transitive set of
99 fn ensure_super_predicates(&self, span: Span, id: DefId)
100 -> Result<(), ErrorReported>;
102 /// Returns the set of bounds in scope for the type parameter with
104 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
105 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
107 /// Returns true if the trait with id `trait_def_id` defines an
108 /// associated type with the name `name`.
109 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
112 /// Return an (optional) substitution to convert bound type parameters that
113 /// are in scope into free ones. This function should only return Some
114 /// within a fn body.
115 /// See ParameterEnvironment::free_substs for more information.
116 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
120 /// What type should we use when a type is omitted?
122 param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
123 substs: Option<&mut Substs<'tcx>>,
124 space: Option<ParamSpace>,
125 span: Span) -> Ty<'tcx>;
127 /// Projecting an associated type from a (potentially)
128 /// higher-ranked trait reference is more complicated, because of
129 /// the possibility of late-bound regions appearing in the
130 /// associated type binding. This is not legal in function
131 /// signatures for that reason. In a function body, we can always
132 /// handle it because we can use inference variables to remove the
133 /// late-bound regions.
134 fn projected_ty_from_poly_trait_ref(&self,
136 poly_trait_ref: ty::PolyTraitRef<'tcx>,
137 item_name: ast::Name)
140 if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
141 self.projected_ty(span, trait_ref, item_name)
143 // no late-bound regions, we can just ignore the binder
144 span_err!(self.tcx().sess, span, E0212,
145 "cannot extract an associated type from a higher-ranked trait bound \
151 /// Project an associated type from a non-higher-ranked trait reference.
152 /// This is fairly straightforward and can be accommodated in any context.
153 fn projected_ty(&self,
155 _trait_ref: ty::TraitRef<'tcx>,
156 _item_name: ast::Name)
159 /// Invoked when we encounter an error from some prior pass
160 /// (e.g. resolve) that is translated into a ty-error. This is
161 /// used to help suppress derived errors typeck might otherwise
163 fn set_tainted_by_errors(&self);
166 pub fn ast_region_to_region(tcx: &TyCtxt, lifetime: &hir::Lifetime)
168 let r = match tcx.named_region_map.get(&lifetime.id) {
170 // should have been recorded by the `resolve_lifetime` pass
171 span_bug!(lifetime.span, "unresolved lifetime");
174 Some(&rl::DefStaticRegion) => {
178 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
179 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id), lifetime.name))
182 Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
183 ty::ReEarlyBound(ty::EarlyBoundRegion {
190 Some(&rl::DefFreeRegion(scope, id)) => {
191 ty::ReFree(ty::FreeRegion {
192 scope: scope.to_code_extent(&tcx.region_maps),
193 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
199 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
207 fn report_elision_failure(
208 db: &mut DiagnosticBuilder,
210 params: Vec<ElisionFailureInfo>)
212 let mut m = String::new();
213 let len = params.len();
214 let mut any_lifetimes = false;
216 for (i, info) in params.into_iter().enumerate() {
217 let ElisionFailureInfo {
218 name, lifetime_count: n, have_bound_regions
221 any_lifetimes = any_lifetimes || (n > 0);
223 let help_name = if name.is_empty() {
224 format!("argument {}", i + 1)
226 format!("`{}`", name)
229 m.push_str(&(if n == 1 {
232 format!("one of {}'s {} elided {}lifetimes", help_name, n,
233 if have_bound_regions { "free " } else { "" } )
236 if len == 2 && i == 0 {
238 } else if i + 2 == len {
240 } else if i + 1 != len {
246 fileline_help!(db, default_span,
247 "this function's return type contains a borrowed value, but \
248 there is no value for it to be borrowed from");
249 fileline_help!(db, default_span,
250 "consider giving it a 'static lifetime");
251 } else if !any_lifetimes {
252 fileline_help!(db, default_span,
253 "this function's return type contains a borrowed value with \
254 an elided lifetime, but the lifetime cannot be derived from \
256 fileline_help!(db, default_span,
257 "consider giving it an explicit bounded or 'static \
260 fileline_help!(db, default_span,
261 "this function's return type contains a borrowed value, but \
262 the signature does not say which {} it is borrowed from",
265 fileline_help!(db, default_span,
266 "this function's return type contains a borrowed value, but \
267 the signature does not say whether it is borrowed from {}",
272 pub fn opt_ast_region_to_region<'tcx>(
273 this: &AstConv<'tcx>,
274 rscope: &RegionScope,
276 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
278 let r = match *opt_lifetime {
279 Some(ref lifetime) => {
280 ast_region_to_region(this.tcx(), lifetime)
283 None => match rscope.anon_regions(default_span, 1) {
286 let mut err = struct_span_err!(this.tcx().sess, default_span, E0106,
287 "missing lifetime specifier");
288 if let Some(params) = params {
289 report_elision_failure(&mut err, default_span, params);
297 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
304 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
305 /// returns an appropriate set of substitutions for this particular reference to `I`.
306 pub fn ast_path_substs_for_ty<'tcx>(
307 this: &AstConv<'tcx>,
308 rscope: &RegionScope,
310 param_mode: PathParamMode,
311 decl_generics: &ty::Generics<'tcx>,
312 item_segment: &hir::PathSegment)
315 let tcx = this.tcx();
317 // ast_path_substs() is only called to convert paths that are
318 // known to refer to traits, types, or structs. In these cases,
319 // all type parameters defined for the item being referenced will
320 // be in the TypeSpace or SelfSpace.
322 // Note: in the case of traits, the self parameter is also
323 // defined, but we don't currently create a `type_param_def` for
324 // `Self` because it is implicit.
325 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
326 assert!(decl_generics.types.all(|d| d.space != FnSpace));
328 let (regions, types, assoc_bindings) = match item_segment.parameters {
329 hir::AngleBracketedParameters(ref data) => {
330 convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
332 hir::ParenthesizedParameters(..) => {
333 span_err!(tcx.sess, span, E0214,
334 "parenthesized parameters may only be used with a trait");
335 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
337 ty_param_defs.iter().map(|_| tcx.types.err).collect(),
342 prohibit_projections(this.tcx(), &assoc_bindings);
344 create_substs_for_ast_path(this,
353 #[derive(PartialEq, Eq)]
354 pub enum PathParamMode {
355 // Any path in a type context.
357 // The `module::Type` in `module::Type::method` in an expression.
361 fn create_region_substs<'tcx>(
362 this: &AstConv<'tcx>,
363 rscope: &RegionScope,
365 decl_generics: &ty::Generics<'tcx>,
366 regions_provided: Vec<ty::Region>)
369 let tcx = this.tcx();
371 // If the type is parameterized by this region, then replace this
372 // region with the current anon region binding (in other words,
373 // whatever & would get replaced with).
374 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
375 let supplied_num_region_params = regions_provided.len();
376 let regions = if expected_num_region_params == supplied_num_region_params {
380 rscope.anon_regions(span, expected_num_region_params);
382 if supplied_num_region_params != 0 || anon_regions.is_err() {
383 report_lifetime_number_error(tcx, span,
384 supplied_num_region_params,
385 expected_num_region_params);
389 Ok(anon_regions) => anon_regions,
390 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
393 Substs::new_type(vec![], regions)
396 /// Given the type/region arguments provided to some path (along with
397 /// an implicit Self, if this is a trait reference) returns the complete
398 /// set of substitutions. This may involve applying defaulted type parameters.
400 /// Note that the type listing given here is *exactly* what the user provided.
402 /// The `region_substs` should be the result of `create_region_substs`
403 /// -- that is, a substitution with no types but the correct number of
405 fn create_substs_for_ast_path<'tcx>(
406 this: &AstConv<'tcx>,
408 param_mode: PathParamMode,
409 decl_generics: &ty::Generics<'tcx>,
410 self_ty: Option<Ty<'tcx>>,
411 types_provided: Vec<Ty<'tcx>>,
412 region_substs: Substs<'tcx>)
415 let tcx = this.tcx();
417 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
418 types_provided={:?}, region_substs={:?})",
419 decl_generics, self_ty, types_provided,
422 assert_eq!(region_substs.regions.len(TypeSpace), decl_generics.regions.len(TypeSpace));
423 assert!(region_substs.types.is_empty());
425 // Convert the type parameters supplied by the user.
426 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
427 let formal_ty_param_count = ty_param_defs.len();
428 let required_ty_param_count = ty_param_defs.iter()
429 .take_while(|x| x.default.is_none())
432 let mut type_substs = get_type_substs_for_defs(this,
437 region_substs.clone(),
440 let supplied_ty_param_count = type_substs.len();
441 check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
442 required_ty_param_count, formal_ty_param_count);
444 if supplied_ty_param_count < required_ty_param_count {
445 while type_substs.len() < required_ty_param_count {
446 type_substs.push(tcx.types.err);
448 } else if supplied_ty_param_count > formal_ty_param_count {
449 type_substs.truncate(formal_ty_param_count);
451 assert!(type_substs.len() >= required_ty_param_count &&
452 type_substs.len() <= formal_ty_param_count);
454 let mut substs = region_substs;
455 substs.types.extend(TypeSpace, type_substs.into_iter());
459 // If no self-type is provided, it's still possible that
460 // one was declared, because this could be an object type.
463 // If a self-type is provided, one should have been
464 // "declared" (in other words, this should be a
466 assert!(decl_generics.types.get_self().is_some());
467 substs.types.push(SelfSpace, ty);
471 let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
472 for param in &ty_param_defs[actual_supplied_ty_param_count..] {
473 if let Some(default) = param.default {
474 // If we are converting an object type, then the
475 // `Self` parameter is unknown. However, some of the
476 // other type parameters may reference `Self` in their
477 // defaults. This will lead to an ICE if we are not
479 if self_ty.is_none() && default.has_self_ty() {
480 span_err!(tcx.sess, span, E0393,
481 "the type parameter `{}` must be explicitly specified \
482 in an object type because its default value `{}` references \
486 substs.types.push(TypeSpace, tcx.types.err);
488 // This is a default type parameter.
489 let default = default.subst_spanned(tcx,
492 substs.types.push(TypeSpace, default);
495 span_bug!(span, "extra parameter without default");
499 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
500 decl_generics, self_ty, substs);
505 /// Returns types_provided if it is not empty, otherwise populating the
506 /// type parameters with inference variables as appropriate.
507 fn get_type_substs_for_defs<'tcx>(this: &AstConv<'tcx>,
509 types_provided: Vec<Ty<'tcx>>,
510 param_mode: PathParamMode,
511 ty_param_defs: &[ty::TypeParameterDef<'tcx>],
512 mut substs: Substs<'tcx>,
513 self_ty: Option<Ty<'tcx>>)
516 fn default_type_parameter<'tcx>(p: &ty::TypeParameterDef<'tcx>, self_ty: Option<Ty<'tcx>>)
517 -> Option<ty::TypeParameterDef<'tcx>>
519 if let Some(ref default) = p.default {
520 if self_ty.is_none() && default.has_self_ty() {
521 // There is no suitable inference default for a type parameter
522 // that references self with no self-type provided.
530 if param_mode == PathParamMode::Optional && types_provided.is_empty() {
533 .map(|p| this.ty_infer(default_type_parameter(p, self_ty), Some(&mut substs),
534 Some(TypeSpace), span))
541 struct ConvertedBinding<'tcx> {
542 item_name: ast::Name,
547 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
548 rscope: &RegionScope,
550 decl_generics: &ty::Generics<'tcx>,
551 data: &hir::AngleBracketedParameterData)
554 Vec<ConvertedBinding<'tcx>>)
556 let regions: Vec<_> =
557 data.lifetimes.iter()
558 .map(|l| ast_region_to_region(this.tcx(), l))
562 create_region_substs(this, rscope, span, decl_generics, regions);
567 .map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
568 i, ®ion_substs, t))
571 let assoc_bindings: Vec<_> =
573 .map(|b| ConvertedBinding { item_name: b.name,
574 ty: ast_ty_to_ty(this, rscope, &b.ty),
578 (region_substs, types, assoc_bindings)
581 /// Returns the appropriate lifetime to use for any output lifetimes
582 /// (if one exists) and a vector of the (pattern, number of lifetimes)
583 /// corresponding to each input type/pattern.
584 fn find_implied_output_region<'tcx>(tcx: &TyCtxt<'tcx>,
585 input_tys: &[Ty<'tcx>],
586 input_pats: Vec<String>) -> ElidedLifetime
588 let mut lifetimes_for_params = Vec::new();
589 let mut possible_implied_output_region = None;
591 for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
592 let mut regions = FnvHashSet();
593 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
595 debug!("find_implied_output_regions: collected {:?} from {:?} \
596 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
598 if regions.len() == 1 {
599 // there's a chance that the unique lifetime of this
600 // iteration will be the appropriate lifetime for output
601 // parameters, so lets store it.
602 possible_implied_output_region = regions.iter().cloned().next();
605 lifetimes_for_params.push(ElisionFailureInfo {
607 lifetime_count: regions.len(),
608 have_bound_regions: have_bound_regions
612 if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
613 Ok(possible_implied_output_region.unwrap())
615 Err(Some(lifetimes_for_params))
619 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
620 elided_lifetime: ElidedLifetime,
624 match elided_lifetime {
625 Ok(implied_output_region) => {
626 let rb = ElidableRscope::new(implied_output_region);
627 ast_ty_to_ty(this, &rb, ty)
629 Err(param_lifetimes) => {
630 // All regions must be explicitly specified in the output
631 // if the lifetime elision rules do not apply. This saves
632 // the user from potentially-confusing errors.
633 let rb = UnelidableRscope::new(param_lifetimes);
634 ast_ty_to_ty(this, &rb, ty)
639 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
640 rscope: &RegionScope,
642 decl_generics: &ty::Generics<'tcx>,
643 data: &hir::ParenthesizedParameterData)
646 Vec<ConvertedBinding<'tcx>>)
649 create_region_substs(this, rscope, span, decl_generics, Vec::new());
651 let binding_rscope = BindingRscope::new();
654 .map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
655 0, ®ion_substs, a_t))
656 .collect::<Vec<Ty<'tcx>>>();
658 let input_params = vec![String::new(); inputs.len()];
659 let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
661 let input_ty = this.tcx().mk_tup(inputs);
663 let (output, output_span) = match data.output {
664 Some(ref output_ty) => {
665 (convert_ty_with_lifetime_elision(this,
666 implied_output_region,
671 (this.tcx().mk_nil(), data.span)
675 let output_binding = ConvertedBinding {
676 item_name: token::intern(FN_OUTPUT_NAME),
681 (region_substs, vec![input_ty], vec![output_binding])
684 pub fn instantiate_poly_trait_ref<'tcx>(
685 this: &AstConv<'tcx>,
686 rscope: &RegionScope,
687 ast_trait_ref: &hir::PolyTraitRef,
688 self_ty: Option<Ty<'tcx>>,
689 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
690 -> ty::PolyTraitRef<'tcx>
692 let trait_ref = &ast_trait_ref.trait_ref;
693 let trait_def_id = trait_def_id(this, trait_ref);
694 ast_path_to_poly_trait_ref(this,
697 PathParamMode::Explicit,
700 trait_ref.path.segments.last().unwrap(),
704 /// Instantiates the path for the given trait reference, assuming that it's
705 /// bound to a valid trait type. Returns the def_id for the defining trait.
706 /// Fails if the type is a type other than a trait type.
708 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
709 /// are disallowed. Otherwise, they are pushed onto the vector given.
710 pub fn instantiate_mono_trait_ref<'tcx>(
711 this: &AstConv<'tcx>,
712 rscope: &RegionScope,
713 trait_ref: &hir::TraitRef,
714 self_ty: Option<Ty<'tcx>>)
715 -> ty::TraitRef<'tcx>
717 let trait_def_id = trait_def_id(this, trait_ref);
718 ast_path_to_mono_trait_ref(this,
721 PathParamMode::Explicit,
724 trait_ref.path.segments.last().unwrap())
727 fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &hir::TraitRef) -> DefId {
728 let path = &trait_ref.path;
729 match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
730 Def::Trait(trait_def_id) => trait_def_id,
732 this.tcx().sess.fatal("cannot continue compilation due to previous error");
735 span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
741 fn object_path_to_poly_trait_ref<'a,'tcx>(
742 this: &AstConv<'tcx>,
743 rscope: &RegionScope,
745 param_mode: PathParamMode,
747 trait_segment: &hir::PathSegment,
748 mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
749 -> ty::PolyTraitRef<'tcx>
751 ast_path_to_poly_trait_ref(this,
761 fn ast_path_to_poly_trait_ref<'a,'tcx>(
762 this: &AstConv<'tcx>,
763 rscope: &RegionScope,
765 param_mode: PathParamMode,
767 self_ty: Option<Ty<'tcx>>,
768 trait_segment: &hir::PathSegment,
769 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
770 -> ty::PolyTraitRef<'tcx>
772 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
773 // The trait reference introduces a binding level here, so
774 // we need to shift the `rscope`. It'd be nice if we could
775 // do away with this rscope stuff and work this knowledge
776 // into resolve_lifetimes, as we do with non-omitted
777 // lifetimes. Oh well, not there yet.
778 let shifted_rscope = &ShiftedRscope::new(rscope);
780 let (substs, assoc_bindings) =
781 create_substs_for_ast_trait_ref(this,
788 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
791 let converted_bindings =
794 .filter_map(|binding| {
795 // specify type to assert that error was already reported in Err case:
796 let predicate: Result<_, ErrorReported> =
797 ast_type_binding_to_poly_projection_predicate(this,
798 poly_trait_ref.clone(),
801 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
803 poly_projections.extend(converted_bindings);
806 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
807 trait_segment, poly_projections, poly_trait_ref);
811 fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
812 rscope: &RegionScope,
814 param_mode: PathParamMode,
816 self_ty: Option<Ty<'tcx>>,
817 trait_segment: &hir::PathSegment)
818 -> ty::TraitRef<'tcx>
820 let (substs, assoc_bindings) =
821 create_substs_for_ast_trait_ref(this,
828 prohibit_projections(this.tcx(), &assoc_bindings);
829 ty::TraitRef::new(trait_def_id, substs)
832 fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
833 rscope: &RegionScope,
835 param_mode: PathParamMode,
837 self_ty: Option<Ty<'tcx>>,
838 trait_segment: &hir::PathSegment)
839 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
841 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
844 let trait_def = match this.get_trait_def(span, trait_def_id) {
845 Ok(trait_def) => trait_def,
846 Err(ErrorReported) => {
847 // No convenient way to recover from a cycle here. Just bail. Sorry!
848 this.tcx().sess.abort_if_errors();
849 bug!("ErrorReported returned, but no errors reports?")
853 let (regions, types, assoc_bindings) = match trait_segment.parameters {
854 hir::AngleBracketedParameters(ref data) => {
855 // For now, require that parenthetical notation be used
856 // only with `Fn()` etc.
857 if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
858 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
859 "unboxed_closures", span, GateIssue::Language,
861 the precise format of `Fn`-family traits' type parameters is \
862 subject to change. Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
865 convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
867 hir::ParenthesizedParameters(ref data) => {
868 // For now, require that parenthetical notation be used
869 // only with `Fn()` etc.
870 if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
871 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
872 "unboxed_closures", span, GateIssue::Language,
874 parenthetical notation is only stable when used with `Fn`-family traits");
877 convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
881 let substs = create_substs_for_ast_path(this,
889 (this.tcx().mk_substs(substs), assoc_bindings)
892 fn ast_type_binding_to_poly_projection_predicate<'tcx>(
893 this: &AstConv<'tcx>,
894 mut trait_ref: ty::PolyTraitRef<'tcx>,
895 self_ty: Option<Ty<'tcx>>,
896 binding: &ConvertedBinding<'tcx>)
897 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
899 let tcx = this.tcx();
901 // Given something like `U : SomeTrait<T=X>`, we want to produce a
902 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
903 // subtle in the event that `T` is defined in a supertrait of
904 // `SomeTrait`, because in that case we need to upcast.
906 // That is, consider this case:
909 // trait SubTrait : SuperTrait<int> { }
910 // trait SuperTrait<A> { type T; }
912 // ... B : SubTrait<T=foo> ...
915 // We want to produce `<B as SuperTrait<int>>::T == foo`.
917 // Simple case: X is defined in the current trait.
918 if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
919 return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
920 projection_ty: ty::ProjectionTy { // |
921 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
922 item_name: binding.item_name,
928 // Otherwise, we have to walk through the supertraits to find
929 // those that do. This is complicated by the fact that, for an
930 // object type, the `Self` type is not present in the
931 // substitutions (after all, it's being constructed right now),
932 // but the `supertraits` iterator really wants one. To handle
933 // this, we currently insert a dummy type and then remove it
936 let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
937 if self_ty.is_none() { // if converting for an object type
938 let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
939 assert!(dummy_substs.self_ty().is_none()); // |
940 dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
941 trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(), // <------------+
942 tcx.mk_substs(dummy_substs)));
945 this.ensure_super_predicates(binding.span, trait_ref.def_id())?;
947 let mut candidates: Vec<ty::PolyTraitRef> =
948 traits::supertraits(tcx, trait_ref.clone())
949 .filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
952 // If converting for an object type, then remove the dummy-ty from `Self` now.
954 if self_ty.is_none() {
955 for candidate in &mut candidates {
956 let mut dummy_substs = candidate.0.substs.clone();
957 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
958 dummy_substs.types.pop(SelfSpace);
959 *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
960 tcx.mk_substs(dummy_substs)));
964 let candidate = one_bound_for_assoc_type(tcx,
966 &trait_ref.to_string(),
967 &binding.item_name.as_str(),
970 Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
971 projection_ty: ty::ProjectionTy { // |
972 trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
973 item_name: binding.item_name,
979 fn ast_path_to_ty<'tcx>(
980 this: &AstConv<'tcx>,
981 rscope: &RegionScope,
983 param_mode: PathParamMode,
985 item_segment: &hir::PathSegment)
988 let tcx = this.tcx();
989 let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
990 Ok(ty::TypeScheme { generics, ty: decl_ty }) => {
993 Err(ErrorReported) => {
994 return tcx.types.err;
998 let substs = ast_path_substs_for_ty(this,
1005 // FIXME(#12938): This is a hack until we have full support for DST.
1006 if Some(did) == this.tcx().lang_items.owned_box() {
1007 assert_eq!(substs.types.len(TypeSpace), 1);
1008 return this.tcx().mk_box(*substs.types.get(TypeSpace, 0));
1011 decl_ty.subst(this.tcx(), &substs)
1014 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
1016 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
1017 rscope: &RegionScope,
1019 bounds: &[hir::TyParamBound])
1020 -> Result<TraitAndProjections<'tcx>, ErrorReported>
1023 * In a type like `Foo + Send`, we want to wait to collect the
1024 * full set of bounds before we make the object type, because we
1025 * need them to infer a region bound. (For example, if we tried
1026 * made a type from just `Foo`, then it wouldn't be enough to
1027 * infer a 'static bound, and hence the user would get an error.)
1028 * So this function is used when we're dealing with a sum type to
1029 * convert the LHS. It only accepts a type that refers to a trait
1030 * name, and reports an error otherwise.
1034 hir::TyPath(None, ref path) => {
1035 let def = match this.tcx().def_map.borrow().get(&ty.id) {
1036 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
1040 Some(Def::Trait(trait_def_id)) => {
1041 let mut projection_bounds = Vec::new();
1042 let trait_ref = object_path_to_poly_trait_ref(this,
1045 PathParamMode::Explicit,
1047 path.segments.last().unwrap(),
1048 &mut projection_bounds);
1049 Ok((trait_ref, projection_bounds))
1052 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
1058 let mut err = struct_span_err!(this.tcx().sess, ty.span, E0178,
1059 "expected a path on the left-hand side of `+`, not `{}`",
1060 pprust::ty_to_string(ty));
1061 let hi = bounds.iter().map(|x| match *x {
1062 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
1063 hir::RegionTyParamBound(ref r) => r.span.hi,
1064 }).max_by_key(|x| x.to_usize());
1065 let full_span = hi.map(|hi| Span {
1068 expn_id: ty.span.expn_id,
1070 match (&ty.node, full_span) {
1071 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1072 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1073 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1074 format!("&{}({} +{})",
1076 pprust::ty_to_string(&mut_ty.ty),
1077 pprust::bounds_to_string(bounds)));
1079 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1080 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1081 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1082 format!("&{} {}({} +{})",
1083 pprust::lifetime_to_string(lt),
1085 pprust::ty_to_string(&mut_ty.ty),
1086 pprust::bounds_to_string(bounds)));
1090 fileline_help!(&mut err, ty.span,
1091 "perhaps you forgot parentheses? (per RFC 438)");
1100 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
1101 rscope: &RegionScope,
1103 trait_ref: ty::PolyTraitRef<'tcx>,
1104 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1105 bounds: &[hir::TyParamBound])
1108 let existential_bounds = conv_existential_bounds(this,
1115 let result = make_object_type(this, span, trait_ref, existential_bounds);
1116 debug!("trait_ref_to_object_type: result={:?}",
1122 fn make_object_type<'tcx>(this: &AstConv<'tcx>,
1124 principal: ty::PolyTraitRef<'tcx>,
1125 bounds: ty::ExistentialBounds<'tcx>)
1127 let tcx = this.tcx();
1128 let object = ty::TraitTy {
1129 principal: principal,
1132 let object_trait_ref =
1133 object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1135 // ensure the super predicates and stop if we encountered an error
1136 if this.ensure_super_predicates(span, principal.def_id()).is_err() {
1137 return tcx.types.err;
1140 // check that there are no gross object safety violations,
1141 // most importantly, that the supertraits don't contain Self,
1143 let object_safety_violations =
1144 traits::astconv_object_safety_violations(tcx, principal.def_id());
1145 if !object_safety_violations.is_empty() {
1146 traits::report_object_safety_error(
1147 tcx, span, principal.def_id(), object_safety_violations)
1149 return tcx.types.err;
1152 let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1153 traits::supertraits(tcx, object_trait_ref)
1155 let trait_def = tcx.lookup_trait_def(tr.def_id());
1156 trait_def.associated_type_names
1159 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1163 for projection_bound in &object.bounds.projection_bounds {
1164 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1165 projection_bound.0.projection_ty.item_name);
1166 associated_types.remove(&pair);
1169 for (trait_def_id, name) in associated_types {
1170 span_err!(tcx.sess, span, E0191,
1171 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1173 tcx.item_path_str(trait_def_id));
1176 tcx.mk_trait(object.principal, object.bounds)
1179 fn report_ambiguous_associated_type(tcx: &TyCtxt,
1184 span_err!(tcx.sess, span, E0223,
1185 "ambiguous associated type; specify the type using the syntax \
1187 type_str, trait_str, name);
1190 // Search for a bound on a type parameter which includes the associated item
1191 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1192 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1193 // impl). This function will fail if there are no suitable bounds or there is
1195 fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
1196 ty_param_node_id: ast::NodeId,
1197 ty_param_name: ast::Name,
1198 assoc_name: ast::Name,
1200 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1202 let tcx = this.tcx();
1204 let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
1206 Err(ErrorReported) => {
1207 return Err(ErrorReported);
1211 // Ensure the super predicates and stop if we encountered an error.
1212 if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
1213 return Err(ErrorReported);
1216 // Check that there is exactly one way to find an associated type with the
1218 let suitable_bounds: Vec<_> =
1219 traits::transitive_bounds(tcx, &bounds)
1220 .filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
1223 one_bound_for_assoc_type(tcx,
1225 &ty_param_name.as_str(),
1226 &assoc_name.as_str(),
1231 // Checks that bounds contains exactly one element and reports appropriate
1232 // errors otherwise.
1233 fn one_bound_for_assoc_type<'tcx>(tcx: &TyCtxt<'tcx>,
1234 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1235 ty_param_name: &str,
1238 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1240 if bounds.is_empty() {
1241 span_err!(tcx.sess, span, E0220,
1242 "associated type `{}` not found for `{}`",
1245 return Err(ErrorReported);
1248 if bounds.len() > 1 {
1249 let mut err = struct_span_err!(tcx.sess, span, E0221,
1250 "ambiguous associated type `{}` in bounds of `{}`",
1254 for bound in &bounds {
1255 span_note!(&mut err, span,
1256 "associated type `{}` could derive from `{}`",
1263 Ok(bounds[0].clone())
1266 // Create a type from a path to an associated type.
1267 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1268 // and item_segment is the path segment for D. We return a type and a def for
1270 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1271 // parameter or Self.
1272 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1276 item_segment: &hir::PathSegment)
1279 let tcx = this.tcx();
1280 let assoc_name = item_segment.identifier.name;
1282 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1284 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1286 // Find the type of the associated item, and the trait where the associated
1287 // item is declared.
1288 let bound = match (&ty.sty, ty_path_def) {
1289 (_, Def::SelfTy(Some(trait_did), Some((impl_id, _)))) => {
1290 // `Self` in an impl of a trait - we have a concrete self type and a
1292 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1293 let trait_ref = if let Some(free_substs) = this.get_free_substs() {
1294 trait_ref.subst(tcx, free_substs)
1299 if this.ensure_super_predicates(span, trait_did).is_err() {
1300 return (tcx.types.err, ty_path_def);
1303 let candidates: Vec<ty::PolyTraitRef> =
1304 traits::supertraits(tcx, ty::Binder(trait_ref))
1305 .filter(|r| this.trait_defines_associated_type_named(r.def_id(),
1309 match one_bound_for_assoc_type(tcx,
1312 &assoc_name.as_str(),
1315 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1318 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1319 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1320 match find_bound_for_assoc_item(this,
1322 keywords::SelfType.name(),
1326 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1329 (&ty::TyParam(_), Def::TyParam(_, _, param_did, param_name)) => {
1330 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1331 match find_bound_for_assoc_item(this,
1337 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1341 report_ambiguous_associated_type(tcx,
1345 &assoc_name.as_str());
1346 return (tcx.types.err, ty_path_def);
1350 let trait_did = bound.0.def_id;
1351 let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1353 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1354 // `ty::trait_items` used below requires information generated
1355 // by type collection, which may be in progress at this point.
1356 match tcx.map.expect_item(trait_id).node {
1357 hir::ItemTrait(_, _, _, ref trait_items) => {
1358 let item = trait_items.iter()
1359 .find(|i| i.name == assoc_name)
1360 .expect("missing associated type");
1361 tcx.map.local_def_id(item.id)
1366 let trait_items = tcx.trait_items(trait_did);
1367 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1368 item.expect("missing associated type").def_id()
1371 (ty, Def::AssociatedTy(trait_did, item_did))
1374 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1375 rscope: &RegionScope,
1377 param_mode: PathParamMode,
1378 opt_self_ty: Option<Ty<'tcx>>,
1379 trait_def_id: DefId,
1380 trait_segment: &hir::PathSegment,
1381 item_segment: &hir::PathSegment)
1384 let tcx = this.tcx();
1386 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1388 let self_ty = if let Some(ty) = opt_self_ty {
1391 let path_str = tcx.item_path_str(trait_def_id);
1392 report_ambiguous_associated_type(tcx,
1396 &item_segment.identifier.name.as_str());
1397 return tcx.types.err;
1400 debug!("qpath_to_ty: self_type={:?}", self_ty);
1402 let trait_ref = ast_path_to_mono_trait_ref(this,
1410 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1412 this.projected_ty(span, trait_ref, item_segment.identifier.name)
1415 /// Convert a type supplied as value for a type argument from AST into our
1416 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1417 /// it applies the object lifetime default.
1421 /// * `this`, `rscope`: the surrounding context
1422 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1424 /// * `index`: the index of the type parameter being instantiated from the list
1425 /// (we assume it is in the `TypeSpace`)
1426 /// * `region_substs`: a partial substitution consisting of
1427 /// only the region type parameters being supplied to this type.
1428 /// * `ast_ty`: the ast representation of the type being supplied
1429 pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
1430 rscope: &RegionScope,
1431 decl_generics: &ty::Generics<'tcx>,
1433 region_substs: &Substs<'tcx>,
1437 let tcx = this.tcx();
1439 if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1440 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1441 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1442 ast_ty_to_ty(this, rscope1, ast_ty)
1444 ast_ty_to_ty(this, rscope, ast_ty)
1448 // Check the base def in a PathResolution and convert it to a Ty. If there are
1449 // associated types in the PathResolution, these will need to be separately
1451 fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1452 rscope: &RegionScope,
1454 param_mode: PathParamMode,
1456 opt_self_ty: Option<Ty<'tcx>>,
1457 base_segments: &[hir::PathSegment])
1459 let tcx = this.tcx();
1462 Def::Trait(trait_def_id) => {
1463 // N.B. this case overlaps somewhat with
1464 // TyObjectSum, see that fn for details
1465 let mut projection_bounds = Vec::new();
1467 let trait_ref = object_path_to_poly_trait_ref(this,
1472 base_segments.last().unwrap(),
1473 &mut projection_bounds);
1475 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1476 trait_ref_to_object_type(this,
1483 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) => {
1484 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1485 ast_path_to_ty(this,
1490 base_segments.last().unwrap())
1492 Def::TyParam(space, index, _, name) => {
1493 prohibit_type_params(tcx, base_segments);
1494 tcx.mk_param(space, index, name)
1496 Def::SelfTy(_, Some((_, self_ty_id))) => {
1497 // Self in impl (we know the concrete type).
1498 prohibit_type_params(tcx, base_segments);
1499 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
1500 if let Some(free_substs) = this.get_free_substs() {
1501 ty.subst(tcx, free_substs)
1506 span_bug!(span, "self type has not been fully resolved")
1509 Def::SelfTy(Some(_), None) => {
1511 prohibit_type_params(tcx, base_segments);
1514 Def::AssociatedTy(trait_did, _) => {
1515 prohibit_type_params(tcx, &base_segments[..base_segments.len()-2]);
1522 &base_segments[base_segments.len()-2],
1523 base_segments.last().unwrap())
1526 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1527 // FIXME(#22519) This part of the resolution logic should be
1528 // avoided entirely for that form, once we stop needed a Def
1529 // for `associated_path_def_to_ty`.
1530 // Fixing this will also let use resolve <Self>::Foo the same way we
1531 // resolve Self::Foo, at the moment we can't resolve the former because
1532 // we don't have the trait information around, which is just sad.
1534 assert!(base_segments.is_empty());
1536 opt_self_ty.expect("missing T in <T>::a::b::c")
1538 Def::PrimTy(prim_ty) => {
1539 prim_ty_to_ty(tcx, base_segments, prim_ty)
1542 this.set_tainted_by_errors();
1543 return this.tcx().types.err;
1546 span_err!(tcx.sess, span, E0248,
1547 "found value `{}` used as a type",
1548 tcx.item_path_str(def.def_id()));
1549 return this.tcx().types.err;
1554 // Note that both base_segments and assoc_segments may be empty, although not at
1556 pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1557 rscope: &RegionScope,
1559 param_mode: PathParamMode,
1561 opt_self_ty: Option<Ty<'tcx>>,
1562 base_segments: &[hir::PathSegment],
1563 assoc_segments: &[hir::PathSegment])
1565 let mut ty = base_def_to_ty(this,
1573 // If any associated type segments remain, attempt to resolve them.
1574 for segment in assoc_segments {
1575 if ty.sty == ty::TyError {
1578 // This is pretty bad (it will fail except for T::A and Self::A).
1579 let (a_ty, a_def) = associated_path_def_to_ty(this,
1590 /// Parses the programmer's textual representation of a type into our
1591 /// internal notion of a type.
1592 pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
1593 rscope: &RegionScope,
1597 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1600 let tcx = this.tcx();
1602 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
1603 debug!("ast_ty_to_ty: id={:?} ty={:?} (cached)", ast_ty.id, ty);
1607 let typ = match ast_ty.node {
1608 hir::TyVec(ref ty) => {
1609 tcx.mk_slice(ast_ty_to_ty(this, rscope, &ty))
1611 hir::TyObjectSum(ref ty, ref bounds) => {
1612 match ast_ty_to_trait_ref(this, rscope, &ty, bounds) {
1613 Ok((trait_ref, projection_bounds)) => {
1614 trait_ref_to_object_type(this,
1621 Err(ErrorReported) => {
1622 this.tcx().types.err
1626 hir::TyPtr(ref mt) => {
1627 tcx.mk_ptr(ty::TypeAndMut {
1628 ty: ast_ty_to_ty(this, rscope, &mt.ty),
1632 hir::TyRptr(ref region, ref mt) => {
1633 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1634 debug!("TyRef r={:?}", r);
1636 &ObjectLifetimeDefaultRscope::new(
1638 ty::ObjectLifetimeDefault::Specific(r));
1639 let t = ast_ty_to_ty(this, rscope1, &mt.ty);
1640 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1642 hir::TyTup(ref fields) => {
1643 let flds = fields.iter()
1644 .map(|t| ast_ty_to_ty(this, rscope, &t))
1648 hir::TyBareFn(ref bf) => {
1649 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1650 tcx.mk_fn_ptr(ty_of_bare_fn(this, bf.unsafety, bf.abi, &bf.decl))
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::Mod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
1662 depth: path.segments.len()
1665 span_bug!(ast_ty.span, "unbound path {:?}", ast_ty)
1667 let def = path_res.base_def;
1668 let base_ty_end = path.segments.len() - path_res.depth;
1669 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1670 ast_ty_to_ty(this, rscope, &qself.ty)
1672 let ty = finish_resolving_def_to_ty(this,
1675 PathParamMode::Explicit,
1678 &path.segments[..base_ty_end],
1679 &path.segments[base_ty_end..]);
1681 if path_res.depth != 0 && ty.sty != ty::TyError {
1682 // Write back the new resolution.
1683 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1691 hir::TyFixedLengthVec(ref ty, ref e) => {
1692 let hint = UncheckedExprHint(tcx.types.usize);
1693 match eval_const_expr_partial(tcx, &e, hint, None) {
1694 Ok(ConstVal::Integral(ConstInt::Usize(i))) => {
1695 let i = i.as_u64(tcx.sess.target.uint_type);
1696 assert_eq!(i as usize as u64, i);
1697 tcx.mk_array(ast_ty_to_ty(this, rscope, &ty), i as usize)
1700 span_err!(tcx.sess, ast_ty.span, E0249,
1701 "expected usize value for array length, got {}", val.description());
1702 this.tcx().types.err
1704 // array length errors happen before the global constant check
1705 // so we need to report the real error
1706 Err(ConstEvalErr { kind: ErroneousReferencedConstant(box r), ..}) |
1708 let mut err = struct_span_err!(tcx.sess, r.span, E0250,
1709 "array length constant evaluation error: {}",
1711 if !ast_ty.span.contains(r.span) {
1712 span_note!(&mut err, ast_ty.span, "for array length here")
1715 this.tcx().types.err
1719 hir::TyTypeof(ref _e) => {
1720 span_err!(tcx.sess, ast_ty.span, E0516,
1721 "`typeof` is a reserved keyword but unimplemented");
1725 // TyInfer also appears as the type of arguments or return
1726 // values in a ExprClosure, or as
1727 // the type of local variables. Both of these cases are
1728 // handled specially and will not descend into this routine.
1729 this.ty_infer(None, None, None, ast_ty.span)
1733 debug!("ast_ty_to_ty: id={:?} ty={:?}", ast_ty.id, typ);
1734 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
1738 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1739 rscope: &RegionScope,
1741 expected_ty: Option<Ty<'tcx>>)
1745 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1746 hir::TyInfer => this.ty_infer(None, None, None, a.ty.span),
1747 _ => ast_ty_to_ty(this, rscope, &a.ty),
1751 struct SelfInfo<'a, 'tcx> {
1752 untransformed_self_ty: Ty<'tcx>,
1753 explicit_self: &'a hir::ExplicitSelf,
1756 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1757 sig: &hir::MethodSig,
1758 untransformed_self_ty: Ty<'tcx>)
1759 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1760 let self_info = Some(SelfInfo {
1761 untransformed_self_ty: untransformed_self_ty,
1762 explicit_self: &sig.explicit_self,
1764 let (bare_fn_ty, optional_explicit_self_category) =
1765 ty_of_method_or_bare_fn(this,
1770 (bare_fn_ty, optional_explicit_self_category.unwrap())
1773 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: hir::Unsafety, abi: abi::Abi,
1774 decl: &hir::FnDecl) -> ty::BareFnTy<'tcx> {
1775 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1779 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1780 unsafety: hir::Unsafety,
1782 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1784 -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1786 debug!("ty_of_method_or_bare_fn");
1788 // New region names that appear inside of the arguments of the function
1789 // declaration are bound to that function type.
1790 let rb = rscope::BindingRscope::new();
1792 // `implied_output_region` is the region that will be assumed for any
1793 // region parameters in the return type. In accordance with the rules for
1794 // lifetime elision, we can determine it in two ways. First (determined
1795 // here), if self is by-reference, then the implied output region is the
1796 // region of the self parameter.
1797 let (self_ty, explicit_self_category) = match opt_self_info {
1798 None => (None, None),
1799 Some(self_info) => determine_self_type(this, &rb, self_info)
1802 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1803 let arg_params = if self_ty.is_some() {
1808 let arg_tys: Vec<Ty> =
1809 arg_params.iter().map(|a| ty_of_arg(this, &rb, a, None)).collect();
1810 let arg_pats: Vec<String> =
1811 arg_params.iter().map(|a| pprust::pat_to_string(&a.pat)).collect();
1813 // Second, if there was exactly one lifetime (either a substitution or a
1814 // reference) in the arguments, then any anonymous regions in the output
1815 // have that lifetime.
1816 let implied_output_region = match explicit_self_category {
1817 Some(ty::ExplicitSelfCategory::ByReference(region, _)) => Ok(region),
1818 _ => find_implied_output_region(this.tcx(), &arg_tys, arg_pats)
1821 let output_ty = match decl.output {
1822 hir::Return(ref output) =>
1823 ty::FnConverging(convert_ty_with_lifetime_elision(this,
1824 implied_output_region,
1826 hir::DefaultReturn(..) => ty::FnConverging(this.tcx().mk_nil()),
1827 hir::NoReturn(..) => ty::FnDiverging
1833 sig: ty::Binder(ty::FnSig {
1834 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1836 variadic: decl.variadic
1838 }, explicit_self_category)
1841 fn determine_self_type<'a, 'tcx>(this: &AstConv<'tcx>,
1842 rscope: &RegionScope,
1843 self_info: SelfInfo<'a, 'tcx>)
1844 -> (Option<Ty<'tcx>>, Option<ty::ExplicitSelfCategory>)
1846 let self_ty = self_info.untransformed_self_ty;
1847 return match self_info.explicit_self.node {
1848 hir::SelfStatic => (None, Some(ty::ExplicitSelfCategory::Static)),
1849 hir::SelfValue(_) => {
1850 (Some(self_ty), Some(ty::ExplicitSelfCategory::ByValue))
1852 hir::SelfRegion(ref lifetime, mutability, _) => {
1854 opt_ast_region_to_region(this,
1856 self_info.explicit_self.span,
1858 (Some(this.tcx().mk_ref(
1859 this.tcx().mk_region(region),
1864 Some(ty::ExplicitSelfCategory::ByReference(region, mutability)))
1866 hir::SelfExplicit(ref ast_type, _) => {
1867 let explicit_type = ast_ty_to_ty(this, rscope, &ast_type);
1869 // We wish to (for now) categorize an explicit self
1870 // declaration like `self: SomeType` into either `self`,
1871 // `&self`, `&mut self`, or `Box<self>`. We do this here
1872 // by some simple pattern matching. A more precise check
1873 // is done later in `check_method_self_type()`.
1878 // impl Foo for &T {
1879 // // Legal declarations:
1880 // fn method1(self: &&T); // ExplicitSelfCategory::ByReference
1881 // fn method2(self: &T); // ExplicitSelfCategory::ByValue
1882 // fn method3(self: Box<&T>); // ExplicitSelfCategory::ByBox
1884 // // Invalid cases will be caught later by `check_method_self_type`:
1885 // fn method_err1(self: &mut T); // ExplicitSelfCategory::ByReference
1889 // To do the check we just count the number of "modifiers"
1890 // on each type and compare them. If they are the same or
1891 // the impl has more, we call it "by value". Otherwise, we
1892 // look at the outermost modifier on the method decl and
1893 // call it by-ref, by-box as appropriate. For method1, for
1894 // example, the impl type has one modifier, but the method
1895 // type has two, so we end up with
1896 // ExplicitSelfCategory::ByReference.
1898 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1899 let method_modifiers = count_modifiers(explicit_type);
1901 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1902 explicit_type={:?} \
1904 self_info.untransformed_self_ty,
1909 let category = if impl_modifiers >= method_modifiers {
1910 ty::ExplicitSelfCategory::ByValue
1912 match explicit_type.sty {
1913 ty::TyRef(r, mt) => ty::ExplicitSelfCategory::ByReference(*r, mt.mutbl),
1914 ty::TyBox(_) => ty::ExplicitSelfCategory::ByBox,
1915 _ => ty::ExplicitSelfCategory::ByValue,
1919 (Some(explicit_type), Some(category))
1923 fn count_modifiers(ty: Ty) -> usize {
1925 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1926 ty::TyBox(t) => count_modifiers(t) + 1,
1932 pub fn ty_of_closure<'tcx>(
1933 this: &AstConv<'tcx>,
1934 unsafety: hir::Unsafety,
1937 expected_sig: Option<ty::FnSig<'tcx>>)
1938 -> ty::ClosureTy<'tcx>
1940 debug!("ty_of_closure(expected_sig={:?})",
1943 // new region names that appear inside of the fn decl are bound to
1944 // that function type
1945 let rb = rscope::BindingRscope::new();
1947 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1948 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1949 // no guarantee that the correct number of expected args
1951 if i < e.inputs.len() {
1957 ty_of_arg(this, &rb, a, expected_arg_ty)
1960 let expected_ret_ty = expected_sig.map(|e| e.output);
1962 let is_infer = match decl.output {
1963 hir::Return(ref output) if output.node == hir::TyInfer => true,
1964 hir::DefaultReturn(..) => true,
1968 let output_ty = match decl.output {
1969 _ if is_infer && expected_ret_ty.is_some() =>
1970 expected_ret_ty.unwrap(),
1972 ty::FnConverging(this.ty_infer(None, None, None, decl.output.span())),
1973 hir::Return(ref output) =>
1974 ty::FnConverging(ast_ty_to_ty(this, &rb, &output)),
1975 hir::DefaultReturn(..) => bug!(),
1976 hir::NoReturn(..) => ty::FnDiverging
1979 debug!("ty_of_closure: input_tys={:?}", input_tys);
1980 debug!("ty_of_closure: output_ty={:?}", output_ty);
1985 sig: ty::Binder(ty::FnSig {inputs: input_tys,
1987 variadic: decl.variadic}),
1991 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1992 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1993 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1994 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1995 fn conv_existential_bounds<'tcx>(
1996 this: &AstConv<'tcx>,
1997 rscope: &RegionScope,
1999 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2000 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2001 ast_bounds: &[hir::TyParamBound])
2002 -> ty::ExistentialBounds<'tcx>
2004 let partitioned_bounds =
2005 partition_bounds(this.tcx(), span, ast_bounds);
2007 conv_existential_bounds_from_partitioned_bounds(
2008 this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2011 fn conv_ty_poly_trait_ref<'tcx>(
2012 this: &AstConv<'tcx>,
2013 rscope: &RegionScope,
2015 ast_bounds: &[hir::TyParamBound])
2018 let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
2020 let mut projection_bounds = Vec::new();
2021 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2022 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2023 instantiate_poly_trait_ref(this,
2027 &mut projection_bounds)
2029 span_err!(this.tcx().sess, span, E0224,
2030 "at least one non-builtin trait is required for an object type");
2031 return this.tcx().types.err;
2035 conv_existential_bounds_from_partitioned_bounds(this,
2038 main_trait_bound.clone(),
2040 partitioned_bounds);
2042 make_object_type(this, span, main_trait_bound, bounds)
2045 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
2046 this: &AstConv<'tcx>,
2047 rscope: &RegionScope,
2049 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2050 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2051 partitioned_bounds: PartitionedBounds)
2052 -> ty::ExistentialBounds<'tcx>
2054 let PartitionedBounds { builtin_bounds,
2059 if !trait_bounds.is_empty() {
2060 let b = &trait_bounds[0];
2061 span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
2062 "only the builtin traits can be used as closure or object bounds");
2066 compute_object_lifetime_bound(this,
2069 principal_trait_ref,
2072 let region_bound = match region_bound {
2075 match rscope.object_lifetime_default(span) {
2078 span_err!(this.tcx().sess, span, E0228,
2079 "the lifetime bound for this object type cannot be deduced \
2080 from context; please supply an explicit bound");
2087 debug!("region_bound: {:?}", region_bound);
2089 ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2092 /// Given the bounds on an object, determines what single region bound
2093 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
2094 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
2095 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
2096 fn compute_object_lifetime_bound<'tcx>(
2097 this: &AstConv<'tcx>,
2099 explicit_region_bounds: &[&hir::Lifetime],
2100 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2101 builtin_bounds: ty::BuiltinBounds)
2102 -> Option<ty::Region> // if None, use the default
2104 let tcx = this.tcx();
2106 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2107 principal_trait_ref={:?}, builtin_bounds={:?})",
2108 explicit_region_bounds,
2109 principal_trait_ref,
2112 if explicit_region_bounds.len() > 1 {
2113 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2114 "only a single explicit lifetime bound is permitted");
2117 if !explicit_region_bounds.is_empty() {
2118 // Explicitly specified region bound. Use that.
2119 let r = explicit_region_bounds[0];
2120 return Some(ast_region_to_region(tcx, r));
2123 if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
2124 return Some(ty::ReStatic);
2127 // No explicit region bound specified. Therefore, examine trait
2128 // bounds and see if we can derive region bounds from those.
2129 let derived_region_bounds =
2130 object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2132 // If there are no derived region bounds, then report back that we
2133 // can find no region bound. The caller will use the default.
2134 if derived_region_bounds.is_empty() {
2138 // If any of the derived region bounds are 'static, that is always
2140 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2141 return Some(ty::ReStatic);
2144 // Determine whether there is exactly one unique region in the set
2145 // of derived region bounds. If so, use that. Otherwise, report an
2147 let r = derived_region_bounds[0];
2148 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2149 span_err!(tcx.sess, span, E0227,
2150 "ambiguous lifetime bound, explicit lifetime bound required");
2155 pub struct PartitionedBounds<'a> {
2156 pub builtin_bounds: ty::BuiltinBounds,
2157 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2158 pub region_bounds: Vec<&'a hir::Lifetime>,
2161 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2162 /// general trait bounds, and region bounds.
2163 pub fn partition_bounds<'a>(tcx: &TyCtxt,
2165 ast_bounds: &'a [hir::TyParamBound])
2166 -> PartitionedBounds<'a>
2168 let mut builtin_bounds = ty::BuiltinBounds::empty();
2169 let mut region_bounds = Vec::new();
2170 let mut trait_bounds = Vec::new();
2171 for ast_bound in ast_bounds {
2173 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2174 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2175 Def::Trait(trait_did) => {
2176 if tcx.try_add_builtin_trait(trait_did,
2177 &mut builtin_bounds) {
2178 let segments = &b.trait_ref.path.segments;
2179 let parameters = &segments[segments.len() - 1].parameters;
2180 if !parameters.types().is_empty() {
2181 check_type_argument_count(tcx, b.trait_ref.path.span,
2182 parameters.types().len(), 0, 0);
2184 if !parameters.lifetimes().is_empty() {
2185 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2186 parameters.lifetimes().len(), 0);
2188 continue; // success
2192 // Not a trait? that's an error, but it'll get
2196 trait_bounds.push(b);
2198 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2199 hir::RegionTyParamBound(ref l) => {
2200 region_bounds.push(l);
2206 builtin_bounds: builtin_bounds,
2207 trait_bounds: trait_bounds,
2208 region_bounds: region_bounds,
2212 fn prohibit_projections<'tcx>(tcx: &TyCtxt<'tcx>,
2213 bindings: &[ConvertedBinding<'tcx>])
2215 for binding in bindings.iter().take(1) {
2216 prohibit_projection(tcx, binding.span);
2220 fn check_type_argument_count(tcx: &TyCtxt, span: Span, supplied: usize,
2221 required: usize, accepted: usize) {
2222 if supplied < required {
2223 let expected = if required < accepted {
2228 span_err!(tcx.sess, span, E0243,
2229 "wrong number of type arguments: {} {}, found {}",
2230 expected, required, supplied);
2231 } else if supplied > accepted {
2232 let expected = if required < accepted {
2237 span_err!(tcx.sess, span, E0244,
2238 "wrong number of type arguments: {} {}, found {}",
2245 fn report_lifetime_number_error(tcx: &TyCtxt, span: Span, number: usize, expected: usize) {
2246 span_err!(tcx.sess, span, E0107,
2247 "wrong number of lifetime parameters: expected {}, found {}",
2251 // A helper struct for conveniently grouping a set of bounds which we pass to
2252 // and return from functions in multiple places.
2253 #[derive(PartialEq, Eq, Clone, Debug)]
2254 pub struct Bounds<'tcx> {
2255 pub region_bounds: Vec<ty::Region>,
2256 pub builtin_bounds: ty::BuiltinBounds,
2257 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2258 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2261 impl<'tcx> Bounds<'tcx> {
2262 pub fn predicates(&self,
2265 -> Vec<ty::Predicate<'tcx>>
2267 let mut vec = Vec::new();
2269 for builtin_bound in &self.builtin_bounds {
2270 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
2271 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2272 Err(ErrorReported) => { }
2276 for ®ion_bound in &self.region_bounds {
2277 // account for the binder being introduced below; no need to shift `param_ty`
2278 // because, at present at least, it can only refer to early-bound regions
2279 let region_bound = ty::fold::shift_region(region_bound, 1);
2280 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2283 for bound_trait_ref in &self.trait_bounds {
2284 vec.push(bound_trait_ref.to_predicate());
2287 for projection in &self.projection_bounds {
2288 vec.push(projection.to_predicate());