1 // Copyright 2012-2015 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.
15 Within the check phase of type check, we check each item one at a time
16 (bodies of function expressions are checked as part of the containing
17 function). Inference is used to supply types wherever they are
20 By far the most complex case is checking the body of a function. This
21 can be broken down into several distinct phases:
23 - gather: creates type variables to represent the type of each local
24 variable and pattern binding.
26 - main: the main pass does the lion's share of the work: it
27 determines the types of all expressions, resolves
28 methods, checks for most invalid conditions, and so forth. In
29 some cases, where a type is unknown, it may create a type or region
30 variable and use that as the type of an expression.
32 In the process of checking, various constraints will be placed on
33 these type variables through the subtyping relationships requested
34 through the `demand` module. The `infer` module is in charge
35 of resolving those constraints.
37 - regionck: after main is complete, the regionck pass goes over all
38 types looking for regions and making sure that they did not escape
39 into places they are not in scope. This may also influence the
40 final assignments of the various region variables if there is some
43 - vtable: find and records the impls to use for each trait bound that
44 appears on a type parameter.
46 - writeback: writes the final types within a function body, replacing
47 type variables with their final inferred types. These final types
48 are written into the `tcx.node_types` table, which should *never* contain
49 any reference to a type variable.
53 While type checking a function, the intermediate types for the
54 expressions, blocks, and so forth contained within the function are
55 stored in `fcx.node_types` and `fcx.item_substs`. These types
56 may contain unresolved type variables. After type checking is
57 complete, the functions in the writeback module are used to take the
58 types from this table, resolve them, and then write them into their
59 permanent home in the type context `ccx.tcx`.
61 This means that during inferencing you should use `fcx.write_ty()`
62 and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
63 nodes within the function.
65 The types of top-level items, which never contain unbound type
66 variables, are stored directly into the `tcx` tables.
68 n.b.: A type variable is not the same thing as a type parameter. A
69 type variable is rather an "instance" of a type parameter: that is,
70 given a generic function `fn foo<T>(t: T)`: while checking the
71 function `foo`, the type `ty_param(0)` refers to the type `T`, which
72 is treated in abstract. When `foo()` is called, however, `T` will be
73 substituted for a fresh type variable `N`. This variable will
74 eventually be resolved to some concrete type (which might itself be
79 pub use self::Expectation::*;
80 pub use self::compare_method::{compare_impl_method, compare_const_impl};
81 use self::TupleArgumentsFlag::*;
83 use astconv::{AstConv, ast_region_to_region, PathParamMode};
84 use dep_graph::DepNode;
85 use fmt_macros::{Parser, Piece, Position};
86 use middle::cstore::LOCAL_CRATE;
87 use hir::def::{Def, PathResolution};
88 use hir::def_id::DefId;
90 use rustc::infer::{self, InferCtxt, InferOk, TypeOrigin, TypeTrace, type_variable};
91 use rustc::ty::subst::{self, Subst, Substs, VecPerParamSpace, ParamSpace};
92 use rustc::traits::{self, ProjectionMode};
93 use rustc::ty::{GenericPredicates, TypeScheme};
94 use rustc::ty::{ParamTy, ParameterEnvironment};
95 use rustc::ty::{LvaluePreference, NoPreference, PreferMutLvalue};
96 use rustc::ty::{self, ToPolyTraitRef, Ty, TyCtxt, Visibility};
97 use rustc::ty::{MethodCall, MethodCallee};
98 use rustc::ty::adjustment;
99 use rustc::ty::fold::TypeFoldable;
100 use rustc::ty::util::{Representability, IntTypeExt};
101 use require_c_abi_if_variadic;
102 use rscope::{ElisionFailureInfo, RegionScope};
103 use session::{Session, CompileResult};
107 use util::common::{block_query, ErrorReported, indenter, loop_query};
108 use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
110 use std::cell::{Cell, Ref, RefCell};
111 use std::collections::{HashSet};
112 use std::mem::replace;
114 use syntax::abi::Abi;
117 use syntax::attr::AttrMetaMethods;
118 use syntax::codemap::{self, Spanned};
119 use syntax::parse::token::{self, InternedString, keywords};
121 use syntax::util::lev_distance::find_best_match_for_name;
122 use syntax_pos::{self, Span};
123 use errors::DiagnosticBuilder;
125 use rustc::hir::intravisit::{self, Visitor};
126 use rustc::hir::{self, PatKind};
127 use rustc::hir::print as pprust;
128 use rustc_back::slice;
129 use rustc_const_eval::eval_length;
149 /// closures defined within the function. For example:
152 /// bar(move|| { ... })
155 /// Here, the function `foo()` and the closure passed to
156 /// `bar()` will each have their own `FnCtxt`, but they will
157 /// share the inherited fields.
158 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
159 ccx: &'a CrateCtxt<'a, 'gcx>,
160 infcx: InferCtxt<'a, 'gcx, 'tcx>,
161 locals: RefCell<NodeMap<Ty<'tcx>>>,
163 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
165 // When we process a call like `c()` where `c` is a closure type,
166 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
167 // `FnOnce` closure. In that case, we defer full resolution of the
168 // call until upvar inference can kick in and make the
169 // decision. We keep these deferred resolutions grouped by the
170 // def-id of the closure, so that once we decide, we can easily go
171 // back and process them.
172 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>>>,
174 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
177 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
178 type Target = InferCtxt<'a, 'gcx, 'tcx>;
179 fn deref(&self) -> &Self::Target {
184 trait DeferredCallResolution<'gcx, 'tcx> {
185 fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>);
188 type DeferredCallResolutionHandler<'gcx, 'tcx> = Box<DeferredCallResolution<'gcx, 'tcx>+'tcx>;
190 /// When type-checking an expression, we propagate downward
191 /// whatever type hint we are able in the form of an `Expectation`.
192 #[derive(Copy, Clone, Debug)]
193 pub enum Expectation<'tcx> {
194 /// We know nothing about what type this expression should have.
197 /// This expression should have the type given (or some subtype)
198 ExpectHasType(Ty<'tcx>),
200 /// This expression will be cast to the `Ty`
201 ExpectCastableToType(Ty<'tcx>),
203 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
204 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
205 ExpectRvalueLikeUnsized(Ty<'tcx>),
208 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
209 // Disregard "castable to" expectations because they
210 // can lead us astray. Consider for example `if cond
211 // {22} else {c} as u8` -- if we propagate the
212 // "castable to u8" constraint to 22, it will pick the
213 // type 22u8, which is overly constrained (c might not
214 // be a u8). In effect, the problem is that the
215 // "castable to" expectation is not the tightest thing
216 // we can say, so we want to drop it in this case.
217 // The tightest thing we can say is "must unify with
218 // else branch". Note that in the case of a "has type"
219 // constraint, this limitation does not hold.
221 // If the expected type is just a type variable, then don't use
222 // an expected type. Otherwise, we might write parts of the type
223 // when checking the 'then' block which are incompatible with the
225 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
227 ExpectHasType(ety) => {
228 let ety = fcx.shallow_resolve(ety);
229 if !ety.is_ty_var() {
235 ExpectRvalueLikeUnsized(ety) => {
236 ExpectRvalueLikeUnsized(ety)
242 /// Provide an expectation for an rvalue expression given an *optional*
243 /// hint, which is not required for type safety (the resulting type might
244 /// be checked higher up, as is the case with `&expr` and `box expr`), but
245 /// is useful in determining the concrete type.
247 /// The primary use case is where the expected type is a fat pointer,
248 /// like `&[isize]`. For example, consider the following statement:
250 /// let x: &[isize] = &[1, 2, 3];
252 /// In this case, the expected type for the `&[1, 2, 3]` expression is
253 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
254 /// expectation `ExpectHasType([isize])`, that would be too strong --
255 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
256 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
257 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
258 /// which still is useful, because it informs integer literals and the like.
259 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
260 /// for examples of where this comes up,.
261 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
262 match fcx.tcx.struct_tail(ty).sty {
263 ty::TySlice(_) | ty::TyStr | ty::TyTrait(..) => {
264 ExpectRvalueLikeUnsized(ty)
266 _ => ExpectHasType(ty)
270 // Resolves `expected` by a single level if it is a variable. If
271 // there is no expected type or resolution is not possible (e.g.,
272 // no constraints yet present), just returns `None`.
273 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
278 ExpectCastableToType(t) => {
279 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
281 ExpectHasType(t) => {
282 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
284 ExpectRvalueLikeUnsized(t) => {
285 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
290 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
291 match self.resolve(fcx) {
292 NoExpectation => None,
293 ExpectCastableToType(ty) |
295 ExpectRvalueLikeUnsized(ty) => Some(ty),
299 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
300 match self.resolve(fcx) {
301 ExpectHasType(ty) => Some(ty),
307 #[derive(Copy, Clone)]
308 pub struct UnsafetyState {
309 pub def: ast::NodeId,
310 pub unsafety: hir::Unsafety,
311 pub unsafe_push_count: u32,
316 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
317 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
320 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
321 match self.unsafety {
322 // If this unsafe, then if the outer function was already marked as
323 // unsafe we shouldn't attribute the unsafe'ness to the block. This
324 // way the block can be warned about instead of ignoring this
325 // extraneous block (functions are never warned about).
326 hir::Unsafety::Unsafe if self.from_fn => *self,
329 let (unsafety, def, count) = match blk.rules {
330 hir::PushUnsafeBlock(..) =>
331 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
332 hir::PopUnsafeBlock(..) =>
333 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
334 hir::UnsafeBlock(..) =>
335 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
336 hir::DefaultBlock | hir::PushUnstableBlock | hir:: PopUnstableBlock =>
337 (unsafety, self.def, self.unsafe_push_count),
339 UnsafetyState{ def: def,
341 unsafe_push_count: count,
349 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
350 ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
352 body_id: ast::NodeId,
354 // This flag is set to true if, during the writeback phase, we encounter
355 // a type error in this function.
356 writeback_errors: Cell<bool>,
358 // Number of errors that had been reported when we started
359 // checking this function. On exit, if we find that *more* errors
360 // have been reported, we will skip regionck and other work that
361 // expects the types within the function to be consistent.
362 err_count_on_creation: usize,
364 ret_ty: ty::FnOutput<'tcx>,
366 ps: RefCell<UnsafetyState>,
368 inh: &'a Inherited<'a, 'gcx, 'tcx>,
371 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
372 type Target = Inherited<'a, 'gcx, 'tcx>;
373 fn deref(&self) -> &Self::Target {
378 /// Helper type of a temporary returned by ccx.inherited(...).
379 /// Necessary because we can't write the following bound:
380 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
381 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
382 ccx: &'a CrateCtxt<'a, 'gcx>,
383 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>
386 impl<'a, 'gcx, 'tcx> CrateCtxt<'a, 'gcx> {
387 pub fn inherited(&'a self, param_env: Option<ty::ParameterEnvironment<'gcx>>)
388 -> InheritedBuilder<'a, 'gcx, 'tcx> {
391 infcx: self.tcx.infer_ctxt(Some(ty::Tables::empty()),
393 ProjectionMode::AnyFinal)
398 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
399 fn enter<F, R>(&'tcx mut self, f: F) -> R
400 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
403 self.infcx.enter(|infcx| {
407 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
408 locals: RefCell::new(NodeMap()),
409 deferred_call_resolutions: RefCell::new(DefIdMap()),
410 deferred_cast_checks: RefCell::new(Vec::new()),
416 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
417 fn normalize_associated_types_in<T>(&self,
419 body_id: ast::NodeId,
422 where T : TypeFoldable<'tcx>
424 assoc::normalize_associated_types_in(self,
425 &mut self.fulfillment_cx.borrow_mut(),
433 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> }
434 struct CheckItemBodiesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> }
436 impl<'a, 'tcx> Visitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
437 fn visit_item(&mut self, i: &'tcx hir::Item) {
438 check_item_type(self.ccx, i);
439 intravisit::walk_item(self, i);
442 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
444 hir::TyFixedLengthVec(_, ref expr) => {
445 check_const_in_type(self.ccx, &expr, self.ccx.tcx.types.usize);
450 intravisit::walk_ty(self, t);
454 impl<'a, 'tcx> Visitor<'tcx> for CheckItemBodiesVisitor<'a, 'tcx> {
455 fn visit_item(&mut self, i: &'tcx hir::Item) {
456 check_item_body(self.ccx, i);
460 pub fn check_wf_new(ccx: &CrateCtxt) -> CompileResult {
461 ccx.tcx.sess.track_errors(|| {
462 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(ccx);
463 ccx.tcx.visit_all_items_in_krate(DepNode::WfCheck, &mut visit);
467 pub fn check_item_types(ccx: &CrateCtxt) -> CompileResult {
468 ccx.tcx.sess.track_errors(|| {
469 let mut visit = CheckItemTypesVisitor { ccx: ccx };
470 ccx.tcx.visit_all_items_in_krate(DepNode::TypeckItemType, &mut visit);
474 pub fn check_item_bodies(ccx: &CrateCtxt) -> CompileResult {
475 ccx.tcx.sess.track_errors(|| {
476 let mut visit = CheckItemBodiesVisitor { ccx: ccx };
477 ccx.tcx.visit_all_items_in_krate(DepNode::TypeckItemBody, &mut visit);
481 pub fn check_drop_impls(ccx: &CrateCtxt) -> CompileResult {
482 ccx.tcx.sess.track_errors(|| {
483 let _task = ccx.tcx.dep_graph.in_task(DepNode::Dropck);
484 let drop_trait = match ccx.tcx.lang_items.drop_trait() {
485 Some(id) => ccx.tcx.lookup_trait_def(id), None => { return }
487 drop_trait.for_each_impl(ccx.tcx, |drop_impl_did| {
488 let _task = ccx.tcx.dep_graph.in_task(DepNode::DropckImpl(drop_impl_did));
489 if drop_impl_did.is_local() {
490 match dropck::check_drop_impl(ccx, drop_impl_did) {
493 assert!(ccx.tcx.sess.has_errors());
501 fn check_bare_fn<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
502 decl: &'tcx hir::FnDecl,
503 body: &'tcx hir::Block,
507 param_env: ty::ParameterEnvironment<'tcx>)
509 let fn_ty = match raw_fty.sty {
510 ty::TyFnDef(_, _, f) => f,
511 _ => span_bug!(body.span, "check_bare_fn: function type expected")
514 ccx.inherited(Some(param_env)).enter(|inh| {
515 // Compute the fty from point of view of inside fn.
516 let fn_scope = inh.tcx.region_maps.call_site_extent(fn_id, body.id);
518 fn_ty.sig.subst(inh.tcx, &inh.parameter_environment.free_substs);
520 inh.tcx.liberate_late_bound_regions(fn_scope, &fn_sig);
522 inh.normalize_associated_types_in(body.span, body.id, &fn_sig);
524 let fcx = check_fn(&inh, fn_ty.unsafety, fn_id, &fn_sig, decl, fn_id, body);
526 fcx.select_all_obligations_and_apply_defaults();
527 fcx.closure_analyze_fn(body);
528 fcx.select_obligations_where_possible();
530 fcx.select_all_obligations_or_error(); // Casts can introduce new obligations.
532 fcx.regionck_fn(fn_id, fn_span, decl, body);
533 fcx.resolve_type_vars_in_fn(decl, body);
537 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
538 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
541 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
542 fn assign(&mut self, _span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
545 // infer the variable's type
546 let var_ty = self.fcx.next_ty_var();
547 self.fcx.locals.borrow_mut().insert(nid, var_ty);
551 // take type that the user specified
552 self.fcx.locals.borrow_mut().insert(nid, typ);
559 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
560 // Add explicitly-declared locals.
561 fn visit_local(&mut self, local: &'gcx hir::Local) {
562 let o_ty = match local.ty {
563 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
566 self.assign(local.span, local.id, o_ty);
567 debug!("Local variable {:?} is assigned type {}",
569 self.fcx.ty_to_string(
570 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
571 intravisit::walk_local(self, local);
574 // Add pattern bindings.
575 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
576 if let PatKind::Binding(_, ref path1, _) = p.node {
577 let var_ty = self.assign(p.span, p.id, None);
579 self.fcx.require_type_is_sized(var_ty, p.span,
580 traits::VariableType(p.id));
582 debug!("Pattern binding {} is assigned to {} with type {:?}",
584 self.fcx.ty_to_string(
585 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
588 intravisit::walk_pat(self, p);
591 fn visit_block(&mut self, b: &'gcx hir::Block) {
592 // non-obvious: the `blk` variable maps to region lb, so
593 // we have to keep this up-to-date. This
594 // is... unfortunate. It'd be nice to not need this.
595 intravisit::walk_block(self, b);
598 // Since an expr occurs as part of the type fixed size arrays we
599 // need to record the type for that node
600 fn visit_ty(&mut self, t: &'gcx hir::Ty) {
602 hir::TyFixedLengthVec(ref ty, ref count_expr) => {
604 self.fcx.check_expr_with_hint(&count_expr, self.fcx.tcx.types.usize);
606 hir::TyBareFn(ref function_declaration) => {
607 intravisit::walk_fn_decl_nopat(self, &function_declaration.decl);
608 walk_list!(self, visit_lifetime_def, &function_declaration.lifetimes);
610 _ => intravisit::walk_ty(self, t)
614 // Don't descend into the bodies of nested closures
615 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
616 _: &'gcx hir::Block, _: Span, _: ast::NodeId) { }
619 /// Helper used by check_bare_fn and check_expr_fn. Does the grungy work of checking a function
620 /// body and returns the function context used for that purpose, since in the case of a fn item
621 /// there is still a bit more to do.
624 /// * inherited: other fields inherited from the enclosing fn (if any)
625 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
626 unsafety: hir::Unsafety,
627 unsafety_id: ast::NodeId,
628 fn_sig: &ty::FnSig<'tcx>,
629 decl: &'gcx hir::FnDecl,
631 body: &'gcx hir::Block)
632 -> FnCtxt<'a, 'gcx, 'tcx>
634 let arg_tys = &fn_sig.inputs;
635 let ret_ty = fn_sig.output;
637 debug!("check_fn(arg_tys={:?}, ret_ty={:?}, fn_id={})",
642 // Create the function context. This is either derived from scratch or,
643 // in the case of function expressions, based on the outer context.
644 let fcx = FnCtxt::new(inherited, ret_ty, body.id);
645 *fcx.ps.borrow_mut() = UnsafetyState::function(unsafety, unsafety_id);
647 if let ty::FnConverging(ret_ty) = ret_ty {
648 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
651 debug!("fn-sig-map: fn_id={} fn_sig={:?}", fn_id, fn_sig);
653 inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig.clone());
656 let mut visit = GatherLocalsVisitor { fcx: &fcx, };
658 // Add formal parameters.
659 for (arg_ty, input) in arg_tys.iter().zip(&decl.inputs) {
660 // The type of the argument must be well-formed.
662 // NB -- this is now checked in wfcheck, but that
663 // currently only results in warnings, so we issue an
664 // old-style WF obligation here so that we still get the
665 // errors that we used to get.
666 fcx.register_old_wf_obligation(arg_ty, input.ty.span, traits::MiscObligation);
668 // Create type variables for each argument.
669 pat_util::pat_bindings(&input.pat, |_bm, pat_id, sp, _path| {
670 let var_ty = visit.assign(sp, pat_id, None);
671 fcx.require_type_is_sized(var_ty, sp, traits::VariableType(pat_id));
674 // Check the pattern.
675 fcx.check_pat(&input.pat, *arg_ty);
678 visit.visit_block(body);
681 fcx.check_block_with_expected(body, match ret_ty {
682 ty::FnConverging(result_type) => ExpectHasType(result_type),
683 ty::FnDiverging => NoExpectation
686 for (input, arg) in decl.inputs.iter().zip(arg_tys) {
687 fcx.write_ty(input.id, arg);
693 pub fn check_struct(ccx: &CrateCtxt, id: ast::NodeId, span: Span) {
696 check_representable(tcx, span, id, "struct");
698 if tcx.lookup_simd(ccx.tcx.map.local_def_id(id)) {
699 check_simd(tcx, span, id);
703 pub fn check_item_type<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx hir::Item) {
704 debug!("check_item_type(it.id={}, it.name={})",
706 ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(it.id)));
707 let _indenter = indenter();
709 // Consts can play a role in type-checking, so they are included here.
710 hir::ItemStatic(_, _, ref e) |
711 hir::ItemConst(_, ref e) => check_const(ccx, it.span, &e, it.id),
712 hir::ItemEnum(ref enum_definition, _) => {
713 check_enum_variants(ccx,
715 &enum_definition.variants,
718 hir::ItemFn(..) => {} // entirely within check_item_body
719 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
720 debug!("ItemImpl {} with id {}", it.name, it.id);
721 let impl_def_id = ccx.tcx.map.local_def_id(it.id);
722 match ccx.tcx.impl_trait_ref(impl_def_id) {
723 Some(impl_trait_ref) => {
724 let trait_def_id = impl_trait_ref.def_id;
726 check_impl_items_against_trait(ccx,
731 check_on_unimplemented(
733 &ccx.tcx.lookup_trait_def(trait_def_id).generics,
735 ccx.tcx.item_name(trait_def_id));
740 hir::ItemTrait(..) => {
741 let def_id = ccx.tcx.map.local_def_id(it.id);
742 let generics = &ccx.tcx.lookup_trait_def(def_id).generics;
743 check_on_unimplemented(ccx, generics, it, it.name);
745 hir::ItemStruct(..) => {
746 check_struct(ccx, it.id, it.span);
748 hir::ItemTy(_, ref generics) => {
749 let pty_ty = ccx.tcx.node_id_to_type(it.id);
750 check_bounds_are_used(ccx, &generics.ty_params, pty_ty);
752 hir::ItemForeignMod(ref m) => {
753 if m.abi == Abi::RustIntrinsic {
754 for item in &m.items {
755 intrinsic::check_intrinsic_type(ccx, item);
757 } else if m.abi == Abi::PlatformIntrinsic {
758 for item in &m.items {
759 intrinsic::check_platform_intrinsic_type(ccx, item);
762 for item in &m.items {
763 let pty = ccx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(item.id));
764 if !pty.generics.types.is_empty() {
765 let mut err = struct_span_err!(ccx.tcx.sess, item.span, E0044,
766 "foreign items may not have type parameters");
767 span_help!(&mut err, item.span,
768 "consider using specialization instead of \
773 if let hir::ForeignItemFn(ref fn_decl, _) = item.node {
774 require_c_abi_if_variadic(ccx.tcx, fn_decl, m.abi, item.span);
779 _ => {/* nothing to do */ }
783 pub fn check_item_body<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx hir::Item) {
784 debug!("check_item_body(it.id={}, it.name={})",
786 ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(it.id)));
787 let _indenter = indenter();
789 hir::ItemFn(ref decl, _, _, _, _, ref body) => {
790 let fn_pty = ccx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(it.id));
791 let param_env = ParameterEnvironment::for_item(ccx.tcx, it.id);
792 check_bare_fn(ccx, &decl, &body, it.id, it.span, fn_pty.ty, param_env);
794 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
795 debug!("ItemImpl {} with id {}", it.name, it.id);
797 let impl_pty = ccx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(it.id));
799 for impl_item in impl_items {
800 match impl_item.node {
801 hir::ImplItemKind::Const(_, ref expr) => {
802 check_const(ccx, impl_item.span, &expr, impl_item.id)
804 hir::ImplItemKind::Method(ref sig, ref body) => {
805 check_method_body(ccx, &impl_pty.generics, sig, body,
806 impl_item.id, impl_item.span);
808 hir::ImplItemKind::Type(_) => {
809 // Nothing to do here.
814 hir::ItemTrait(_, _, _, ref trait_items) => {
815 let trait_def = ccx.tcx.lookup_trait_def(ccx.tcx.map.local_def_id(it.id));
816 for trait_item in trait_items {
817 match trait_item.node {
818 hir::ConstTraitItem(_, Some(ref expr)) => {
819 check_const(ccx, trait_item.span, &expr, trait_item.id)
821 hir::MethodTraitItem(ref sig, Some(ref body)) => {
822 check_trait_fn_not_const(ccx, trait_item.span, sig.constness);
824 check_method_body(ccx, &trait_def.generics, sig, body,
825 trait_item.id, trait_item.span);
827 hir::MethodTraitItem(ref sig, None) => {
828 check_trait_fn_not_const(ccx, trait_item.span, sig.constness);
830 hir::ConstTraitItem(_, None) |
831 hir::TypeTraitItem(..) => {
837 _ => {/* nothing to do */ }
841 fn check_trait_fn_not_const<'a,'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
843 constness: hir::Constness)
846 hir::Constness::NotConst => {
849 hir::Constness::Const => {
850 struct_span_err!(ccx.tcx.sess, span, E0379, "trait fns cannot be declared const")
851 .span_label(span, &format!("trait fns cannot be const"))
857 fn check_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
858 generics: &ty::Generics,
861 if let Some(ref attr) = item.attrs.iter().find(|a| {
862 a.check_name("rustc_on_unimplemented")
864 if let Some(ref istring) = attr.value_str() {
865 let parser = Parser::new(&istring);
866 let types = &generics.types;
867 for token in parser {
869 Piece::String(_) => (), // Normal string, no need to check it
870 Piece::NextArgument(a) => match a.position {
871 // `{Self}` is allowed
872 Position::ArgumentNamed(s) if s == "Self" => (),
873 // So is `{A}` if A is a type parameter
874 Position::ArgumentNamed(s) => match types.iter().find(|t| {
879 span_err!(ccx.tcx.sess, attr.span, E0230,
880 "there is no type parameter \
885 // `{:1}` and `{}` are not to be used
886 Position::ArgumentIs(_) => {
887 span_err!(ccx.tcx.sess, attr.span, E0231,
888 "only named substitution \
889 parameters are allowed");
895 span_err!(ccx.tcx.sess, attr.span, E0232,
896 "this attribute must have a value, \
897 eg `#[rustc_on_unimplemented = \"foo\"]`")
902 /// Type checks a method body.
906 /// * `item_generics`: generics defined on the impl/trait that contains
908 /// * `self_bound`: bound for the `Self` type parameter, if any
909 /// * `method`: the method definition
910 fn check_method_body<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
911 item_generics: &ty::Generics<'tcx>,
912 sig: &'tcx hir::MethodSig,
913 body: &'tcx hir::Block,
914 id: ast::NodeId, span: Span) {
915 debug!("check_method_body(item_generics={:?}, id={})",
917 let param_env = ParameterEnvironment::for_item(ccx.tcx, id);
919 let fty = ccx.tcx.node_id_to_type(id);
920 debug!("check_method_body: fty={:?}", fty);
922 check_bare_fn(ccx, &sig.decl, body, id, span, fty, param_env);
925 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
926 impl_item: &hir::ImplItem,
929 let mut err = struct_span_err!(
930 tcx.sess, impl_item.span, E0520,
931 "item `{}` is provided by an `impl` that specializes \
932 another, but the item in the parent `impl` is not \
933 marked `default` and so it cannot be specialized.",
936 match tcx.span_of_impl(parent_impl) {
938 err.span_note(span, "parent implementation is here:");
941 err.note(&format!("parent implementation is in crate `{}`", cname));
948 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
949 trait_def: &ty::TraitDef<'tcx>,
951 impl_item: &hir::ImplItem)
953 let ancestors = trait_def.ancestors(impl_id);
955 let parent = match impl_item.node {
956 hir::ImplItemKind::Const(..) => {
957 ancestors.const_defs(tcx, impl_item.name).skip(1).next()
958 .map(|node_item| node_item.map(|parent| parent.defaultness))
960 hir::ImplItemKind::Method(..) => {
961 ancestors.fn_defs(tcx, impl_item.name).skip(1).next()
962 .map(|node_item| node_item.map(|parent| parent.defaultness))
965 hir::ImplItemKind::Type(_) => {
966 ancestors.type_defs(tcx, impl_item.name).skip(1).next()
967 .map(|node_item| node_item.map(|parent| parent.defaultness))
971 if let Some(parent) = parent {
972 if parent.item.is_final() {
973 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
979 fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
982 impl_trait_ref: &ty::TraitRef<'tcx>,
983 impl_items: &[hir::ImplItem]) {
984 // If the trait reference itself is erroneous (so the compilation is going
985 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
986 // isn't populated for such impls.
987 if impl_trait_ref.references_error() { return; }
989 // Locate trait definition and items
991 let trait_def = tcx.lookup_trait_def(impl_trait_ref.def_id);
992 let trait_items = tcx.trait_items(impl_trait_ref.def_id);
993 let mut overridden_associated_type = None;
995 // Check existing impl methods to see if they are both present in trait
996 // and compatible with trait signature
997 for impl_item in impl_items {
998 let ty_impl_item = tcx.impl_or_trait_item(tcx.map.local_def_id(impl_item.id));
999 let ty_trait_item = trait_items.iter()
1000 .find(|ac| ac.name() == ty_impl_item.name());
1002 // Check that impl definition matches trait definition
1003 if let Some(ty_trait_item) = ty_trait_item {
1004 match impl_item.node {
1005 hir::ImplItemKind::Const(..) => {
1006 let impl_const = match ty_impl_item {
1007 ty::ConstTraitItem(ref cti) => cti,
1008 _ => span_bug!(impl_item.span, "non-const impl-item for const")
1011 // Find associated const definition.
1012 if let &ty::ConstTraitItem(ref trait_const) = ty_trait_item {
1013 compare_const_impl(ccx,
1019 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1020 "item `{}` is an associated const, \
1021 which doesn't match its trait `{:?}`",
1024 err.span_label(impl_item.span, &format!("does not match trait"));
1025 // We can only get the spans from local trait definition
1026 // Same for E0324 and E0325
1027 if let Some(trait_span) = tcx.map.span_if_local(ty_trait_item.def_id()) {
1028 err.span_label(trait_span, &format!("original trait requirement"));
1033 hir::ImplItemKind::Method(ref sig, ref body) => {
1034 check_trait_fn_not_const(ccx, impl_item.span, sig.constness);
1036 let impl_method = match ty_impl_item {
1037 ty::MethodTraitItem(ref mti) => mti,
1038 _ => span_bug!(impl_item.span, "non-method impl-item for method")
1041 if let &ty::MethodTraitItem(ref trait_method) = ty_trait_item {
1042 compare_impl_method(ccx,
1049 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1050 "item `{}` is an associated method, \
1051 which doesn't match its trait `{:?}`",
1054 err.span_label(impl_item.span, &format!("does not match trait"));
1055 if let Some(trait_span) = tcx.map.span_if_local(ty_trait_item.def_id()) {
1056 err.span_label(trait_span, &format!("original trait requirement"));
1061 hir::ImplItemKind::Type(_) => {
1062 let impl_type = match ty_impl_item {
1063 ty::TypeTraitItem(ref tti) => tti,
1064 _ => span_bug!(impl_item.span, "non-type impl-item for type")
1067 if let &ty::TypeTraitItem(ref at) = ty_trait_item {
1068 if let Some(_) = at.ty {
1069 overridden_associated_type = Some(impl_item);
1072 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1073 "item `{}` is an associated type, \
1074 which doesn't match its trait `{:?}`",
1077 err.span_label(impl_item.span, &format!("does not match trait"));
1078 if let Some(trait_span) = tcx.map.span_if_local(ty_trait_item.def_id()) {
1079 err.span_label(trait_span, &format!("original trait requirement"));
1087 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1090 // Check for missing items from trait
1091 let provided_methods = tcx.provided_trait_methods(impl_trait_ref.def_id);
1092 let mut missing_items = Vec::new();
1093 let mut invalidated_items = Vec::new();
1094 let associated_type_overridden = overridden_associated_type.is_some();
1095 for trait_item in trait_items.iter() {
1100 ty::ConstTraitItem(ref associated_const) => {
1101 is_provided = associated_const.has_value;
1102 is_implemented = impl_items.iter().any(|ii| {
1104 hir::ImplItemKind::Const(..) => {
1105 ii.name == associated_const.name
1111 ty::MethodTraitItem(ref trait_method) => {
1112 is_provided = provided_methods.iter().any(|m| m.name == trait_method.name);
1113 is_implemented = trait_def.ancestors(impl_id)
1114 .fn_defs(tcx, trait_method.name)
1116 .map(|node_item| !node_item.node.is_from_trait())
1119 ty::TypeTraitItem(ref trait_assoc_ty) => {
1120 is_provided = trait_assoc_ty.ty.is_some();
1121 is_implemented = trait_def.ancestors(impl_id)
1122 .type_defs(tcx, trait_assoc_ty.name)
1124 .map(|node_item| !node_item.node.is_from_trait())
1129 if !is_implemented {
1131 missing_items.push(trait_item.name());
1132 } else if associated_type_overridden {
1133 invalidated_items.push(trait_item.name());
1138 if !missing_items.is_empty() {
1139 struct_span_err!(tcx.sess, impl_span, E0046,
1140 "not all trait items implemented, missing: `{}`",
1141 missing_items.iter()
1142 .map(|name| name.to_string())
1143 .collect::<Vec<_>>().join("`, `"))
1144 .span_label(impl_span, &format!("missing `{}` in implementation",
1145 missing_items.iter()
1146 .map(|name| name.to_string())
1147 .collect::<Vec<_>>().join("`, `"))
1151 if !invalidated_items.is_empty() {
1152 let invalidator = overridden_associated_type.unwrap();
1153 span_err!(tcx.sess, invalidator.span, E0399,
1154 "the following trait items need to be reimplemented \
1155 as `{}` was overridden: `{}`",
1157 invalidated_items.iter()
1158 .map(|name| name.to_string())
1159 .collect::<Vec<_>>().join("`, `"))
1163 /// Checks a constant appearing in a type. At the moment this is just the
1164 /// length expression in a fixed-length vector, but someday it might be
1165 /// extended to type-level numeric literals.
1166 fn check_const_in_type<'a,'tcx>(ccx: &'a CrateCtxt<'a,'tcx>,
1167 expr: &'tcx hir::Expr,
1168 expected_type: Ty<'tcx>) {
1169 ccx.inherited(None).enter(|inh| {
1170 let fcx = FnCtxt::new(&inh, ty::FnConverging(expected_type), expr.id);
1171 fcx.check_const_with_ty(expr.span, expr, expected_type);
1175 fn check_const<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>,
1179 let param_env = ParameterEnvironment::for_item(ccx.tcx, id);
1180 ccx.inherited(Some(param_env)).enter(|inh| {
1181 let rty = ccx.tcx.node_id_to_type(id);
1182 let fcx = FnCtxt::new(&inh, ty::FnConverging(rty), e.id);
1183 let declty = fcx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(id)).ty;
1184 fcx.require_type_is_sized(declty, e.span, traits::ConstSized);
1185 fcx.check_const_with_ty(sp, e, declty);
1189 /// Checks whether a type can be represented in memory. In particular, it
1190 /// identifies types that contain themselves without indirection through a
1191 /// pointer, which would mean their size is unbounded.
1192 pub fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1194 item_id: ast::NodeId,
1195 _designation: &str) -> bool {
1196 let rty = tcx.node_id_to_type(item_id);
1198 // Check that it is possible to represent this type. This call identifies
1199 // (1) types that contain themselves and (2) types that contain a different
1200 // recursive type. It is only necessary to throw an error on those that
1201 // contain themselves. For case 2, there must be an inner type that will be
1202 // caught by case 1.
1203 match rty.is_representable(tcx, sp) {
1204 Representability::SelfRecursive => {
1205 let item_def_id = tcx.map.local_def_id(item_id);
1206 tcx.recursive_type_with_infinite_size_error(item_def_id).emit();
1209 Representability::Representable | Representability::ContainsRecursive => (),
1214 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, id: ast::NodeId) {
1215 let t = tcx.node_id_to_type(id);
1217 ty::TyStruct(def, substs) => {
1218 let fields = &def.struct_variant().fields;
1219 if fields.is_empty() {
1220 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1223 let e = fields[0].ty(tcx, substs);
1224 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1225 span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous");
1229 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1230 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1232 span_err!(tcx.sess, sp, E0077,
1233 "SIMD vector element type should be machine type");
1242 #[allow(trivial_numeric_casts)]
1243 pub fn check_enum_variants<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>,
1245 vs: &'tcx [hir::Variant],
1247 let def_id = ccx.tcx.map.local_def_id(id);
1248 let hint = *ccx.tcx.lookup_repr_hints(def_id).get(0).unwrap_or(&attr::ReprAny);
1250 if hint != attr::ReprAny && vs.is_empty() {
1251 span_err!(ccx.tcx.sess, sp, E0084,
1252 "unsupported representation for zero-variant enum");
1255 ccx.inherited(None).enter(|inh| {
1256 let rty = ccx.tcx.node_id_to_type(id);
1257 let fcx = FnCtxt::new(&inh, ty::FnConverging(rty), id);
1259 let repr_type_ty = ccx.tcx.enum_repr_type(Some(&hint)).to_ty(ccx.tcx);
1261 if let Some(ref e) = v.node.disr_expr {
1262 fcx.check_const_with_ty(e.span, e, repr_type_ty);
1266 let def_id = ccx.tcx.map.local_def_id(id);
1268 let variants = &ccx.tcx.lookup_adt_def(def_id).variants;
1269 let mut disr_vals: Vec<ty::Disr> = Vec::new();
1270 for (v, variant) in vs.iter().zip(variants.iter()) {
1271 let current_disr_val = variant.disr_val;
1273 // Check for duplicate discriminant values
1274 if let Some(i) = disr_vals.iter().position(|&x| x == current_disr_val) {
1275 let variant_i_node_id = ccx.tcx.map.as_local_node_id(variants[i].did).unwrap();
1276 let variant_i = ccx.tcx.map.expect_variant(variant_i_node_id);
1277 let i_span = match variant_i.node.disr_expr {
1278 Some(ref expr) => expr.span,
1279 None => ccx.tcx.map.span(variant_i_node_id)
1281 let span = match v.node.disr_expr {
1282 Some(ref expr) => expr.span,
1285 struct_span_err!(ccx.tcx.sess, span, E0081,
1286 "discriminant value `{}` already exists", disr_vals[i])
1287 .span_label(i_span, &format!("first use of `{}`", disr_vals[i]))
1288 .span_label(span , &format!("enum already has `{}`", disr_vals[i]))
1291 disr_vals.push(current_disr_val);
1295 check_representable(ccx.tcx, sp, id, "enum");
1298 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1299 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1301 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> {
1302 &self.ast_ty_to_ty_cache
1305 fn get_item_type_scheme(&self, _: Span, id: DefId)
1306 -> Result<ty::TypeScheme<'tcx>, ErrorReported>
1308 Ok(self.tcx().lookup_item_type(id))
1311 fn get_trait_def(&self, _: Span, id: DefId)
1312 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>
1314 Ok(self.tcx().lookup_trait_def(id))
1317 fn ensure_super_predicates(&self, _: Span, _: DefId) -> Result<(), ErrorReported> {
1318 // all super predicates are ensured during collect pass
1322 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
1323 Some(&self.parameter_environment.free_substs)
1326 fn get_type_parameter_bounds(&self,
1328 node_id: ast::NodeId)
1329 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>
1331 let def = self.tcx.type_parameter_def(node_id);
1332 let r = self.parameter_environment
1335 .filter_map(|predicate| {
1337 ty::Predicate::Trait(ref data) => {
1338 if data.0.self_ty().is_param(def.space, def.index) {
1339 Some(data.to_poly_trait_ref())
1353 fn trait_defines_associated_type_named(&self,
1354 trait_def_id: DefId,
1355 assoc_name: ast::Name)
1358 let trait_def = self.tcx().lookup_trait_def(trait_def_id);
1359 trait_def.associated_type_names.contains(&assoc_name)
1363 ty_param_def: Option<ty::TypeParameterDef<'tcx>>,
1364 substs: Option<&mut subst::Substs<'tcx>>,
1365 space: Option<subst::ParamSpace>,
1366 span: Span) -> Ty<'tcx> {
1367 // Grab the default doing subsitution
1368 let default = ty_param_def.and_then(|def| {
1369 def.default.map(|ty| type_variable::Default {
1370 ty: ty.subst_spanned(self.tcx(), substs.as_ref().unwrap(), Some(span)),
1372 def_id: def.default_def_id
1376 let ty_var = self.next_ty_var_with_default(default);
1378 // Finally we add the type variable to the substs
1381 Some(substs) => { substs.types.push(space.unwrap(), ty_var); ty_var }
1385 fn projected_ty_from_poly_trait_ref(&self,
1387 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1388 item_name: ast::Name)
1391 let (trait_ref, _) =
1392 self.replace_late_bound_regions_with_fresh_var(
1394 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1397 self.normalize_associated_type(span, trait_ref, item_name)
1400 fn projected_ty(&self,
1402 trait_ref: ty::TraitRef<'tcx>,
1403 item_name: ast::Name)
1406 self.normalize_associated_type(span, trait_ref, item_name)
1409 fn set_tainted_by_errors(&self) {
1410 self.infcx.set_tainted_by_errors()
1414 impl<'a, 'gcx, 'tcx> RegionScope for FnCtxt<'a, 'gcx, 'tcx> {
1415 fn object_lifetime_default(&self, span: Span) -> Option<ty::Region> {
1416 Some(self.base_object_lifetime_default(span))
1419 fn base_object_lifetime_default(&self, span: Span) -> ty::Region {
1420 // RFC #599 specifies that object lifetime defaults take
1421 // precedence over other defaults. But within a fn body we
1422 // don't have a *default* region, rather we use inference to
1423 // find the *correct* region, which is strictly more general
1424 // (and anyway, within a fn body the right region may not even
1425 // be something the user can write explicitly, since it might
1426 // be some expression).
1427 self.next_region_var(infer::MiscVariable(span))
1430 fn anon_regions(&self, span: Span, count: usize)
1431 -> Result<Vec<ty::Region>, Option<Vec<ElisionFailureInfo>>> {
1432 Ok((0..count).map(|_| {
1433 self.next_region_var(infer::MiscVariable(span))
1438 /// Controls whether the arguments are tupled. This is used for the call
1441 /// Tupling means that all call-side arguments are packed into a tuple and
1442 /// passed as a single parameter. For example, if tupling is enabled, this
1445 /// fn f(x: (isize, isize))
1447 /// Can be called as:
1454 #[derive(Clone, Eq, PartialEq)]
1455 enum TupleArgumentsFlag {
1460 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1461 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1462 rty: ty::FnOutput<'tcx>,
1463 body_id: ast::NodeId)
1464 -> FnCtxt<'a, 'gcx, 'tcx> {
1466 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
1468 writeback_errors: Cell::new(false),
1469 err_count_on_creation: inh.tcx.sess.err_count(),
1471 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal, 0)),
1476 pub fn param_env(&self) -> &ty::ParameterEnvironment<'tcx> {
1477 &self.parameter_environment
1480 pub fn sess(&self) -> &Session {
1484 pub fn err_count_since_creation(&self) -> usize {
1485 self.tcx.sess.err_count() - self.err_count_on_creation
1488 /// Resolves type variables in `ty` if possible. Unlike the infcx
1489 /// version (resolve_type_vars_if_possible), this version will
1490 /// also select obligations if it seems useful, in an effort
1491 /// to get more type information.
1492 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1493 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1495 // No TyInfer()? Nothing needs doing.
1496 if !ty.has_infer_types() {
1497 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1501 // If `ty` is a type variable, see whether we already know what it is.
1502 ty = self.resolve_type_vars_if_possible(&ty);
1503 if !ty.has_infer_types() {
1504 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1508 // If not, try resolving pending obligations as much as
1509 // possible. This can help substantially when there are
1510 // indirect dependencies that don't seem worth tracking
1512 self.select_obligations_where_possible();
1513 ty = self.resolve_type_vars_if_possible(&ty);
1515 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1519 fn record_deferred_call_resolution(&self,
1520 closure_def_id: DefId,
1521 r: DeferredCallResolutionHandler<'gcx, 'tcx>) {
1522 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1523 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1526 fn remove_deferred_call_resolutions(&self,
1527 closure_def_id: DefId)
1528 -> Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>
1530 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1531 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(Vec::new())
1534 pub fn tag(&self) -> String {
1535 let self_ptr: *const FnCtxt = self;
1536 format!("{:?}", self_ptr)
1539 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1540 match self.locals.borrow().get(&nid) {
1543 span_err!(self.tcx.sess, span, E0513,
1544 "no type for local variable {}",
1552 pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
1553 debug!("write_ty({}, {:?}) in fcx {}",
1554 node_id, ty, self.tag());
1555 self.tables.borrow_mut().node_types.insert(node_id, ty);
1558 pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
1559 if !substs.substs.is_noop() {
1560 debug!("write_substs({}, {:?}) in fcx {}",
1565 self.tables.borrow_mut().item_substs.insert(node_id, substs);
1569 pub fn write_autoderef_adjustment(&self,
1570 node_id: ast::NodeId,
1572 self.write_adjustment(
1574 adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
1582 pub fn write_adjustment(&self,
1583 node_id: ast::NodeId,
1584 adj: adjustment::AutoAdjustment<'tcx>) {
1585 debug!("write_adjustment(node_id={}, adj={:?})", node_id, adj);
1587 if adj.is_identity() {
1591 self.tables.borrow_mut().adjustments.insert(node_id, adj);
1594 /// Basically whenever we are converting from a type scheme into
1595 /// the fn body space, we always want to normalize associated
1596 /// types as well. This function combines the two.
1597 fn instantiate_type_scheme<T>(&self,
1599 substs: &Substs<'tcx>,
1602 where T : TypeFoldable<'tcx>
1604 let value = value.subst(self.tcx, substs);
1605 let result = self.normalize_associated_types_in(span, &value);
1606 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1613 /// As `instantiate_type_scheme`, but for the bounds found in a
1614 /// generic type scheme.
1615 fn instantiate_bounds(&self,
1617 substs: &Substs<'tcx>,
1618 bounds: &ty::GenericPredicates<'tcx>)
1619 -> ty::InstantiatedPredicates<'tcx>
1621 ty::InstantiatedPredicates {
1622 predicates: self.instantiate_type_scheme(span, substs, &bounds.predicates)
1627 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1628 where T : TypeFoldable<'tcx>
1630 self.inh.normalize_associated_types_in(span, self.body_id, value)
1633 fn normalize_associated_type(&self,
1635 trait_ref: ty::TraitRef<'tcx>,
1636 item_name: ast::Name)
1639 let cause = traits::ObligationCause::new(span,
1641 traits::ObligationCauseCode::MiscObligation);
1644 .normalize_projection_type(self,
1646 trait_ref: trait_ref,
1647 item_name: item_name,
1652 /// Instantiates the type in `did` with the generics in `path` and returns
1653 /// it (registering the necessary trait obligations along the way).
1655 /// Note that this function is only intended to be used with type-paths,
1656 /// not with value-paths.
1657 pub fn instantiate_type_path(&self,
1660 node_id: ast::NodeId)
1662 debug!("instantiate_type_path(did={:?}, path={:?})", did, path);
1663 let type_scheme = self.tcx.lookup_item_type(did);
1664 let type_predicates = self.tcx.lookup_predicates(did);
1665 let substs = AstConv::ast_path_substs_for_ty(self, self,
1667 PathParamMode::Optional,
1668 &type_scheme.generics,
1669 path.segments.last().unwrap());
1670 let substs = self.tcx.mk_substs(substs);
1671 debug!("instantiate_type_path: ty={:?} substs={:?}", &type_scheme.ty, substs);
1672 let bounds = self.instantiate_bounds(path.span, substs, &type_predicates);
1673 let cause = traits::ObligationCause::new(path.span, self.body_id,
1674 traits::ItemObligation(did));
1675 self.add_obligations_for_parameters(cause, &bounds);
1677 let ty_substituted = self.instantiate_type_scheme(path.span, substs, &type_scheme.ty);
1678 self.write_ty(node_id, ty_substituted);
1679 self.write_substs(node_id, ty::ItemSubsts {
1685 pub fn write_nil(&self, node_id: ast::NodeId) {
1686 self.write_ty(node_id, self.tcx.mk_nil());
1688 pub fn write_error(&self, node_id: ast::NodeId) {
1689 self.write_ty(node_id, self.tcx.types.err);
1692 pub fn require_type_meets(&self,
1695 code: traits::ObligationCauseCode<'tcx>,
1696 bound: ty::BuiltinBound)
1698 self.register_builtin_bound(
1701 traits::ObligationCause::new(span, self.body_id, code));
1704 pub fn require_type_is_sized(&self,
1707 code: traits::ObligationCauseCode<'tcx>)
1709 self.require_type_meets(ty, span, code, ty::BoundSized);
1712 pub fn require_expr_have_sized_type(&self,
1714 code: traits::ObligationCauseCode<'tcx>)
1716 self.require_type_is_sized(self.expr_ty(expr), expr.span, code);
1719 pub fn register_builtin_bound(&self,
1721 builtin_bound: ty::BuiltinBound,
1722 cause: traits::ObligationCause<'tcx>)
1724 self.fulfillment_cx.borrow_mut()
1725 .register_builtin_bound(self, ty, builtin_bound, cause);
1728 pub fn register_predicate(&self,
1729 obligation: traits::PredicateObligation<'tcx>)
1731 debug!("register_predicate({:?})",
1735 .register_predicate_obligation(self, obligation);
1738 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
1739 let t = AstConv::ast_ty_to_ty(self, self, ast_t);
1740 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1744 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1745 match self.tables.borrow().node_types.get(&ex.id) {
1748 bug!("no type for expr in fcx {}", self.tag());
1753 /// Apply `adjustment` to the type of `expr`
1754 pub fn adjust_expr_ty(&self,
1756 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1759 let raw_ty = self.expr_ty(expr);
1760 let raw_ty = self.shallow_resolve(raw_ty);
1761 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1762 raw_ty.adjust(self.tcx, expr.span, expr.id, adjustment, |method_call| {
1763 self.tables.borrow().method_map.get(&method_call)
1764 .map(|method| resolve_ty(method.ty))
1768 pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
1769 match self.tables.borrow().node_types.get(&id) {
1771 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1773 bug!("no type for node {}: {} in fcx {}",
1774 id, self.tcx.map.node_to_string(id),
1780 pub fn item_substs(&self) -> Ref<NodeMap<ty::ItemSubsts<'tcx>>> {
1781 // NOTE: @jroesch this is hack that appears to be fixed on nightly, will monitor if
1782 // it changes when we upgrade the snapshot compiler
1783 fn project_item_susbts<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1784 -> &'a NodeMap<ty::ItemSubsts<'tcx>> {
1788 Ref::map(self.tables.borrow(), project_item_susbts)
1791 pub fn opt_node_ty_substs<F>(&self,
1794 F: FnOnce(&ty::ItemSubsts<'tcx>),
1796 match self.tables.borrow().item_substs.get(&id) {
1802 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1803 /// outlive the region `r`.
1804 pub fn register_region_obligation(&self,
1807 cause: traits::ObligationCause<'tcx>)
1809 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
1810 fulfillment_cx.register_region_obligation(ty, region, cause);
1813 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1814 /// outlive the region `r`.
1815 pub fn register_wf_obligation(&self,
1818 code: traits::ObligationCauseCode<'tcx>)
1820 // WF obligations never themselves fail, so no real need to give a detailed cause:
1821 let cause = traits::ObligationCause::new(span, self.body_id, code);
1822 self.register_predicate(traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
1825 pub fn register_old_wf_obligation(&self,
1828 code: traits::ObligationCauseCode<'tcx>)
1830 // Registers an "old-style" WF obligation that uses the
1831 // implicator code. This is basically a buggy version of
1832 // `register_wf_obligation` that is being kept around
1833 // temporarily just to help with phasing in the newer rules.
1835 // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
1836 let cause = traits::ObligationCause::new(span, self.body_id, code);
1837 self.register_region_obligation(ty, ty::ReEmpty, cause);
1840 /// Registers obligations that all types appearing in `substs` are well-formed.
1841 pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
1843 for &ty in &substs.types {
1844 self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
1848 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
1849 /// type/region parameter was instantiated (`substs`), creates and registers suitable
1850 /// trait/region obligations.
1852 /// For example, if there is a function:
1855 /// fn foo<'a,T:'a>(...)
1858 /// and a reference:
1864 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
1865 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
1866 pub fn add_obligations_for_parameters(&self,
1867 cause: traits::ObligationCause<'tcx>,
1868 predicates: &ty::InstantiatedPredicates<'tcx>)
1870 assert!(!predicates.has_escaping_regions());
1872 debug!("add_obligations_for_parameters(predicates={:?})",
1875 for obligation in traits::predicates_for_generics(cause, predicates) {
1876 self.register_predicate(obligation);
1880 // FIXME(arielb1): use this instead of field.ty everywhere
1881 // Only for fields! Returns <none> for methods>
1882 // Indifferent to privacy flags
1883 pub fn field_ty(&self,
1885 field: ty::FieldDef<'tcx>,
1886 substs: &Substs<'tcx>)
1889 self.normalize_associated_types_in(span,
1890 &field.ty(self.tcx, substs))
1893 fn check_casts(&self) {
1894 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1895 for cast in deferred_cast_checks.drain(..) {
1900 /// Apply "fallbacks" to some types
1901 /// ! gets replaced with (), unconstrained ints with i32, and unconstrained floats with f64.
1902 fn default_type_parameters(&self) {
1903 use rustc::ty::error::UnconstrainedNumeric::Neither;
1904 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
1906 // Defaulting inference variables becomes very dubious if we have
1907 // encountered type-checking errors. Therefore, if we think we saw
1908 // some errors in this function, just resolve all uninstanted type
1909 // varibles to TyError.
1910 if self.is_tainted_by_errors() {
1911 for ty in &self.unsolved_variables() {
1912 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
1913 debug!("default_type_parameters: defaulting `{:?}` to error", ty);
1914 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
1920 for ty in &self.unsolved_variables() {
1921 let resolved = self.resolve_type_vars_if_possible(ty);
1922 if self.type_var_diverges(resolved) {
1923 debug!("default_type_parameters: defaulting `{:?}` to `()` because it diverges",
1925 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.mk_nil());
1927 match self.type_is_unconstrained_numeric(resolved) {
1928 UnconstrainedInt => {
1929 debug!("default_type_parameters: defaulting `{:?}` to `i32`",
1931 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
1933 UnconstrainedFloat => {
1934 debug!("default_type_parameters: defaulting `{:?}` to `f32`",
1936 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
1944 fn select_all_obligations_and_apply_defaults(&self) {
1945 if self.tcx.sess.features.borrow().default_type_parameter_fallback {
1946 self.new_select_all_obligations_and_apply_defaults();
1948 self.old_select_all_obligations_and_apply_defaults();
1952 // Implements old type inference fallback algorithm
1953 fn old_select_all_obligations_and_apply_defaults(&self) {
1954 self.select_obligations_where_possible();
1955 self.default_type_parameters();
1956 self.select_obligations_where_possible();
1959 fn new_select_all_obligations_and_apply_defaults(&self) {
1960 use rustc::ty::error::UnconstrainedNumeric::Neither;
1961 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
1963 // For the time being this errs on the side of being memory wasteful but provides better
1965 // let type_variables = self.type_variables.clone();
1967 // There is a possibility that this algorithm will have to run an arbitrary number of times
1968 // to terminate so we bound it by the compiler's recursion limit.
1969 for _ in 0..self.tcx.sess.recursion_limit.get() {
1970 // First we try to solve all obligations, it is possible that the last iteration
1971 // has made it possible to make more progress.
1972 self.select_obligations_where_possible();
1974 let mut conflicts = Vec::new();
1976 // Collect all unsolved type, integral and floating point variables.
1977 let unsolved_variables = self.unsolved_variables();
1979 // We must collect the defaults *before* we do any unification. Because we have
1980 // directly attached defaults to the type variables any unification that occurs
1981 // will erase defaults causing conflicting defaults to be completely ignored.
1982 let default_map: FnvHashMap<_, _> =
1985 .filter_map(|t| self.default(t).map(|d| (t, d)))
1988 let mut unbound_tyvars = HashSet::new();
1990 debug!("select_all_obligations_and_apply_defaults: defaults={:?}", default_map);
1992 // We loop over the unsolved variables, resolving them and if they are
1993 // and unconstrainted numeric type we add them to the set of unbound
1994 // variables. We do this so we only apply literal fallback to type
1995 // variables without defaults.
1996 for ty in &unsolved_variables {
1997 let resolved = self.resolve_type_vars_if_possible(ty);
1998 if self.type_var_diverges(resolved) {
1999 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.mk_nil());
2001 match self.type_is_unconstrained_numeric(resolved) {
2002 UnconstrainedInt | UnconstrainedFloat => {
2003 unbound_tyvars.insert(resolved);
2010 // We now remove any numeric types that also have defaults, and instead insert
2011 // the type variable with a defined fallback.
2012 for ty in &unsolved_variables {
2013 if let Some(_default) = default_map.get(ty) {
2014 let resolved = self.resolve_type_vars_if_possible(ty);
2016 debug!("select_all_obligations_and_apply_defaults: \
2017 ty: {:?} with default: {:?}",
2020 match resolved.sty {
2021 ty::TyInfer(ty::TyVar(_)) => {
2022 unbound_tyvars.insert(ty);
2025 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) => {
2026 unbound_tyvars.insert(ty);
2027 if unbound_tyvars.contains(resolved) {
2028 unbound_tyvars.remove(resolved);
2037 // If there are no more fallbacks to apply at this point we have applied all possible
2038 // defaults and type inference will proceed as normal.
2039 if unbound_tyvars.is_empty() {
2043 // Finally we go through each of the unbound type variables and unify them with
2044 // the proper fallback, reporting a conflicting default error if any of the
2045 // unifications fail. We know it must be a conflicting default because the
2046 // variable would only be in `unbound_tyvars` and have a concrete value if
2047 // it had been solved by previously applying a default.
2049 // We wrap this in a transaction for error reporting, if we detect a conflict
2050 // we will rollback the inference context to its prior state so we can probe
2051 // for conflicts and correctly report them.
2054 let _ = self.commit_if_ok(|_: &infer::CombinedSnapshot| {
2055 for ty in &unbound_tyvars {
2056 if self.type_var_diverges(ty) {
2057 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.mk_nil());
2059 match self.type_is_unconstrained_numeric(ty) {
2060 UnconstrainedInt => {
2061 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
2063 UnconstrainedFloat => {
2064 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
2067 if let Some(default) = default_map.get(ty) {
2068 let default = default.clone();
2069 match self.eq_types(false,
2070 TypeOrigin::Misc(default.origin_span),
2072 Ok(InferOk { obligations, .. }) => {
2073 // FIXME(#32730) propagate obligations
2074 assert!(obligations.is_empty())
2077 conflicts.push((*ty, default));
2086 // If there are conflicts we rollback, otherwise commit
2087 if conflicts.len() > 0 {
2094 if conflicts.len() > 0 {
2095 // Loop through each conflicting default, figuring out the default that caused
2096 // a unification failure and then report an error for each.
2097 for (conflict, default) in conflicts {
2098 let conflicting_default =
2099 self.find_conflicting_default(&unbound_tyvars, &default_map, conflict)
2100 .unwrap_or(type_variable::Default {
2101 ty: self.next_ty_var(),
2102 origin_span: syntax_pos::DUMMY_SP,
2103 def_id: self.tcx.map.local_def_id(0) // what do I put here?
2106 // This is to ensure that we elimnate any non-determinism from the error
2107 // reporting by fixing an order, it doesn't matter what order we choose
2108 // just that it is consistent.
2109 let (first_default, second_default) =
2110 if default.def_id < conflicting_default.def_id {
2111 (default, conflicting_default)
2113 (conflicting_default, default)
2117 self.report_conflicting_default_types(
2118 first_default.origin_span,
2125 self.select_obligations_where_possible();
2128 // For use in error handling related to default type parameter fallback. We explicitly
2129 // apply the default that caused conflict first to a local version of the type variable
2130 // table then apply defaults until we find a conflict. That default must be the one
2131 // that caused conflict earlier.
2132 fn find_conflicting_default(&self,
2133 unbound_vars: &HashSet<Ty<'tcx>>,
2134 default_map: &FnvHashMap<&Ty<'tcx>, type_variable::Default<'tcx>>,
2136 -> Option<type_variable::Default<'tcx>> {
2137 use rustc::ty::error::UnconstrainedNumeric::Neither;
2138 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
2140 // Ensure that we apply the conflicting default first
2141 let mut unbound_tyvars = Vec::with_capacity(unbound_vars.len() + 1);
2142 unbound_tyvars.push(conflict);
2143 unbound_tyvars.extend(unbound_vars.iter());
2145 let mut result = None;
2146 // We run the same code as above applying defaults in order, this time when
2147 // we find the conflict we just return it for error reporting above.
2149 // We also run this inside snapshot that never commits so we can do error
2150 // reporting for more then one conflict.
2151 for ty in &unbound_tyvars {
2152 if self.type_var_diverges(ty) {
2153 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.mk_nil());
2155 match self.type_is_unconstrained_numeric(ty) {
2156 UnconstrainedInt => {
2157 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
2159 UnconstrainedFloat => {
2160 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
2163 if let Some(default) = default_map.get(ty) {
2164 let default = default.clone();
2165 match self.eq_types(false,
2166 TypeOrigin::Misc(default.origin_span),
2168 // FIXME(#32730) propagate obligations
2169 Ok(InferOk { obligations, .. }) => assert!(obligations.is_empty()),
2171 result = Some(default);
2183 fn select_all_obligations_or_error(&self) {
2184 debug!("select_all_obligations_or_error");
2186 // upvar inference should have ensured that all deferred call
2187 // resolutions are handled by now.
2188 assert!(self.deferred_call_resolutions.borrow().is_empty());
2190 self.select_all_obligations_and_apply_defaults();
2192 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2193 match fulfillment_cx.select_all_or_error(self) {
2195 Err(errors) => { self.report_fulfillment_errors(&errors); }
2198 if let Err(ref errors) = fulfillment_cx.select_rfc1592_obligations(self) {
2199 self.report_fulfillment_errors_as_warnings(errors, self.body_id);
2203 /// Select as many obligations as we can at present.
2204 fn select_obligations_where_possible(&self) {
2205 match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
2207 Err(errors) => { self.report_fulfillment_errors(&errors); }
2211 /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2212 /// returns a type of `&T`, but the actual type we assign to the
2213 /// *expression* is `T`. So this function just peels off the return
2214 /// type by one layer to yield `T`.
2215 fn make_overloaded_lvalue_return_type(&self,
2216 method: MethodCallee<'tcx>)
2217 -> ty::TypeAndMut<'tcx>
2219 // extract method return type, which will be &T;
2220 // all LB regions should have been instantiated during method lookup
2221 let ret_ty = method.ty.fn_ret();
2222 let ret_ty = self.tcx.no_late_bound_regions(&ret_ty).unwrap().unwrap();
2224 // method returns &T, but the type as visible to user is T, so deref
2225 ret_ty.builtin_deref(true, NoPreference).unwrap()
2228 fn lookup_indexing(&self,
2230 base_expr: &'gcx hir::Expr,
2233 lvalue_pref: LvaluePreference)
2234 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2236 // FIXME(#18741) -- this is almost but not quite the same as the
2237 // autoderef that normal method probing does. They could likely be
2240 let mut autoderef = self.autoderef(base_expr.span, base_ty);
2242 while let Some((adj_ty, autoderefs)) = autoderef.next() {
2243 if let Some(final_mt) = self.try_index_step(
2244 MethodCall::expr(expr.id),
2245 expr, base_expr, adj_ty, autoderefs,
2246 false, lvalue_pref, idx_ty)
2248 autoderef.finalize(lvalue_pref, Some(base_expr));
2249 return Some(final_mt);
2252 if let ty::TyArray(element_ty, _) = adj_ty.sty {
2253 autoderef.finalize(lvalue_pref, Some(base_expr));
2254 let adjusted_ty = self.tcx.mk_slice(element_ty);
2255 return self.try_index_step(
2256 MethodCall::expr(expr.id), expr, base_expr,
2257 adjusted_ty, autoderefs, true, lvalue_pref, idx_ty);
2260 autoderef.unambiguous_final_ty();
2264 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2265 /// (and otherwise adjust) `base_expr`, looking for a type which either
2266 /// supports builtin indexing or overloaded indexing.
2267 /// This loop implements one step in that search; the autoderef loop
2268 /// is implemented by `lookup_indexing`.
2269 fn try_index_step(&self,
2270 method_call: MethodCall,
2272 base_expr: &'gcx hir::Expr,
2273 adjusted_ty: Ty<'tcx>,
2276 lvalue_pref: LvaluePreference,
2278 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2281 debug!("try_index_step(expr={:?}, base_expr.id={:?}, adjusted_ty={:?}, \
2282 autoderefs={}, unsize={}, index_ty={:?})",
2290 let input_ty = self.next_ty_var();
2292 // First, try built-in indexing.
2293 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2294 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2295 debug!("try_index_step: success, using built-in indexing");
2296 // If we had `[T; N]`, we should've caught it before unsizing to `[T]`.
2298 self.write_autoderef_adjustment(base_expr.id, autoderefs);
2299 return Some((tcx.types.usize, ty));
2304 // Try `IndexMut` first, if preferred.
2305 let method = match (lvalue_pref, tcx.lang_items.index_mut_trait()) {
2306 (PreferMutLvalue, Some(trait_did)) => {
2307 self.lookup_method_in_trait_adjusted(expr.span,
2309 token::intern("index_mut"),
2314 Some(vec![input_ty]))
2319 // Otherwise, fall back to `Index`.
2320 let method = match (method, tcx.lang_items.index_trait()) {
2321 (None, Some(trait_did)) => {
2322 self.lookup_method_in_trait_adjusted(expr.span,
2324 token::intern("index"),
2329 Some(vec![input_ty]))
2331 (method, _) => method,
2334 // If some lookup succeeds, write callee into table and extract index/element
2335 // type from the method signature.
2336 // If some lookup succeeded, install method in table
2337 method.map(|method| {
2338 debug!("try_index_step: success, using overloaded indexing");
2339 self.tables.borrow_mut().method_map.insert(method_call, method);
2340 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2344 fn check_method_argument_types(&self,
2346 method_fn_ty: Ty<'tcx>,
2347 callee_expr: &'gcx hir::Expr,
2348 args_no_rcvr: &'gcx [P<hir::Expr>],
2349 tuple_arguments: TupleArgumentsFlag,
2350 expected: Expectation<'tcx>)
2351 -> ty::FnOutput<'tcx> {
2352 if method_fn_ty.references_error() {
2353 let err_inputs = self.err_args(args_no_rcvr.len());
2355 let err_inputs = match tuple_arguments {
2356 DontTupleArguments => err_inputs,
2357 TupleArguments => vec![self.tcx.mk_tup(err_inputs)],
2360 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2361 false, tuple_arguments);
2362 ty::FnConverging(self.tcx.types.err)
2364 match method_fn_ty.sty {
2365 ty::TyFnDef(_, _, ref fty) => {
2366 // HACK(eddyb) ignore self in the definition (see above).
2367 let expected_arg_tys = self.expected_types_for_fn_args(sp, expected,
2369 &fty.sig.0.inputs[1..]);
2370 self.check_argument_types(sp, &fty.sig.0.inputs[1..], &expected_arg_tys[..],
2371 args_no_rcvr, fty.sig.0.variadic, tuple_arguments);
2375 span_bug!(callee_expr.span, "method without bare fn type");
2381 /// Generic function that factors out common logic from function calls,
2382 /// method calls and overloaded operators.
2383 fn check_argument_types(&self,
2385 fn_inputs: &[Ty<'tcx>],
2386 expected_arg_tys: &[Ty<'tcx>],
2387 args: &'gcx [P<hir::Expr>],
2389 tuple_arguments: TupleArgumentsFlag) {
2392 // Grab the argument types, supplying fresh type variables
2393 // if the wrong number of arguments were supplied
2394 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2400 // All the input types from the fn signature must outlive the call
2401 // so as to validate implied bounds.
2402 for &fn_input_ty in fn_inputs {
2403 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2406 let mut expected_arg_tys = expected_arg_tys;
2407 let expected_arg_count = fn_inputs.len();
2409 fn parameter_count_error<'tcx>(sess: &Session, sp: Span, fn_inputs: &[Ty<'tcx>],
2410 expected_count: usize, arg_count: usize, error_code: &str,
2412 let mut err = sess.struct_span_err_with_code(sp,
2413 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2414 if variadic {"at least "} else {""},
2416 if expected_count == 1 {""} else {"s"},
2418 if arg_count == 1 {" was"} else {"s were"}),
2421 err.span_label(sp, &format!("expected {}{} parameter{}",
2422 if variadic {"at least "} else {""},
2424 if expected_count == 1 {""} else {"s"}));
2426 let input_types = fn_inputs.iter().map(|i| format!("{:?}", i)).collect::<Vec<String>>();
2427 if input_types.len() > 0 {
2428 err.note(&format!("the following parameter type{} expected: {}",
2429 if expected_count == 1 {" was"} else {"s were"},
2430 input_types.join(", ")));
2435 let formal_tys = if tuple_arguments == TupleArguments {
2436 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2437 match tuple_type.sty {
2438 ty::TyTuple(arg_types) if arg_types.len() != args.len() => {
2439 parameter_count_error(tcx.sess, sp, fn_inputs, arg_types.len(), args.len(),
2441 expected_arg_tys = &[];
2442 self.err_args(args.len())
2444 ty::TyTuple(arg_types) => {
2445 expected_arg_tys = match expected_arg_tys.get(0) {
2446 Some(&ty) => match ty.sty {
2447 ty::TyTuple(ref tys) => &tys,
2455 span_err!(tcx.sess, sp, E0059,
2456 "cannot use call notation; the first type parameter \
2457 for the function trait is neither a tuple nor unit");
2458 expected_arg_tys = &[];
2459 self.err_args(args.len())
2462 } else if expected_arg_count == supplied_arg_count {
2464 } else if variadic {
2465 if supplied_arg_count >= expected_arg_count {
2468 parameter_count_error(tcx.sess, sp, fn_inputs, expected_arg_count,
2469 supplied_arg_count, "E0060", true);
2470 expected_arg_tys = &[];
2471 self.err_args(supplied_arg_count)
2474 parameter_count_error(tcx.sess, sp, fn_inputs, expected_arg_count, supplied_arg_count,
2476 expected_arg_tys = &[];
2477 self.err_args(supplied_arg_count)
2480 debug!("check_argument_types: formal_tys={:?}",
2481 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2483 // Check the arguments.
2484 // We do this in a pretty awful way: first we typecheck any arguments
2485 // that are not anonymous functions, then we typecheck the anonymous
2486 // functions. This is so that we have more information about the types
2487 // of arguments when we typecheck the functions. This isn't really the
2488 // right way to do this.
2489 let xs = [false, true];
2490 let mut any_diverges = false; // has any of the arguments diverged?
2491 let mut warned = false; // have we already warned about unreachable code?
2492 for check_blocks in &xs {
2493 let check_blocks = *check_blocks;
2494 debug!("check_blocks={}", check_blocks);
2496 // More awful hacks: before we check argument types, try to do
2497 // an "opportunistic" vtable resolution of any trait bounds on
2498 // the call. This helps coercions.
2500 self.select_obligations_where_possible();
2503 // For variadic functions, we don't have a declared type for all of
2504 // the arguments hence we only do our usual type checking with
2505 // the arguments who's types we do know.
2506 let t = if variadic {
2508 } else if tuple_arguments == TupleArguments {
2513 for (i, arg) in args.iter().take(t).enumerate() {
2514 if any_diverges && !warned {
2517 .add_lint(lint::builtin::UNREACHABLE_CODE,
2520 "unreachable expression".to_string());
2523 let is_block = match arg.node {
2524 hir::ExprClosure(..) => true,
2528 if is_block == check_blocks {
2529 debug!("checking the argument");
2530 let formal_ty = formal_tys[i];
2532 // The special-cased logic below has three functions:
2533 // 1. Provide as good of an expected type as possible.
2534 let expected = expected_arg_tys.get(i).map(|&ty| {
2535 Expectation::rvalue_hint(self, ty)
2538 self.check_expr_with_expectation(&arg,
2539 expected.unwrap_or(ExpectHasType(formal_ty)));
2540 // 2. Coerce to the most detailed type that could be coerced
2541 // to, which is `expected_ty` if `rvalue_hint` returns an
2542 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2543 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2544 self.demand_coerce(&arg, coerce_ty.unwrap_or(formal_ty));
2546 // 3. Relate the expected type and the formal one,
2547 // if the expected type was used for the coercion.
2548 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2551 if let Some(&arg_ty) = self.tables.borrow().node_types.get(&arg.id) {
2552 any_diverges = any_diverges || self.type_var_diverges(arg_ty);
2555 if any_diverges && !warned {
2556 let parent = self.tcx.map.get_parent_node(args[0].id);
2559 .add_lint(lint::builtin::UNREACHABLE_CODE,
2562 "unreachable call".to_string());
2568 // We also need to make sure we at least write the ty of the other
2569 // arguments which we skipped above.
2571 for arg in args.iter().skip(expected_arg_count) {
2572 self.check_expr(&arg);
2574 // There are a few types which get autopromoted when passed via varargs
2575 // in C but we just error out instead and require explicit casts.
2576 let arg_ty = self.structurally_resolved_type(arg.span,
2577 self.expr_ty(&arg));
2579 ty::TyFloat(ast::FloatTy::F32) => {
2580 self.type_error_message(arg.span, |t| {
2581 format!("can't pass an `{}` to variadic \
2582 function, cast to `c_double`", t)
2585 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2586 self.type_error_message(arg.span, |t| {
2587 format!("can't pass `{}` to variadic \
2588 function, cast to `c_int`",
2592 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2593 self.type_error_message(arg.span, |t| {
2594 format!("can't pass `{}` to variadic \
2595 function, cast to `c_uint`",
2599 ty::TyFnDef(_, _, f) => {
2600 let ptr_ty = self.tcx.mk_fn_ptr(f);
2601 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2602 self.type_error_message(arg.span,
2604 format!("can't pass `{}` to variadic \
2605 function, cast to `{}`", t, ptr_ty)
2614 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2615 (0..len).map(|_| self.tcx.types.err).collect()
2618 fn write_call(&self,
2619 call_expr: &hir::Expr,
2620 output: ty::FnOutput<'tcx>) {
2621 self.write_ty(call_expr.id, match output {
2622 ty::FnConverging(output_ty) => output_ty,
2623 ty::FnDiverging => self.next_diverging_ty_var()
2627 // AST fragment checking
2630 expected: Expectation<'tcx>)
2636 ast::LitKind::Str(..) => tcx.mk_static_str(),
2637 ast::LitKind::ByteStr(ref v) => {
2638 tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic),
2639 tcx.mk_array(tcx.types.u8, v.len()))
2641 ast::LitKind::Byte(_) => tcx.types.u8,
2642 ast::LitKind::Char(_) => tcx.types.char,
2643 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2644 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2645 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2646 let opt_ty = expected.to_option(self).and_then(|ty| {
2648 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2649 ty::TyChar => Some(tcx.types.u8),
2650 ty::TyRawPtr(..) => Some(tcx.types.usize),
2651 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2655 opt_ty.unwrap_or_else(
2656 || tcx.mk_int_var(self.next_int_var_id()))
2658 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2659 ast::LitKind::FloatUnsuffixed(_) => {
2660 let opt_ty = expected.to_option(self).and_then(|ty| {
2662 ty::TyFloat(_) => Some(ty),
2666 opt_ty.unwrap_or_else(
2667 || tcx.mk_float_var(self.next_float_var_id()))
2669 ast::LitKind::Bool(_) => tcx.types.bool
2673 fn check_expr_eq_type(&self,
2674 expr: &'gcx hir::Expr,
2675 expected: Ty<'tcx>) {
2676 self.check_expr_with_hint(expr, expected);
2677 self.demand_eqtype(expr.span, expected, self.expr_ty(expr));
2680 pub fn check_expr_has_type(&self,
2681 expr: &'gcx hir::Expr,
2682 expected: Ty<'tcx>) {
2683 self.check_expr_with_hint(expr, expected);
2684 self.demand_suptype(expr.span, expected, self.expr_ty(expr));
2687 fn check_expr_coercable_to_type(&self,
2688 expr: &'gcx hir::Expr,
2689 expected: Ty<'tcx>) {
2690 self.check_expr_with_hint(expr, expected);
2691 self.demand_coerce(expr, expected);
2694 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2695 expected: Ty<'tcx>) {
2696 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2699 fn check_expr_with_expectation(&self,
2700 expr: &'gcx hir::Expr,
2701 expected: Expectation<'tcx>) {
2702 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2705 fn check_expr(&self, expr: &'gcx hir::Expr) {
2706 self.check_expr_with_expectation(expr, NoExpectation)
2709 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2710 lvalue_pref: LvaluePreference) {
2711 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2714 // determine the `self` type, using fresh variables for all variables
2715 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2716 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2718 pub fn impl_self_ty(&self,
2719 span: Span, // (potential) receiver for this impl
2721 -> TypeAndSubsts<'tcx> {
2724 let ity = tcx.lookup_item_type(did);
2725 let (tps, rps, raw_ty) =
2726 (ity.generics.types.get_slice(subst::TypeSpace),
2727 ity.generics.regions.get_slice(subst::TypeSpace),
2730 debug!("impl_self_ty: tps={:?} rps={:?} raw_ty={:?}", tps, rps, raw_ty);
2732 let rps = self.region_vars_for_defs(span, rps);
2733 let mut substs = subst::Substs::new(
2734 VecPerParamSpace::empty(),
2735 VecPerParamSpace::new(rps, Vec::new(), Vec::new()));
2736 self.type_vars_for_defs(span, ParamSpace::TypeSpace, &mut substs, tps);
2737 let substd_ty = self.instantiate_type_scheme(span, &substs, &raw_ty);
2739 TypeAndSubsts { substs: substs, ty: substd_ty }
2742 /// Unifies the return type with the expected type early, for more coercions
2743 /// and forward type information on the argument expressions.
2744 fn expected_types_for_fn_args(&self,
2746 expected_ret: Expectation<'tcx>,
2747 formal_ret: ty::FnOutput<'tcx>,
2748 formal_args: &[Ty<'tcx>])
2750 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2751 if let ty::FnConverging(formal_ret_ty) = formal_ret {
2752 self.commit_regions_if_ok(|| {
2753 // Attempt to apply a subtyping relationship between the formal
2754 // return type (likely containing type variables if the function
2755 // is polymorphic) and the expected return type.
2756 // No argument expectations are produced if unification fails.
2757 let origin = TypeOrigin::Misc(call_span);
2758 let ures = self.sub_types(false, origin, formal_ret_ty, ret_ty);
2759 // FIXME(#15760) can't use try! here, FromError doesn't default
2760 // to identity so the resulting type is not constrained.
2762 // FIXME(#32730) propagate obligations
2763 Ok(InferOk { obligations, .. }) => assert!(obligations.is_empty()),
2764 Err(e) => return Err(e),
2767 // Record all the argument types, with the substitutions
2768 // produced from the above subtyping unification.
2769 Ok(formal_args.iter().map(|ty| {
2770 self.resolve_type_vars_if_possible(ty)
2776 }).unwrap_or(vec![]);
2777 debug!("expected_types_for_fn_args(formal={:?} -> {:?}, expected={:?} -> {:?})",
2778 formal_args, formal_ret,
2779 expected_args, expected_ret);
2783 // Checks a method call.
2784 fn check_method_call(&self,
2785 expr: &'gcx hir::Expr,
2786 method_name: Spanned<ast::Name>,
2787 args: &'gcx [P<hir::Expr>],
2789 expected: Expectation<'tcx>,
2790 lvalue_pref: LvaluePreference) {
2791 let rcvr = &args[0];
2792 self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2794 // no need to check for bot/err -- callee does that
2795 let expr_t = self.structurally_resolved_type(expr.span, self.expr_ty(&rcvr));
2797 let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2798 let fn_ty = match self.lookup_method(method_name.span,
2805 let method_ty = method.ty;
2806 let method_call = MethodCall::expr(expr.id);
2807 self.tables.borrow_mut().method_map.insert(method_call, method);
2811 if method_name.node != keywords::Invalid.name() {
2812 self.report_method_error(method_name.span, expr_t,
2813 method_name.node, Some(rcvr), error);
2815 self.write_error(expr.id);
2820 // Call the generic checker.
2821 let ret_ty = self.check_method_argument_types(method_name.span, fn_ty,
2826 self.write_call(expr, ret_ty);
2829 // A generic function for checking the then and else in an if
2831 fn check_then_else(&self,
2832 cond_expr: &'gcx hir::Expr,
2833 then_blk: &'gcx hir::Block,
2834 opt_else_expr: Option<&'gcx hir::Expr>,
2837 expected: Expectation<'tcx>) {
2838 self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2840 let expected = expected.adjust_for_branches(self);
2841 self.check_block_with_expected(then_blk, expected);
2842 let then_ty = self.node_ty(then_blk.id);
2844 let unit = self.tcx.mk_nil();
2845 let (origin, expected, found, result) =
2846 if let Some(else_expr) = opt_else_expr {
2847 self.check_expr_with_expectation(else_expr, expected);
2848 let else_ty = self.expr_ty(else_expr);
2849 let origin = TypeOrigin::IfExpression(sp);
2851 // Only try to coerce-unify if we have a then expression
2852 // to assign coercions to, otherwise it's () or diverging.
2853 let result = if let Some(ref then) = then_blk.expr {
2854 let res = self.try_find_coercion_lub(origin, || Some(&**then),
2855 then_ty, else_expr);
2857 // In case we did perform an adjustment, we have to update
2858 // the type of the block, because old trans still uses it.
2859 let adj = self.tables.borrow().adjustments.get(&then.id).cloned();
2860 if res.is_ok() && adj.is_some() {
2861 self.write_ty(then_blk.id, self.adjust_expr_ty(then, adj.as_ref()));
2866 self.commit_if_ok(|_| {
2867 let trace = TypeTrace::types(origin, true, then_ty, else_ty);
2868 self.lub(true, trace, &then_ty, &else_ty)
2869 .map(|InferOk { value, obligations }| {
2870 // FIXME(#32730) propagate obligations
2871 assert!(obligations.is_empty());
2876 (origin, then_ty, else_ty, result)
2878 let origin = TypeOrigin::IfExpressionWithNoElse(sp);
2879 (origin, unit, then_ty,
2880 self.eq_types(true, origin, unit, then_ty)
2881 .map(|InferOk { obligations, .. }| {
2882 // FIXME(#32730) propagate obligations
2883 assert!(obligations.is_empty());
2888 let if_ty = match result {
2890 if self.expr_ty(cond_expr).references_error() {
2897 self.report_mismatched_types(origin, expected, found, e);
2902 self.write_ty(id, if_ty);
2905 // Check field access expressions
2906 fn check_field(&self,
2907 expr: &'gcx hir::Expr,
2908 lvalue_pref: LvaluePreference,
2909 base: &'gcx hir::Expr,
2910 field: &Spanned<ast::Name>) {
2911 self.check_expr_with_lvalue_pref(base, lvalue_pref);
2912 let expr_t = self.structurally_resolved_type(expr.span,
2913 self.expr_ty(base));
2914 let mut private_candidate = None;
2915 let mut autoderef = self.autoderef(expr.span, expr_t);
2916 while let Some((base_t, autoderefs)) = autoderef.next() {
2917 if let ty::TyStruct(base_def, substs) = base_t.sty {
2918 debug!("struct named {:?}", base_t);
2919 if let Some(field) = base_def.struct_variant().find_field_named(field.node) {
2920 let field_ty = self.field_ty(expr.span, field, substs);
2921 if field.vis.is_accessible_from(self.body_id, &self.tcx().map) {
2922 autoderef.finalize(lvalue_pref, Some(base));
2923 self.write_ty(expr.id, field_ty);
2924 self.write_autoderef_adjustment(base.id, autoderefs);
2927 private_candidate = Some((base_def.did, field_ty));
2931 autoderef.unambiguous_final_ty();
2933 if let Some((did, field_ty)) = private_candidate {
2934 let struct_path = self.tcx().item_path_str(did);
2935 self.write_ty(expr.id, field_ty);
2936 let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
2937 let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
2938 // Also check if an accessible method exists, which is often what is meant.
2939 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2940 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2944 } else if field.node == keywords::Invalid.name() {
2945 self.write_error(expr.id);
2946 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2947 self.type_error_struct(field.span, |actual| {
2948 format!("attempted to take value of method `{}` on type \
2949 `{}`", field.node, actual)
2951 .help("maybe a `()` to call it is missing? \
2952 If not, try an anonymous function")
2954 self.write_error(expr.id);
2956 let mut err = self.type_error_struct(expr.span, |actual| {
2957 format!("attempted access of field `{}` on type `{}`, \
2958 but no field with that name was found",
2961 if let ty::TyStruct(def, _) = expr_t.sty {
2962 Self::suggest_field_names(&mut err, def.struct_variant(), field, vec![]);
2965 self.write_error(expr.id);
2969 // displays hints about the closest matches in field names
2970 fn suggest_field_names(err: &mut DiagnosticBuilder,
2971 variant: ty::VariantDef<'tcx>,
2972 field: &Spanned<ast::Name>,
2973 skip : Vec<InternedString>) {
2974 let name = field.node.as_str();
2975 let names = variant.fields.iter().filter_map(|field| {
2976 // ignore already set fields and private fields from non-local crates
2977 if skip.iter().any(|x| *x == field.name.as_str()) ||
2978 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
2985 // only find fits with at least one matching letter
2986 if let Some(name) = find_best_match_for_name(names, &name, Some(name.len())) {
2987 err.span_help(field.span,
2988 &format!("did you mean `{}`?", name));
2992 // Check tuple index expressions
2993 fn check_tup_field(&self,
2994 expr: &'gcx hir::Expr,
2995 lvalue_pref: LvaluePreference,
2996 base: &'gcx hir::Expr,
2997 idx: codemap::Spanned<usize>) {
2998 self.check_expr_with_lvalue_pref(base, lvalue_pref);
2999 let expr_t = self.structurally_resolved_type(expr.span,
3000 self.expr_ty(base));
3001 let mut private_candidate = None;
3002 let mut tuple_like = false;
3003 let mut autoderef = self.autoderef(expr.span, expr_t);
3004 while let Some((base_t, autoderefs)) = autoderef.next() {
3005 let field = match base_t.sty {
3006 ty::TyStruct(base_def, substs) => {
3007 tuple_like = base_def.struct_variant().kind == ty::VariantKind::Tuple;
3008 if !tuple_like { continue }
3010 debug!("tuple struct named {:?}", base_t);
3011 base_def.struct_variant().fields.get(idx.node).and_then(|field| {
3012 let field_ty = self.field_ty(expr.span, field, substs);
3013 private_candidate = Some((base_def.did, field_ty));
3014 if field.vis.is_accessible_from(self.body_id, &self.tcx().map) {
3021 ty::TyTuple(ref v) => {
3023 v.get(idx.node).cloned()
3028 if let Some(field_ty) = field {
3029 autoderef.finalize(lvalue_pref, Some(base));
3030 self.write_ty(expr.id, field_ty);
3031 self.write_autoderef_adjustment(base.id, autoderefs);
3035 autoderef.unambiguous_final_ty();
3037 if let Some((did, field_ty)) = private_candidate {
3038 let struct_path = self.tcx().item_path_str(did);
3039 let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3040 self.tcx().sess.span_err(expr.span, &msg);
3041 self.write_ty(expr.id, field_ty);
3045 self.type_error_message(
3049 format!("attempted out-of-bounds tuple index `{}` on \
3054 format!("attempted tuple index `{}` on type `{}`, but the \
3055 type was not a tuple or tuple struct",
3062 self.write_error(expr.id);
3065 fn report_unknown_field(&self,
3067 variant: ty::VariantDef<'tcx>,
3069 skip_fields: &[hir::Field]) {
3070 let mut err = self.type_error_struct_with_diag(
3072 |actual| if let ty::TyEnum(..) = ty.sty {
3073 struct_span_err!(self.tcx.sess, field.name.span, E0559,
3074 "struct variant `{}::{}` has no field named `{}`",
3075 actual, variant.name.as_str(), field.name.node)
3077 struct_span_err!(self.tcx.sess, field.name.span, E0560,
3078 "structure `{}` has no field named `{}`",
3079 actual, field.name.node)
3082 // prevent all specified fields from being suggested
3083 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3084 Self::suggest_field_names(&mut err, variant, &field.name, skip_fields.collect());
3088 fn check_expr_struct_fields(&self,
3091 variant: ty::VariantDef<'tcx>,
3092 ast_fields: &'gcx [hir::Field],
3093 check_completeness: bool) {
3095 let substs = match adt_ty.sty {
3096 ty::TyStruct(_, substs) | ty::TyEnum(_, substs) => substs,
3097 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3100 let mut remaining_fields = FnvHashMap();
3101 for field in &variant.fields {
3102 remaining_fields.insert(field.name, field);
3105 let mut seen_fields = FnvHashMap();
3107 let mut error_happened = false;
3109 // Typecheck each field.
3110 for field in ast_fields {
3111 let expected_field_type;
3113 if let Some(v_field) = remaining_fields.remove(&field.name.node) {
3114 expected_field_type = self.field_ty(field.span, v_field, substs);
3116 seen_fields.insert(field.name.node, field.span);
3118 error_happened = true;
3119 expected_field_type = tcx.types.err;
3120 if let Some(_) = variant.find_field_named(field.name.node) {
3121 let mut err = struct_span_err!(self.tcx.sess,
3124 "field `{}` specified more than once",
3127 err.span_label(field.name.span, &format!("used more than once"));
3129 if let Some(prev_span) = seen_fields.get(&field.name.node) {
3130 err.span_label(*prev_span, &format!("first use of `{}`", field.name.node));
3135 self.report_unknown_field(adt_ty, variant, field, ast_fields);
3139 // Make sure to give a type to the field even if there's
3140 // an error, so we can continue typechecking
3141 self.check_expr_coercable_to_type(&field.expr, expected_field_type);
3144 // Make sure the programmer specified all the fields.
3145 if check_completeness &&
3147 !remaining_fields.is_empty()
3149 span_err!(tcx.sess, span, E0063,
3150 "missing field{} {} in initializer of `{}`",
3151 if remaining_fields.len() == 1 {""} else {"s"},
3152 remaining_fields.keys()
3153 .map(|n| format!("`{}`", n))
3154 .collect::<Vec<_>>()
3161 fn check_struct_fields_on_error(&self,
3163 fields: &'gcx [hir::Field],
3164 base_expr: &'gcx Option<P<hir::Expr>>) {
3165 // Make sure to still write the types
3166 // otherwise we might ICE
3167 self.write_error(id);
3168 for field in fields {
3169 self.check_expr(&field.expr);
3172 Some(ref base) => self.check_expr(&base),
3177 pub fn check_struct_path(&self,
3179 node_id: ast::NodeId,
3181 -> Option<(ty::VariantDef<'tcx>, Ty<'tcx>)> {
3182 let def = self.finish_resolving_struct_path(path, node_id, span);
3183 let variant = match def {
3185 self.set_tainted_by_errors();
3188 Def::Variant(..) | Def::Struct(..) => {
3189 Some(self.tcx.expect_variant_def(def))
3191 Def::TyAlias(did) | Def::AssociatedTy(_, did) => {
3192 if let Some(&ty::TyStruct(adt, _)) = self.tcx.opt_lookup_item_type(did)
3193 .map(|scheme| &scheme.ty.sty) {
3194 Some(adt.struct_variant())
3201 if variant.is_none() || variant.unwrap().kind == ty::VariantKind::Tuple {
3202 // Reject tuple structs for now, braced and unit structs are allowed.
3203 struct_span_err!(self.tcx.sess, path.span, E0071,
3204 "`{}` does not name a struct or a struct variant",
3205 pprust::path_to_string(path))
3206 .span_label(path.span, &format!("not a struct"))
3212 let ty = self.instantiate_type_path(def.def_id(), path, node_id);
3213 Some((variant.unwrap(), ty))
3216 fn check_expr_struct(&self,
3219 fields: &'gcx [hir::Field],
3220 base_expr: &'gcx Option<P<hir::Expr>>)
3222 // Find the relevant variant
3223 let (variant, expr_ty) = if let Some(variant_ty) = self.check_struct_path(path, expr.id,
3227 self.check_struct_fields_on_error(expr.id, fields, base_expr);
3231 self.check_expr_struct_fields(expr_ty, path.span, variant, fields,
3232 base_expr.is_none());
3233 if let &Some(ref base_expr) = base_expr {
3234 self.check_expr_has_type(base_expr, expr_ty);
3236 ty::TyStruct(adt, substs) => {
3237 self.tables.borrow_mut().fru_field_types.insert(
3239 adt.struct_variant().fields.iter().map(|f| {
3240 self.normalize_associated_types_in(
3241 expr.span, &f.ty(self.tcx, substs)
3247 span_err!(self.tcx.sess, base_expr.span, E0436,
3248 "functional record update syntax requires a struct");
3256 /// If an expression has any sub-expressions that result in a type error,
3257 /// inspecting that expression's type with `ty.references_error()` will return
3258 /// true. Likewise, if an expression is known to diverge, inspecting its
3259 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3260 /// strict, _|_ can appear in the type of an expression that does not,
3261 /// itself, diverge: for example, fn() -> _|_.)
3262 /// Note that inspecting a type's structure *directly* may expose the fact
3263 /// that there are actually multiple representations for `TyError`, so avoid
3264 /// that when err needs to be handled differently.
3265 fn check_expr_with_expectation_and_lvalue_pref(&self,
3266 expr: &'gcx hir::Expr,
3267 expected: Expectation<'tcx>,
3268 lvalue_pref: LvaluePreference) {
3269 debug!(">> typechecking: expr={:?} expected={:?}",
3275 hir::ExprBox(ref subexpr) => {
3276 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3278 ty::TyBox(ty) => Expectation::rvalue_hint(self, ty),
3282 self.check_expr_with_expectation(subexpr, expected_inner);
3283 let referent_ty = self.expr_ty(&subexpr);
3284 self.write_ty(id, tcx.mk_box(referent_ty));
3287 hir::ExprLit(ref lit) => {
3288 let typ = self.check_lit(&lit, expected);
3289 self.write_ty(id, typ);
3291 hir::ExprBinary(op, ref lhs, ref rhs) => {
3292 self.check_binop(expr, op, lhs, rhs);
3294 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3295 self.check_binop_assign(expr, op, lhs, rhs);
3297 hir::ExprUnary(unop, ref oprnd) => {
3298 let expected_inner = match unop {
3299 hir::UnNot | hir::UnNeg => {
3306 let lvalue_pref = match unop {
3307 hir::UnDeref => lvalue_pref,
3310 self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3313 let mut oprnd_t = self.expr_ty(&oprnd);
3315 if !oprnd_t.references_error() {
3318 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3320 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3322 } else if let Some(method) = self.try_overloaded_deref(
3323 expr.span, Some(&oprnd), oprnd_t, lvalue_pref) {
3324 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3325 self.tables.borrow_mut().method_map.insert(MethodCall::expr(expr.id),
3328 self.type_error_message(expr.span, |actual| {
3329 format!("type `{}` cannot be \
3330 dereferenced", actual)
3332 oprnd_t = tcx.types.err;
3336 oprnd_t = self.structurally_resolved_type(oprnd.span,
3338 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3339 oprnd_t = self.check_user_unop("!", "not",
3340 tcx.lang_items.not_trait(),
3341 expr, &oprnd, oprnd_t, unop);
3345 oprnd_t = self.structurally_resolved_type(oprnd.span,
3347 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3348 oprnd_t = self.check_user_unop("-", "neg",
3349 tcx.lang_items.neg_trait(),
3350 expr, &oprnd, oprnd_t, unop);
3355 self.write_ty(id, oprnd_t);
3357 hir::ExprAddrOf(mutbl, ref oprnd) => {
3358 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3360 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3361 if self.tcx.expr_is_lval(&oprnd) {
3362 // Lvalues may legitimately have unsized types.
3363 // For example, dereferences of a fat pointer and
3364 // the last field of a struct can be unsized.
3365 ExpectHasType(mt.ty)
3367 Expectation::rvalue_hint(self, mt.ty)
3373 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3374 self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3376 let tm = ty::TypeAndMut { ty: self.expr_ty(&oprnd), mutbl: mutbl };
3377 let oprnd_t = if tm.ty.references_error() {
3380 // Note: at this point, we cannot say what the best lifetime
3381 // is to use for resulting pointer. We want to use the
3382 // shortest lifetime possible so as to avoid spurious borrowck
3383 // errors. Moreover, the longest lifetime will depend on the
3384 // precise details of the value whose address is being taken
3385 // (and how long it is valid), which we don't know yet until type
3386 // inference is complete.
3388 // Therefore, here we simply generate a region variable. The
3389 // region inferencer will then select the ultimate value.
3390 // Finally, borrowck is charged with guaranteeing that the
3391 // value whose address was taken can actually be made to live
3392 // as long as it needs to live.
3393 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3394 tcx.mk_ref(tcx.mk_region(region), tm)
3396 self.write_ty(id, oprnd_t);
3398 hir::ExprPath(ref opt_qself, ref path) => {
3399 let opt_self_ty = opt_qself.as_ref().map(|qself| self.to_ty(&qself.ty));
3400 let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(opt_self_ty, path,
3401 expr.id, expr.span);
3402 if def != Def::Err {
3403 let (scheme, predicates) = self.type_scheme_and_predicates_for_def(expr.span,
3405 self.instantiate_value_path(segments, scheme, &predicates,
3406 opt_ty, def, expr.span, id);
3408 self.set_tainted_by_errors();
3409 self.write_error(id);
3412 // We always require that the type provided as the value for
3413 // a type parameter outlives the moment of instantiation.
3414 self.opt_node_ty_substs(expr.id, |item_substs| {
3415 self.add_wf_bounds(&item_substs.substs, expr);
3418 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3419 for output in outputs {
3420 self.check_expr(output);
3422 for input in inputs {
3423 self.check_expr(input);
3427 hir::ExprBreak(_) => { self.write_ty(id, self.next_diverging_ty_var()); }
3428 hir::ExprAgain(_) => { self.write_ty(id, self.next_diverging_ty_var()); }
3429 hir::ExprRet(ref expr_opt) => {
3431 ty::FnConverging(result_type) => {
3432 if let Some(ref e) = *expr_opt {
3433 self.check_expr_coercable_to_type(&e, result_type);
3435 let eq_result = self.eq_types(false,
3436 TypeOrigin::Misc(expr.span),
3439 // FIXME(#32730) propagate obligations
3440 .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()));
3441 if eq_result.is_err() {
3442 struct_span_err!(tcx.sess, expr.span, E0069,
3443 "`return;` in a function whose return type is not `()`")
3444 .span_label(expr.span, &format!("return type is not ()"))
3449 ty::FnDiverging => {
3450 if let Some(ref e) = *expr_opt {
3451 self.check_expr(&e);
3453 struct_span_err!(tcx.sess, expr.span, E0166,
3454 "`return` in a function declared as diverging")
3455 .span_label(expr.span, &format!("diverging function cannot return"))
3459 self.write_ty(id, self.next_diverging_ty_var());
3461 hir::ExprAssign(ref lhs, ref rhs) => {
3462 self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3465 if !tcx.expr_is_lval(&lhs) {
3466 span_err!(tcx.sess, expr.span, E0070,
3467 "invalid left-hand side expression");
3470 let lhs_ty = self.expr_ty(&lhs);
3471 self.check_expr_coercable_to_type(&rhs, lhs_ty);
3472 let rhs_ty = self.expr_ty(&rhs);
3474 self.require_expr_have_sized_type(&lhs, traits::AssignmentLhsSized);
3476 if lhs_ty.references_error() || rhs_ty.references_error() {
3477 self.write_error(id);
3482 hir::ExprIf(ref cond, ref then_blk, ref opt_else_expr) => {
3483 self.check_then_else(&cond, &then_blk, opt_else_expr.as_ref().map(|e| &**e),
3484 id, expr.span, expected);
3486 hir::ExprWhile(ref cond, ref body, _) => {
3487 self.check_expr_has_type(&cond, tcx.types.bool);
3488 self.check_block_no_value(&body);
3489 let cond_ty = self.expr_ty(&cond);
3490 let body_ty = self.node_ty(body.id);
3491 if cond_ty.references_error() || body_ty.references_error() {
3492 self.write_error(id);
3498 hir::ExprLoop(ref body, _) => {
3499 self.check_block_no_value(&body);
3500 if !may_break(tcx, expr.id, &body) {
3501 self.write_ty(id, self.next_diverging_ty_var());
3506 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3507 self.check_match(expr, &discrim, arms, expected, match_src);
3509 hir::ExprClosure(capture, ref decl, ref body, _) => {
3510 self.check_expr_closure(expr, capture, &decl, &body, expected);
3512 hir::ExprBlock(ref b) => {
3513 self.check_block_with_expected(&b, expected);
3514 self.write_ty(id, self.node_ty(b.id));
3516 hir::ExprCall(ref callee, ref args) => {
3517 self.check_call(expr, &callee, &args[..], expected);
3519 // we must check that return type of called functions is WF:
3520 let ret_ty = self.expr_ty(expr);
3521 self.register_wf_obligation(ret_ty, expr.span, traits::MiscObligation);
3523 hir::ExprMethodCall(name, ref tps, ref args) => {
3524 self.check_method_call(expr, name, &args[..], &tps[..], expected, lvalue_pref);
3525 let arg_tys = args.iter().map(|a| self.expr_ty(&a));
3526 let args_err = arg_tys.fold(false, |rest_err, a| rest_err || a.references_error());
3528 self.write_error(id);
3531 hir::ExprCast(ref e, ref t) => {
3532 if let hir::TyFixedLengthVec(_, ref count_expr) = t.node {
3533 self.check_expr_with_hint(&count_expr, tcx.types.usize);
3536 // Find the type of `e`. Supply hints based on the type we are casting to,
3538 let t_cast = self.to_ty(t);
3539 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3540 self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3541 let t_expr = self.expr_ty(e);
3542 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3544 // Eagerly check for some obvious errors.
3545 if t_expr.references_error() || t_cast.references_error() {
3546 self.write_error(id);
3548 // Write a type for the whole expression, assuming everything is going
3550 self.write_ty(id, t_cast);
3552 // Defer other checks until we're done type checking.
3553 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3554 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
3556 deferred_cast_checks.push(cast_check);
3558 Err(ErrorReported) => {
3559 self.write_error(id);
3564 hir::ExprType(ref e, ref t) => {
3565 let typ = self.to_ty(&t);
3566 self.check_expr_eq_type(&e, typ);
3567 self.write_ty(id, typ);
3569 hir::ExprVec(ref args) => {
3570 let uty = expected.to_option(self).and_then(|uty| {
3572 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3577 let mut unified = self.next_ty_var();
3578 let coerce_to = uty.unwrap_or(unified);
3580 for (i, e) in args.iter().enumerate() {
3581 self.check_expr_with_hint(e, coerce_to);
3582 let e_ty = self.expr_ty(e);
3583 let origin = TypeOrigin::Misc(e.span);
3585 // Special-case the first element, as it has no "previous expressions".
3586 let result = if i == 0 {
3587 self.try_coerce(e, coerce_to)
3589 let prev_elems = || args[..i].iter().map(|e| &**e);
3590 self.try_find_coercion_lub(origin, prev_elems, unified, e)
3594 Ok(ty) => unified = ty,
3596 self.report_mismatched_types(origin, unified, e_ty, e);
3600 self.write_ty(id, tcx.mk_array(unified, args.len()));
3602 hir::ExprRepeat(ref element, ref count_expr) => {
3603 self.check_expr_has_type(&count_expr, tcx.types.usize);
3604 let count = eval_length(self.tcx.global_tcx(), &count_expr, "repeat count")
3607 let uty = match expected {
3608 ExpectHasType(uty) => {
3610 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3617 let (element_ty, t) = match uty {
3619 self.check_expr_coercable_to_type(&element, uty);
3623 let t: Ty = self.next_ty_var();
3624 self.check_expr_has_type(&element, t);
3625 (self.expr_ty(&element), t)
3630 // For [foo, ..n] where n > 1, `foo` must have
3632 self.require_type_meets(t, expr.span, traits::RepeatVec, ty::BoundCopy);
3635 if element_ty.references_error() {
3636 self.write_error(id);
3638 let t = tcx.mk_array(t, count);
3639 self.write_ty(id, t);
3642 hir::ExprTup(ref elts) => {
3643 let flds = expected.only_has_type(self).and_then(|ty| {
3645 ty::TyTuple(ref flds) => Some(&flds[..]),
3649 let mut err_field = false;
3651 let elt_ts = elts.iter().enumerate().map(|(i, e)| {
3652 let t = match flds {
3653 Some(ref fs) if i < fs.len() => {
3655 self.check_expr_coercable_to_type(&e, ety);
3659 self.check_expr_with_expectation(&e, NoExpectation);
3663 err_field = err_field || t.references_error();
3667 self.write_error(id);
3669 let typ = tcx.mk_tup(elt_ts);
3670 self.write_ty(id, typ);
3673 hir::ExprStruct(ref path, ref fields, ref base_expr) => {
3674 self.check_expr_struct(expr, path, fields, base_expr);
3676 self.require_expr_have_sized_type(expr, traits::StructInitializerSized);
3678 hir::ExprField(ref base, ref field) => {
3679 self.check_field(expr, lvalue_pref, &base, field);
3681 hir::ExprTupField(ref base, idx) => {
3682 self.check_tup_field(expr, lvalue_pref, &base, idx);
3684 hir::ExprIndex(ref base, ref idx) => {
3685 self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3686 self.check_expr(&idx);
3688 let base_t = self.expr_ty(&base);
3689 let idx_t = self.expr_ty(&idx);
3691 if base_t.references_error() {
3692 self.write_ty(id, base_t);
3693 } else if idx_t.references_error() {
3694 self.write_ty(id, idx_t);
3696 let base_t = self.structurally_resolved_type(expr.span, base_t);
3697 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3698 Some((index_ty, element_ty)) => {
3699 let idx_expr_ty = self.expr_ty(idx);
3700 self.demand_eqtype(expr.span, index_ty, idx_expr_ty);
3701 self.write_ty(id, element_ty);
3704 self.check_expr_has_type(&idx, self.tcx.types.err);
3705 let mut err = self.type_error_struct(
3708 format!("cannot index a value of type `{}`",
3712 // Try to give some advice about indexing tuples.
3713 if let ty::TyTuple(_) = base_t.sty {
3714 let mut needs_note = true;
3715 // If the index is an integer, we can show the actual
3716 // fixed expression:
3717 if let hir::ExprLit(ref lit) = idx.node {
3718 if let ast::LitKind::Int(i,
3719 ast::LitIntType::Unsuffixed) = lit.node {
3720 let snip = tcx.sess.codemap().span_to_snippet(base.span);
3721 if let Ok(snip) = snip {
3722 err.span_suggestion(expr.span,
3723 "to access tuple elements, \
3724 use tuple indexing syntax \
3726 format!("{}.{}", snip, i));
3732 err.help("to access tuple elements, use tuple indexing \
3733 syntax (e.g. `tuple.0`)");
3737 self.write_ty(id, self.tcx().types.err);
3744 debug!("type of expr({}) {} is...", expr.id,
3745 pprust::expr_to_string(expr));
3746 debug!("... {:?}, expected is {:?}",
3751 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3752 // The newly resolved definition is written into `def_map`.
3753 pub fn finish_resolving_struct_path(&self,
3755 node_id: ast::NodeId,
3759 let path_res = self.tcx().expect_resolution(node_id);
3760 if path_res.depth == 0 {
3761 // If fully resolved already, we don't have to do anything.
3764 let base_ty_end = path.segments.len() - path_res.depth;
3765 let (_ty, def) = AstConv::finish_resolving_def_to_ty(self, self, span,
3766 PathParamMode::Optional,
3770 &path.segments[..base_ty_end],
3771 &path.segments[base_ty_end..]);
3772 // Write back the new resolution.
3773 self.tcx().def_map.borrow_mut().insert(node_id, PathResolution::new(def));
3778 // Resolve associated value path into a base type and associated constant or method definition.
3779 // The newly resolved definition is written into `def_map`.
3780 pub fn resolve_ty_and_def_ufcs<'b>(&self,
3781 opt_self_ty: Option<Ty<'tcx>>,
3782 path: &'b hir::Path,
3783 node_id: ast::NodeId,
3785 -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3787 let path_res = self.tcx().expect_resolution(node_id);
3788 if path_res.depth == 0 {
3789 // If fully resolved already, we don't have to do anything.
3790 (path_res.base_def, opt_self_ty, &path.segments)
3792 // Try to resolve everything except for the last segment as a type.
3793 let ty_segments = path.segments.split_last().unwrap().1;
3794 let base_ty_end = path.segments.len() - path_res.depth;
3795 let (ty, _def) = AstConv::finish_resolving_def_to_ty(self, self, span,
3796 PathParamMode::Optional,
3800 &ty_segments[..base_ty_end],
3801 &ty_segments[base_ty_end..]);
3803 // Resolve an associated constant or method on the previously resolved type.
3804 let item_segment = path.segments.last().unwrap();
3805 let item_name = item_segment.name;
3806 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3809 let def = match error {
3810 method::MethodError::PrivateMatch(def) => def,
3813 if item_name != keywords::Invalid.name() {
3814 self.report_method_error(span, ty, item_name, None, error);
3820 // Write back the new resolution.
3821 self.tcx().def_map.borrow_mut().insert(node_id, PathResolution::new(def));
3822 (def, Some(ty), slice::ref_slice(item_segment))
3826 pub fn check_decl_initializer(&self,
3827 local: &'gcx hir::Local,
3828 init: &'gcx hir::Expr)
3830 let ref_bindings = self.tcx.pat_contains_ref_binding(&local.pat);
3832 let local_ty = self.local_ty(init.span, local.id);
3833 if let Some(m) = ref_bindings {
3834 // Somewhat subtle: if we have a `ref` binding in the pattern,
3835 // we want to avoid introducing coercions for the RHS. This is
3836 // both because it helps preserve sanity and, in the case of
3837 // ref mut, for soundness (issue #23116). In particular, in
3838 // the latter case, we need to be clear that the type of the
3839 // referent for the reference that results is *equal to* the
3840 // type of the lvalue it is referencing, and not some
3841 // supertype thereof.
3842 self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
3843 let init_ty = self.expr_ty(init);
3844 self.demand_eqtype(init.span, init_ty, local_ty);
3846 self.check_expr_coercable_to_type(init, local_ty)
3850 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
3851 let t = self.local_ty(local.span, local.id);
3852 self.write_ty(local.id, t);
3854 if let Some(ref init) = local.init {
3855 self.check_decl_initializer(local, &init);
3856 let init_ty = self.expr_ty(&init);
3857 if init_ty.references_error() {
3858 self.write_ty(local.id, init_ty);
3862 self.check_pat(&local.pat, t);
3863 let pat_ty = self.node_ty(local.pat.id);
3864 if pat_ty.references_error() {
3865 self.write_ty(local.id, pat_ty);
3869 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
3871 let mut saw_bot = false;
3872 let mut saw_err = false;
3874 hir::StmtDecl(ref decl, id) => {
3877 hir::DeclLocal(ref l) => {
3878 self.check_decl_local(&l);
3879 let l_t = self.node_ty(l.id);
3880 saw_bot = saw_bot || self.type_var_diverges(l_t);
3881 saw_err = saw_err || l_t.references_error();
3883 hir::DeclItem(_) => {/* ignore for now */ }
3886 hir::StmtExpr(ref expr, id) => {
3888 // Check with expected type of ()
3889 self.check_expr_has_type(&expr, self.tcx.mk_nil());
3890 let expr_ty = self.expr_ty(&expr);
3891 saw_bot = saw_bot || self.type_var_diverges(expr_ty);
3892 saw_err = saw_err || expr_ty.references_error();
3894 hir::StmtSemi(ref expr, id) => {
3896 self.check_expr(&expr);
3897 let expr_ty = self.expr_ty(&expr);
3898 saw_bot |= self.type_var_diverges(expr_ty);
3899 saw_err |= expr_ty.references_error();
3903 self.write_ty(node_id, self.next_diverging_ty_var());
3906 self.write_error(node_id);
3909 self.write_nil(node_id)
3913 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
3914 self.check_block_with_expected(blk, ExpectHasType(self.tcx.mk_nil()));
3915 let blkty = self.node_ty(blk.id);
3916 if blkty.references_error() {
3917 self.write_error(blk.id);
3919 let nilty = self.tcx.mk_nil();
3920 self.demand_suptype(blk.span, nilty, blkty);
3924 fn check_block_with_expected(&self,
3925 blk: &'gcx hir::Block,
3926 expected: Expectation<'tcx>) {
3928 let mut fcx_ps = self.ps.borrow_mut();
3929 let unsafety_state = fcx_ps.recurse(blk);
3930 replace(&mut *fcx_ps, unsafety_state)
3933 let mut warned = false;
3934 let mut any_diverges = false;
3935 let mut any_err = false;
3936 for s in &blk.stmts {
3938 let s_id = s.node.id();
3939 let s_ty = self.node_ty(s_id);
3940 if any_diverges && !warned && match s.node {
3941 hir::StmtDecl(ref decl, _) => {
3943 hir::DeclLocal(_) => true,
3947 hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
3951 .add_lint(lint::builtin::UNREACHABLE_CODE,
3954 "unreachable statement".to_string());
3957 any_diverges = any_diverges || self.type_var_diverges(s_ty);
3958 any_err = any_err || s_ty.references_error();
3961 None => if any_err {
3962 self.write_error(blk.id);
3963 } else if any_diverges {
3964 self.write_ty(blk.id, self.next_diverging_ty_var());
3966 self.write_nil(blk.id);
3969 if any_diverges && !warned {
3972 .add_lint(lint::builtin::UNREACHABLE_CODE,
3975 "unreachable expression".to_string());
3977 let ety = match expected {
3978 ExpectHasType(ety) => {
3979 self.check_expr_coercable_to_type(&e, ety);
3983 self.check_expr_with_expectation(&e, expected);
3989 self.write_error(blk.id);
3990 } else if any_diverges {
3991 self.write_ty(blk.id, self.next_diverging_ty_var());
3993 self.write_ty(blk.id, ety);
3998 *self.ps.borrow_mut() = prev;
4002 fn check_const_with_ty(&self,
4006 // Gather locals in statics (because of block expressions).
4007 // This is technically unnecessary because locals in static items are forbidden,
4008 // but prevents type checking from blowing up before const checking can properly
4010 GatherLocalsVisitor { fcx: self }.visit_expr(e);
4012 self.check_expr_coercable_to_type(e, declty);
4014 self.select_all_obligations_and_apply_defaults();
4015 self.closure_analyze_const(e);
4016 self.select_obligations_where_possible();
4018 self.select_all_obligations_or_error();
4020 self.regionck_expr(e);
4021 self.resolve_type_vars_in_expr(e);
4024 // Returns the type parameter count and the type for the given definition.
4025 fn type_scheme_and_predicates_for_def(&self,
4028 -> (TypeScheme<'tcx>, GenericPredicates<'tcx>) {
4030 Def::Local(_, nid) | Def::Upvar(_, nid, _, _) => {
4031 let typ = self.local_ty(sp, nid);
4032 (ty::TypeScheme { generics: ty::Generics::empty(), ty: typ },
4033 ty::GenericPredicates::empty())
4035 Def::Fn(id) | Def::Method(id) |
4036 Def::Static(id, _) | Def::Variant(_, id) |
4037 Def::Struct(id) | Def::Const(id) | Def::AssociatedConst(id) => {
4038 (self.tcx.lookup_item_type(id), self.tcx.lookup_predicates(id))
4043 Def::AssociatedTy(..) |
4047 Def::ForeignMod(..) |
4051 span_bug!(sp, "expected value, found {:?}", defn);
4056 // Instantiates the given path, which must refer to an item with the given
4057 // number of type parameters and type.
4058 pub fn instantiate_value_path(&self,
4059 segments: &[hir::PathSegment],
4060 type_scheme: TypeScheme<'tcx>,
4061 type_predicates: &ty::GenericPredicates<'tcx>,
4062 opt_self_ty: Option<Ty<'tcx>>,
4065 node_id: ast::NodeId)
4067 debug!("instantiate_value_path(path={:?}, def={:?}, node_id={}, type_scheme={:?})",
4073 // We need to extract the type parameters supplied by the user in
4074 // the path `path`. Due to the current setup, this is a bit of a
4075 // tricky-process; the problem is that resolve only tells us the
4076 // end-point of the path resolution, and not the intermediate steps.
4077 // Luckily, we can (at least for now) deduce the intermediate steps
4078 // just from the end-point.
4080 // There are basically four cases to consider:
4082 // 1. Reference to a *type*, such as a struct or enum:
4084 // mod a { struct Foo<T> { ... } }
4086 // Because we don't allow types to be declared within one
4087 // another, a path that leads to a type will always look like
4088 // `a::b::Foo<T>` where `a` and `b` are modules. This implies
4089 // that only the final segment can have type parameters, and
4090 // they are located in the TypeSpace.
4092 // *Note:* Generally speaking, references to types don't
4093 // actually pass through this function, but rather the
4094 // `ast_ty_to_ty` function in `astconv`. However, in the case
4095 // of struct patterns (and maybe literals) we do invoke
4096 // `instantiate_value_path` to get the general type of an instance of
4097 // a struct. (In these cases, there are actually no type
4098 // parameters permitted at present, but perhaps we will allow
4099 // them in the future.)
4101 // 1b. Reference to an enum variant or tuple-like struct:
4103 // struct foo<T>(...)
4104 // enum E<T> { foo(...) }
4106 // In these cases, the parameters are declared in the type
4109 // 2. Reference to a *fn item*:
4113 // In this case, the path will again always have the form
4114 // `a::b::foo::<T>` where only the final segment should have
4115 // type parameters. However, in this case, those parameters are
4116 // declared on a value, and hence are in the `FnSpace`.
4118 // 3. Reference to a *method*:
4120 // impl<A> SomeStruct<A> {
4124 // Here we can have a path like
4125 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4126 // may appear in two places. The penultimate segment,
4127 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4128 // final segment, `foo::<B>` contains parameters in fn space.
4130 // 4. Reference to an *associated const*:
4132 // impl<A> AnotherStruct<A> {
4133 // const FOO: B = BAR;
4136 // The path in this case will look like
4137 // `a::b::AnotherStruct::<A>::FOO`, so the penultimate segment
4138 // only will have parameters in TypeSpace.
4140 // The first step then is to categorize the segments appropriately.
4142 assert!(!segments.is_empty());
4144 let mut ufcs_associated = None;
4145 let mut segment_spaces: Vec<_>;
4147 // Case 1 and 1b. Reference to a *type* or *enum variant*.
4153 Def::AssociatedTy(..) |
4156 Def::TyParam(..) => {
4157 // Everything but the final segment should have no
4158 // parameters at all.
4159 segment_spaces = vec![None; segments.len() - 1];
4160 segment_spaces.push(Some(subst::TypeSpace));
4163 // Case 2. Reference to a top-level value.
4166 Def::Static(..) => {
4167 segment_spaces = vec![None; segments.len() - 1];
4168 segment_spaces.push(Some(subst::FnSpace));
4171 // Case 3. Reference to a method.
4172 Def::Method(def_id) => {
4173 let container = self.tcx.impl_or_trait_item(def_id).container();
4175 ty::TraitContainer(trait_did) => {
4176 callee::check_legal_trait_for_method_call(self.ccx, span, trait_did)
4178 ty::ImplContainer(_) => {}
4181 if segments.len() >= 2 {
4182 segment_spaces = vec![None; segments.len() - 2];
4183 segment_spaces.push(Some(subst::TypeSpace));
4184 segment_spaces.push(Some(subst::FnSpace));
4186 // `<T>::method` will end up here, and so can `T::method`.
4187 let self_ty = opt_self_ty.expect("UFCS sugared method missing Self");
4188 segment_spaces = vec![Some(subst::FnSpace)];
4189 ufcs_associated = Some((container, self_ty));
4193 Def::AssociatedConst(def_id) => {
4194 let container = self.tcx.impl_or_trait_item(def_id).container();
4196 ty::TraitContainer(trait_did) => {
4197 callee::check_legal_trait_for_method_call(self.ccx, span, trait_did)
4199 ty::ImplContainer(_) => {}
4202 if segments.len() >= 2 {
4203 segment_spaces = vec![None; segments.len() - 2];
4204 segment_spaces.push(Some(subst::TypeSpace));
4205 segment_spaces.push(None);
4207 // `<T>::CONST` will end up here, and so can `T::CONST`.
4208 let self_ty = opt_self_ty.expect("UFCS sugared const missing Self");
4209 segment_spaces = vec![None];
4210 ufcs_associated = Some((container, self_ty));
4214 // Other cases. Various nonsense that really shouldn't show up
4215 // here. If they do, an error will have been reported
4216 // elsewhere. (I hope)
4218 Def::ForeignMod(..) |
4222 segment_spaces = vec![None; segments.len()];
4226 self.set_tainted_by_errors();
4227 segment_spaces = vec![None; segments.len()];
4230 assert_eq!(segment_spaces.len(), segments.len());
4232 // In `<T as Trait<A, B>>::method`, `A` and `B` are mandatory, but
4233 // `opt_self_ty` can also be Some for `Foo::method`, where Foo's
4234 // type parameters are not mandatory.
4235 let require_type_space = opt_self_ty.is_some() && ufcs_associated.is_none();
4237 debug!("segment_spaces={:?}", segment_spaces);
4239 // Next, examine the definition, and determine how many type
4240 // parameters we expect from each space.
4241 let type_defs = &type_scheme.generics.types;
4242 let region_defs = &type_scheme.generics.regions;
4244 // Now that we have categorized what space the parameters for each
4245 // segment belong to, let's sort out the parameters that the user
4246 // provided (if any) into their appropriate spaces. We'll also report
4247 // errors if type parameters are provided in an inappropriate place.
4248 let mut substs = Substs::empty();
4249 for (&opt_space, segment) in segment_spaces.iter().zip(segments) {
4250 if let Some(space) = opt_space {
4251 self.push_explicit_parameters_from_segment_to_substs(space,
4258 self.tcx.prohibit_type_params(slice::ref_slice(segment));
4261 if let Some(self_ty) = opt_self_ty {
4262 if type_defs.len(subst::SelfSpace) == 1 {
4263 substs.types.push(subst::SelfSpace, self_ty);
4267 // Now we have to compare the types that the user *actually*
4268 // provided against the types that were *expected*. If the user
4269 // did not provide any types, then we want to substitute inference
4270 // variables. If the user provided some types, we may still need
4271 // to add defaults. If the user provided *too many* types, that's
4273 for &space in &[subst::SelfSpace, subst::TypeSpace, subst::FnSpace] {
4274 self.adjust_type_parameters(span, space, type_defs,
4275 require_type_space, &mut substs);
4276 assert_eq!(substs.types.len(space), type_defs.len(space));
4278 self.adjust_region_parameters(span, space, region_defs, &mut substs);
4279 assert_eq!(substs.regions.len(space), region_defs.len(space));
4282 // The things we are substituting into the type should not contain
4283 // escaping late-bound regions, and nor should the base type scheme.
4284 let substs = self.tcx.mk_substs(substs);
4285 assert!(!substs.has_regions_escaping_depth(0));
4286 assert!(!type_scheme.has_escaping_regions());
4288 // Add all the obligations that are required, substituting and
4289 // normalized appropriately.
4290 let bounds = self.instantiate_bounds(span, &substs, &type_predicates);
4291 self.add_obligations_for_parameters(
4292 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4295 // Substitute the values for the type parameters into the type of
4296 // the referenced item.
4297 let ty_substituted = self.instantiate_type_scheme(span, &substs, &type_scheme.ty);
4300 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4301 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4302 // is inherent, there is no `Self` parameter, instead, the impl needs
4303 // type parameters, which we can infer by unifying the provided `Self`
4304 // with the substituted impl type.
4305 let impl_scheme = self.tcx.lookup_item_type(impl_def_id);
4306 assert_eq!(substs.types.len(subst::TypeSpace),
4307 impl_scheme.generics.types.len(subst::TypeSpace));
4308 assert_eq!(substs.regions.len(subst::TypeSpace),
4309 impl_scheme.generics.regions.len(subst::TypeSpace));
4311 let impl_ty = self.instantiate_type_scheme(span, &substs, &impl_scheme.ty);
4312 match self.sub_types(false, TypeOrigin::Misc(span), self_ty, impl_ty) {
4313 Ok(InferOk { obligations, .. }) => {
4314 // FIXME(#32730) propagate obligations
4315 assert!(obligations.is_empty());
4319 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4326 debug!("instantiate_value_path: type of {:?} is {:?}",
4329 self.write_ty(node_id, ty_substituted);
4330 self.write_substs(node_id, ty::ItemSubsts {
4336 /// Finds the parameters that the user provided and adds them to `substs`. If too many
4337 /// parameters are provided, then reports an error and clears the output vector.
4339 /// We clear the output vector because that will cause the `adjust_XXX_parameters()` later to
4340 /// use inference variables. This seems less likely to lead to derived errors.
4342 /// Note that we *do not* check for *too few* parameters here. Due to the presence of defaults
4343 /// etc that is more complicated. I wanted however to do the reporting of *too many* parameters
4344 /// here because we can easily use the precise span of the N+1'th parameter.
4345 fn push_explicit_parameters_from_segment_to_substs(&self,
4346 space: subst::ParamSpace,
4348 type_defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
4349 region_defs: &VecPerParamSpace<ty::RegionParameterDef>,
4350 segment: &hir::PathSegment,
4351 substs: &mut Substs<'tcx>)
4353 match segment.parameters {
4354 hir::AngleBracketedParameters(ref data) => {
4355 self.push_explicit_angle_bracketed_parameters_from_segment_to_substs(
4356 space, type_defs, region_defs, data, substs);
4359 hir::ParenthesizedParameters(ref data) => {
4360 span_err!(self.tcx.sess, span, E0238,
4361 "parenthesized parameters may only be used with a trait");
4362 self.push_explicit_parenthesized_parameters_from_segment_to_substs(
4363 space, span, type_defs, data, substs);
4368 fn push_explicit_angle_bracketed_parameters_from_segment_to_substs(&self,
4369 space: subst::ParamSpace,
4370 type_defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
4371 region_defs: &VecPerParamSpace<ty::RegionParameterDef>,
4372 data: &hir::AngleBracketedParameterData,
4373 substs: &mut Substs<'tcx>)
4376 let type_count = type_defs.len(space);
4377 assert_eq!(substs.types.len(space), 0);
4378 for (i, typ) in data.types.iter().enumerate() {
4379 let t = self.to_ty(&typ);
4381 substs.types.push(space, t);
4382 } else if i == type_count {
4383 struct_span_err!(self.tcx.sess, typ.span, E0087,
4384 "too many type parameters provided: \
4385 expected at most {} parameter{}, \
4386 found {} parameter{}",
4388 if type_count == 1 {""} else {"s"},
4390 if data.types.len() == 1 {""} else {"s"})
4391 .span_label(typ.span , &format!("expected {} parameter{}",
4393 if type_count == 1 {""} else {"s"})).emit();
4394 substs.types.truncate(space, 0);
4400 if !data.bindings.is_empty() {
4401 span_err!(self.tcx.sess, data.bindings[0].span, E0182,
4402 "unexpected binding of associated item in expression path \
4403 (only allowed in type paths)");
4407 let region_count = region_defs.len(space);
4408 assert_eq!(substs.regions.len(space), 0);
4409 for (i, lifetime) in data.lifetimes.iter().enumerate() {
4410 let r = ast_region_to_region(self.tcx, lifetime);
4411 if i < region_count {
4412 substs.regions.push(space, r);
4413 } else if i == region_count {
4414 span_err!(self.tcx.sess, lifetime.span, E0088,
4415 "too many lifetime parameters provided: \
4416 expected {} parameter{}, found {} parameter{}",
4418 if region_count == 1 {""} else {"s"},
4419 data.lifetimes.len(),
4420 if data.lifetimes.len() == 1 {""} else {"s"});
4421 substs.regions.truncate(space, 0);
4429 /// `push_explicit_angle_bracketed_parameters_from_segment_to_substs`,
4430 /// but intended for `Foo(A,B) -> C` form. This expands to
4431 /// roughly the same thing as `Foo<(A,B),C>`. One important
4432 /// difference has to do with the treatment of anonymous
4433 /// regions, which are translated into bound regions (NYI).
4434 fn push_explicit_parenthesized_parameters_from_segment_to_substs(&self,
4435 space: subst::ParamSpace,
4437 type_defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
4438 data: &hir::ParenthesizedParameterData,
4439 substs: &mut Substs<'tcx>)
4441 let type_count = type_defs.len(space);
4443 span_err!(self.tcx.sess, span, E0167,
4444 "parenthesized form always supplies 2 type parameters, \
4445 but only {} parameter(s) were expected",
4449 let input_tys: Vec<Ty> =
4450 data.inputs.iter().map(|ty| self.to_ty(&ty)).collect();
4452 let tuple_ty = self.tcx.mk_tup(input_tys);
4454 if type_count >= 1 {
4455 substs.types.push(space, tuple_ty);
4458 let output_ty: Option<Ty> =
4459 data.output.as_ref().map(|ty| self.to_ty(&ty));
4462 output_ty.unwrap_or(self.tcx.mk_nil());
4464 if type_count >= 2 {
4465 substs.types.push(space, output_ty);
4469 fn adjust_type_parameters(&self,
4472 defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
4473 require_type_space: bool,
4474 substs: &mut Substs<'tcx>)
4476 let provided_len = substs.types.len(space);
4477 let desired = defs.get_slice(space);
4478 let required_len = desired.iter()
4479 .take_while(|d| d.default.is_none())
4482 debug!("adjust_type_parameters(space={:?}, \
4491 // Enforced by `push_explicit_parameters_from_segment_to_substs()`.
4492 assert!(provided_len <= desired.len());
4494 // Nothing specified at all: supply inference variables for
4496 if provided_len == 0 && !(require_type_space && space == subst::TypeSpace) {
4497 substs.types.replace(space, Vec::new());
4498 self.type_vars_for_defs(span, space, substs, &desired[..]);
4502 // Too few parameters specified: report an error and use Err
4504 if provided_len < required_len {
4506 if desired.len() != required_len { "at least " } else { "" };
4507 span_err!(self.tcx.sess, span, E0089,
4508 "too few type parameters provided: expected {}{} parameter{}, \
4509 found {} parameter{}",
4510 qualifier, required_len,
4511 if required_len == 1 {""} else {"s"},
4513 if provided_len == 1 {""} else {"s"});
4514 substs.types.replace(space, vec![self.tcx.types.err; desired.len()]);
4518 // Otherwise, add in any optional parameters that the user
4519 // omitted. The case of *too many* parameters is handled
4521 // push_explicit_parameters_from_segment_to_substs(). Note
4522 // that the *default* type are expressed in terms of all prior
4523 // parameters, so we have to substitute as we go with the
4524 // partial substitution that we have built up.
4525 for i in provided_len..desired.len() {
4526 let default = desired[i].default.unwrap();
4527 let default = default.subst_spanned(self.tcx, substs, Some(span));
4528 substs.types.push(space, default);
4530 assert_eq!(substs.types.len(space), desired.len());
4532 debug!("Final substs: {:?}", substs);
4535 fn adjust_region_parameters(&self,
4538 defs: &VecPerParamSpace<ty::RegionParameterDef>,
4539 substs: &mut Substs)
4541 let provided_len = substs.regions.len(space);
4542 let desired = defs.get_slice(space);
4544 // Enforced by `push_explicit_parameters_from_segment_to_substs()`.
4545 assert!(provided_len <= desired.len());
4547 // If nothing was provided, just use inference variables.
4548 if provided_len == 0 {
4549 substs.regions.replace(
4551 self.region_vars_for_defs(span, desired));
4555 // If just the right number were provided, everybody is happy.
4556 if provided_len == desired.len() {
4560 // Otherwise, too few were provided. Report an error and then
4561 // use inference variables.
4562 span_err!(self.tcx.sess, span, E0090,
4563 "too few lifetime parameters provided: expected {} parameter{}, \
4564 found {} parameter{}",
4566 if desired.len() == 1 {""} else {"s"},
4568 if provided_len == 1 {""} else {"s"});
4570 substs.regions.replace(
4572 self.region_vars_for_defs(span, desired));
4575 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4577 where F: Fn() -> Ty<'tcx>
4579 let mut ty = self.resolve_type_vars_with_obligations(ty);
4582 let alternative = f();
4585 if alternative.is_ty_var() || alternative.references_error() {
4586 if !self.is_tainted_by_errors() {
4587 self.type_error_message(sp, |_actual| {
4588 "the type of this value must be known in this context".to_string()
4591 self.demand_suptype(sp, self.tcx.types.err, ty);
4592 ty = self.tcx.types.err;
4594 self.demand_suptype(sp, alternative, ty);
4602 // Resolves `typ` by a single level if `typ` is a type variable. If no
4603 // resolution is possible, then an error is reported.
4604 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4605 self.structurally_resolve_type_or_else(sp, ty, || {
4611 // Returns true if b contains a break that can exit from b
4612 pub fn may_break(tcx: TyCtxt, id: ast::NodeId, b: &hir::Block) -> bool {
4613 // First: is there an unlabeled break immediately
4615 (loop_query(&b, |e| {
4617 hir::ExprBreak(None) => true,
4621 // Second: is there a labeled break with label
4622 // <id> nested anywhere inside the loop?
4623 (block_query(b, |e| {
4624 if let hir::ExprBreak(Some(_)) = e.node {
4625 tcx.expect_def(e.id) == Def::Label(id)
4632 pub fn check_bounds_are_used<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
4633 tps: &[hir::TyParam],
4635 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4638 // make a vector of booleans initially false, set to true when used
4639 if tps.is_empty() { return; }
4640 let mut tps_used = vec![false; tps.len()];
4642 for leaf_ty in ty.walk() {
4643 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4644 debug!("Found use of ty param num {}", idx);
4645 tps_used[idx as usize] = true;
4649 for (i, b) in tps_used.iter().enumerate() {
4651 span_err!(ccx.tcx.sess, tps[i].span, E0091,
4652 "type parameter `{}` is unused",