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 `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 use self::coercion::CoerceMany;
81 pub use self::compare_method::{compare_impl_method, compare_const_impl};
82 use self::TupleArgumentsFlag::*;
85 use dep_graph::DepNode;
86 use fmt_macros::{Parser, Piece, Position};
87 use hir::def::{Def, CtorKind};
88 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
89 use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin, TypeTrace};
90 use rustc::infer::type_variable::{self, TypeVariableOrigin};
91 use rustc::ty::subst::{Kind, Subst, Substs};
92 use rustc::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
93 use rustc::ty::{ParamTy, ParameterEnvironment};
94 use rustc::ty::{LvaluePreference, NoPreference, PreferMutLvalue};
95 use rustc::ty::{self, Ty, TyCtxt, Visibility};
96 use rustc::ty::{MethodCall, MethodCallee};
97 use rustc::ty::adjustment;
98 use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
99 use rustc::ty::maps::Providers;
100 use rustc::ty::util::{Representability, IntTypeExt};
101 use require_c_abi_if_variadic;
102 use session::{Session, CompileResult};
105 use util::common::{ErrorReported, indenter};
106 use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap};
108 use std::cell::{Cell, RefCell};
110 use std::mem::replace;
111 use std::ops::{self, Deref};
112 use syntax::abi::Abi;
114 use syntax::codemap::{self, original_sp, Spanned};
115 use syntax::feature_gate::{GateIssue, emit_feature_err};
117 use syntax::symbol::{Symbol, InternedString, keywords};
118 use syntax::util::lev_distance::find_best_match_for_name;
119 use syntax_pos::{self, BytePos, Span, DUMMY_SP};
121 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
122 use rustc::hir::itemlikevisit::ItemLikeVisitor;
123 use rustc::hir::{self, PatKind};
124 use rustc::middle::lang_items;
125 use rustc_back::slice;
126 use rustc_const_eval::eval_length;
127 use rustc_const_math::ConstInt;
147 /// closures defined within the function. For example:
150 /// bar(move|| { ... })
153 /// Here, the function `foo()` and the closure passed to
154 /// `bar()` will each have their own `FnCtxt`, but they will
155 /// share the inherited fields.
156 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
157 infcx: InferCtxt<'a, 'gcx, 'tcx>,
159 locals: RefCell<NodeMap<Ty<'tcx>>>,
161 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
163 // When we process a call like `c()` where `c` is a closure type,
164 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
165 // `FnOnce` closure. In that case, we defer full resolution of the
166 // call until upvar inference can kick in and make the
167 // decision. We keep these deferred resolutions grouped by the
168 // def-id of the closure, so that once we decide, we can easily go
169 // back and process them.
170 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>>>,
172 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
174 // Anonymized types found in explicit return types and their
175 // associated fresh inference variable. Writeback resolves these
176 // variables to get the concrete type, which can be used to
177 // deanonymize TyAnon, after typeck is done with all functions.
178 anon_types: RefCell<NodeMap<Ty<'tcx>>>,
181 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
182 type Target = InferCtxt<'a, 'gcx, 'tcx>;
183 fn deref(&self) -> &Self::Target {
188 trait DeferredCallResolution<'gcx, 'tcx> {
189 fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>);
192 type DeferredCallResolutionHandler<'gcx, 'tcx> = Box<DeferredCallResolution<'gcx, 'tcx>+'tcx>;
194 /// When type-checking an expression, we propagate downward
195 /// whatever type hint we are able in the form of an `Expectation`.
196 #[derive(Copy, Clone, Debug)]
197 pub enum Expectation<'tcx> {
198 /// We know nothing about what type this expression should have.
201 /// This expression should have the type given (or some subtype)
202 ExpectHasType(Ty<'tcx>),
204 /// This expression will be cast to the `Ty`
205 ExpectCastableToType(Ty<'tcx>),
207 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
208 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
209 ExpectRvalueLikeUnsized(Ty<'tcx>),
212 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
213 // Disregard "castable to" expectations because they
214 // can lead us astray. Consider for example `if cond
215 // {22} else {c} as u8` -- if we propagate the
216 // "castable to u8" constraint to 22, it will pick the
217 // type 22u8, which is overly constrained (c might not
218 // be a u8). In effect, the problem is that the
219 // "castable to" expectation is not the tightest thing
220 // we can say, so we want to drop it in this case.
221 // The tightest thing we can say is "must unify with
222 // else branch". Note that in the case of a "has type"
223 // constraint, this limitation does not hold.
225 // If the expected type is just a type variable, then don't use
226 // an expected type. Otherwise, we might write parts of the type
227 // when checking the 'then' block which are incompatible with the
229 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
231 ExpectHasType(ety) => {
232 let ety = fcx.shallow_resolve(ety);
233 if !ety.is_ty_var() {
239 ExpectRvalueLikeUnsized(ety) => {
240 ExpectRvalueLikeUnsized(ety)
246 /// Provide an expectation for an rvalue expression given an *optional*
247 /// hint, which is not required for type safety (the resulting type might
248 /// be checked higher up, as is the case with `&expr` and `box expr`), but
249 /// is useful in determining the concrete type.
251 /// The primary use case is where the expected type is a fat pointer,
252 /// like `&[isize]`. For example, consider the following statement:
254 /// let x: &[isize] = &[1, 2, 3];
256 /// In this case, the expected type for the `&[1, 2, 3]` expression is
257 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
258 /// expectation `ExpectHasType([isize])`, that would be too strong --
259 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
260 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
261 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
262 /// which still is useful, because it informs integer literals and the like.
263 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
264 /// for examples of where this comes up,.
265 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
266 match fcx.tcx.struct_tail(ty).sty {
267 ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
268 ExpectRvalueLikeUnsized(ty)
270 _ => ExpectHasType(ty)
274 // Resolves `expected` by a single level if it is a variable. If
275 // there is no expected type or resolution is not possible (e.g.,
276 // no constraints yet present), just returns `None`.
277 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
282 ExpectCastableToType(t) => {
283 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
285 ExpectHasType(t) => {
286 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
288 ExpectRvalueLikeUnsized(t) => {
289 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
294 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
295 match self.resolve(fcx) {
296 NoExpectation => None,
297 ExpectCastableToType(ty) |
299 ExpectRvalueLikeUnsized(ty) => Some(ty),
303 /// It sometimes happens that we want to turn an expectation into
304 /// a **hard constraint** (i.e., something that must be satisfied
305 /// for the program to type-check). `only_has_type` will return
306 /// such a constraint, if it exists.
307 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
308 match self.resolve(fcx) {
309 ExpectHasType(ty) => Some(ty),
314 /// Like `only_has_type`, but instead of returning `None` if no
315 /// hard constraint exists, creates a fresh type variable.
316 fn only_has_type_or_fresh_var(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
317 self.only_has_type(fcx)
318 .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
322 #[derive(Copy, Clone)]
323 pub struct UnsafetyState {
324 pub def: ast::NodeId,
325 pub unsafety: hir::Unsafety,
326 pub unsafe_push_count: u32,
331 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
332 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
335 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
336 match self.unsafety {
337 // If this unsafe, then if the outer function was already marked as
338 // unsafe we shouldn't attribute the unsafe'ness to the block. This
339 // way the block can be warned about instead of ignoring this
340 // extraneous block (functions are never warned about).
341 hir::Unsafety::Unsafe if self.from_fn => *self,
344 let (unsafety, def, count) = match blk.rules {
345 hir::PushUnsafeBlock(..) =>
346 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
347 hir::PopUnsafeBlock(..) =>
348 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
349 hir::UnsafeBlock(..) =>
350 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
352 (unsafety, self.def, self.unsafe_push_count),
354 UnsafetyState{ def: def,
356 unsafe_push_count: count,
363 /// Tracks whether executing a node may exit normally (versus
364 /// return/break/panic, which "diverge", leaving dead code in their
365 /// wake). Tracked semi-automatically (through type variables marked
366 /// as diverging), with some manual adjustments for control-flow
367 /// primitives (approximating a CFG).
368 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
370 /// Potentially unknown, some cases converge,
371 /// others require a CFG to determine them.
374 /// Definitely known to diverge and therefore
375 /// not reach the next sibling or its parent.
378 /// Same as `Always` but with a reachability
379 /// warning already emitted
383 // Convenience impls for combinig `Diverges`.
385 impl ops::BitAnd for Diverges {
387 fn bitand(self, other: Self) -> Self {
388 cmp::min(self, other)
392 impl ops::BitOr for Diverges {
394 fn bitor(self, other: Self) -> Self {
395 cmp::max(self, other)
399 impl ops::BitAndAssign for Diverges {
400 fn bitand_assign(&mut self, other: Self) {
401 *self = *self & other;
405 impl ops::BitOrAssign for Diverges {
406 fn bitor_assign(&mut self, other: Self) {
407 *self = *self | other;
412 fn always(self) -> bool {
413 self >= Diverges::Always
418 pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
421 // this is `null` for loops where break with a value is illegal,
422 // such as `while`, `for`, and `while let`
423 coerce: Option<CoerceMany<'gcx, 'tcx>>,
427 pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
428 stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
429 by_id: NodeMap<usize>,
432 impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
433 fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
434 let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
435 bug!("could not find enclosing breakable with id {}", target_id);
442 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
443 ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
445 body_id: ast::NodeId,
447 // Number of errors that had been reported when we started
448 // checking this function. On exit, if we find that *more* errors
449 // have been reported, we will skip regionck and other work that
450 // expects the types within the function to be consistent.
451 err_count_on_creation: usize,
453 ret_coercion: Option<RefCell<CoerceMany<'gcx, 'tcx>>>,
455 ps: RefCell<UnsafetyState>,
457 /// Whether the last checked node generates a divergence (e.g.,
458 /// `return` will set this to Always). In general, this is
459 /// typically set to *Maybe* on the way **down** the tree, and
460 /// then values are propagated **up** the tree. In a block, we
461 /// combine the results from statements and propagate the
464 /// We use this flag for two purposes:
466 /// - To warn about unreachable code: if, after processing a
467 /// sub-expression but before we have applied the effects of the
468 /// current node, we see that the flag is set to `Always`, we
469 /// can issue a warning. This corresponds to something like
470 /// `foo(return)`; we warn on the `foo()` expression. (We then
471 /// update the flag to `WarnedAlways` to suppress duplicate
472 /// reports.) Similarly, if we traverse to a fresh statement (or
473 /// tail expression) from a `Always` setting, we will isssue a
474 /// warning. This corresponds to something like `{return;
475 /// foo();}` or `{return; 22}`, where we would warn on the
478 /// - To permit assignment into a local variable or other lvalue
479 /// (including the "return slot") of type `!`. This is allowed
480 /// if **either** the type of value being assigned is `!`, which
481 /// means the current code is dead, **or** the expression's
482 /// divering flag is true, which means that a divering value was
483 /// wrapped (e.g., `let x: ! = foo(return)`).
485 /// To repeat the last point: an expression represents dead-code
486 /// if, after checking it, **either** its type is `!` OR the
487 /// diverges flag is set to something other than `Maybe`.
488 diverges: Cell<Diverges>,
490 /// Whether any child nodes have any type errors.
491 has_errors: Cell<bool>,
493 enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
495 inh: &'a Inherited<'a, 'gcx, 'tcx>,
498 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
499 type Target = Inherited<'a, 'gcx, 'tcx>;
500 fn deref(&self) -> &Self::Target {
505 /// Helper type of a temporary returned by Inherited::build(...).
506 /// Necessary because we can't write the following bound:
507 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
508 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
509 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>
512 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
513 pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId)
514 -> InheritedBuilder<'a, 'gcx, 'tcx> {
515 let tables = ty::TypeckTables::empty();
516 let param_env = ParameterEnvironment::for_item(tcx, id);
518 infcx: tcx.infer_ctxt((tables, param_env), Reveal::UserFacing)
523 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
524 fn enter<F, R>(&'tcx mut self, f: F) -> R
525 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
527 self.infcx.enter(|infcx| f(Inherited::new(infcx)))
531 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
532 pub fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>) -> Self {
535 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
536 locals: RefCell::new(NodeMap()),
537 deferred_call_resolutions: RefCell::new(DefIdMap()),
538 deferred_cast_checks: RefCell::new(Vec::new()),
539 anon_types: RefCell::new(NodeMap()),
543 fn normalize_associated_types_in<T>(&self,
545 body_id: ast::NodeId,
548 where T : TypeFoldable<'tcx>
550 assoc::normalize_associated_types_in(self,
551 &mut self.fulfillment_cx.borrow_mut(),
559 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
561 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
562 fn visit_item(&mut self, i: &'tcx hir::Item) {
563 check_item_type(self.tcx, i);
565 fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
566 fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
569 pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
570 tcx.sess.track_errors(|| {
571 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
572 tcx.visit_all_item_likes_in_krate(DepNode::WfCheck, &mut visit.as_deep_visitor());
576 pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
577 tcx.sess.track_errors(|| {
578 tcx.visit_all_item_likes_in_krate(DepNode::TypeckItemType,
579 &mut CheckItemTypesVisitor { tcx });
583 pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
584 ty::queries::typeck_item_bodies::get(tcx, DUMMY_SP, LOCAL_CRATE)
587 fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> CompileResult {
588 debug_assert!(crate_num == LOCAL_CRATE);
589 tcx.sess.track_errors(|| {
590 tcx.visit_all_bodies_in_krate(|body_owner_def_id, _body_id| {
591 tcx.item_tables(body_owner_def_id);
596 pub fn provide(providers: &mut Providers) {
597 *providers = Providers {
607 fn closure_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
609 -> ty::PolyFnSig<'tcx> {
610 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
611 tcx.item_tables(def_id).closure_tys[&node_id]
614 fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
617 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
618 tcx.item_tables(def_id).closure_kinds[&node_id]
621 fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
623 -> Option<ty::Destructor> {
624 tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
627 fn typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
629 -> &'tcx ty::TypeckTables<'tcx> {
630 // Closures' tables come from their outermost function,
631 // as they are part of the same "inference environment".
632 let outer_def_id = tcx.closure_base_def_id(def_id);
633 if outer_def_id != def_id {
634 return tcx.item_tables(outer_def_id);
637 let id = tcx.hir.as_local_node_id(def_id).unwrap();
638 let span = tcx.hir.span(id);
639 let unsupported = || {
640 span_bug!(span, "can't type-check body of {:?}", def_id);
643 // Figure out what primary body this item has.
644 let mut fn_decl = None;
645 let body_id = match tcx.hir.get(id) {
646 hir::map::NodeItem(item) => {
648 hir::ItemConst(_, body) |
649 hir::ItemStatic(_, _, body) => body,
650 hir::ItemFn(ref decl, .., body) => {
651 fn_decl = Some(decl);
657 hir::map::NodeTraitItem(item) => {
659 hir::TraitItemKind::Const(_, Some(body)) => body,
660 hir::TraitItemKind::Method(ref sig,
661 hir::TraitMethod::Provided(body)) => {
662 fn_decl = Some(&sig.decl);
668 hir::map::NodeImplItem(item) => {
670 hir::ImplItemKind::Const(_, body) => body,
671 hir::ImplItemKind::Method(ref sig, body) => {
672 fn_decl = Some(&sig.decl);
678 hir::map::NodeExpr(expr) => {
679 // FIXME(eddyb) Closures should have separate
680 // function definition IDs and expression IDs.
681 // Type-checking should not let closures get
682 // this far in a constant position.
683 // Assume that everything other than closures
684 // is a constant "initializer" expression.
686 hir::ExprClosure(..) => {
687 // We should've bailed out above for closures.
688 span_bug!(expr.span, "unexpected closure")
690 _ => hir::BodyId { node_id: expr.id }
695 let body = tcx.hir.body(body_id);
697 Inherited::build(tcx, id).enter(|inh| {
698 let fcx = if let Some(decl) = fn_decl {
699 let fn_sig = tcx.item_type(def_id).fn_sig();
701 check_abi(tcx, span, fn_sig.abi());
703 // Compute the fty from point of view of inside fn.
704 let fn_scope = inh.tcx.region_maps.call_site_extent(id, body_id.node_id);
706 fn_sig.subst(inh.tcx, &inh.parameter_environment.free_substs);
708 inh.tcx.liberate_late_bound_regions(fn_scope, &fn_sig);
710 inh.normalize_associated_types_in(body.value.span, body_id.node_id, &fn_sig);
712 check_fn(&inh, fn_sig, decl, id, body)
714 let fcx = FnCtxt::new(&inh, body.value.id);
715 let expected_type = tcx.item_type(def_id);
716 let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
717 fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
719 // Gather locals in statics (because of block expressions).
720 // This is technically unnecessary because locals in static items are forbidden,
721 // but prevents type checking from blowing up before const checking can properly
723 GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
725 fcx.check_expr_coercable_to_type(&body.value, expected_type);
730 fcx.select_all_obligations_and_apply_defaults();
731 fcx.closure_analyze(body);
732 fcx.select_obligations_where_possible();
734 fcx.select_all_obligations_or_error();
736 if fn_decl.is_some() {
737 fcx.regionck_fn(id, body);
739 fcx.regionck_expr(body);
742 fcx.resolve_type_vars_in_body(body)
746 fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
747 if !tcx.sess.target.target.is_abi_supported(abi) {
748 struct_span_err!(tcx.sess, span, E0570,
749 "The ABI `{}` is not supported for the current target", abi).emit()
753 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
754 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
757 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
758 fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
761 // infer the variable's type
762 let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
763 self.fcx.locals.borrow_mut().insert(nid, var_ty);
767 // take type that the user specified
768 self.fcx.locals.borrow_mut().insert(nid, typ);
775 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
776 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
777 NestedVisitorMap::None
780 // Add explicitly-declared locals.
781 fn visit_local(&mut self, local: &'gcx hir::Local) {
782 let o_ty = match local.ty {
783 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
786 self.assign(local.span, local.id, o_ty);
787 debug!("Local variable {:?} is assigned type {}",
789 self.fcx.ty_to_string(
790 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
791 intravisit::walk_local(self, local);
794 // Add pattern bindings.
795 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
796 if let PatKind::Binding(_, _, ref path1, _) = p.node {
797 let var_ty = self.assign(p.span, p.id, None);
799 self.fcx.require_type_is_sized(var_ty, p.span,
800 traits::VariableType(p.id));
802 debug!("Pattern binding {} is assigned to {} with type {:?}",
804 self.fcx.ty_to_string(
805 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
808 intravisit::walk_pat(self, p);
811 // Don't descend into the bodies of nested closures
812 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
813 _: hir::BodyId, _: Span, _: ast::NodeId) { }
816 /// Helper used for fns and closures. Does the grungy work of checking a function
817 /// body and returns the function context used for that purpose, since in the case of a fn item
818 /// there is still a bit more to do.
821 /// * inherited: other fields inherited from the enclosing fn (if any)
822 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
823 fn_sig: ty::FnSig<'tcx>,
824 decl: &'gcx hir::FnDecl,
826 body: &'gcx hir::Body)
827 -> FnCtxt<'a, 'gcx, 'tcx>
829 let mut fn_sig = fn_sig.clone();
831 debug!("check_fn(sig={:?}, fn_id={})", fn_sig, fn_id);
833 // Create the function context. This is either derived from scratch or,
834 // in the case of function expressions, based on the outer context.
835 let mut fcx = FnCtxt::new(inherited, body.value.id);
836 *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
838 let ret_ty = fn_sig.output();
839 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
840 let ret_ty = fcx.instantiate_anon_types(&ret_ty);
841 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
842 fn_sig = fcx.tcx.mk_fn_sig(
843 fn_sig.inputs().iter().cloned(),
850 GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
852 // Add formal parameters.
853 for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
854 // The type of the argument must be well-formed.
856 // NB -- this is now checked in wfcheck, but that
857 // currently only results in warnings, so we issue an
858 // old-style WF obligation here so that we still get the
859 // errors that we used to get.
860 fcx.register_old_wf_obligation(arg_ty, arg.pat.span, traits::MiscObligation);
862 // Check the pattern.
863 fcx.check_pat_arg(&arg.pat, arg_ty, true);
864 fcx.write_ty(arg.id, arg_ty);
867 inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig);
869 fcx.check_return_expr(&body.value);
871 // Finalize the return check by taking the LUB of the return types
872 // we saw and assigning it to the expected return type. This isn't
873 // really expected to fail, since the coercions would have failed
874 // earlier when trying to find a LUB.
876 // However, the behavior around `!` is sort of complex. In the
877 // event that the `actual_return_ty` comes back as `!`, that
878 // indicates that the fn either does not return or "returns" only
879 // values of type `!`. In this case, if there is an expected
880 // return type that is *not* `!`, that should be ok. But if the
881 // return type is being inferred, we want to "fallback" to `!`:
883 // let x = move || panic!();
885 // To allow for that, I am creating a type variable with diverging
886 // fallback. This was deemed ever so slightly better than unifying
887 // the return value with `!` because it allows for the caller to
888 // make more assumptions about the return type (e.g., they could do
890 // let y: Option<u32> = Some(x());
892 // which would then cause this return type to become `u32`, not
894 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
895 let mut actual_return_ty = coercion.complete(&fcx);
896 if actual_return_ty.is_never() {
897 actual_return_ty = fcx.next_diverging_ty_var(
898 TypeVariableOrigin::DivergingFn(body.value.span));
900 fcx.demand_suptype(body.value.span, ret_ty, actual_return_ty);
905 fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
908 let def_id = tcx.hir.local_def_id(id);
909 let def = tcx.lookup_adt_def(def_id);
910 def.destructor(tcx); // force the destructor to be evaluated
911 check_representable(tcx, span, def_id);
914 check_simd(tcx, span, def_id);
918 fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
921 let def_id = tcx.hir.local_def_id(id);
922 let def = tcx.lookup_adt_def(def_id);
923 def.destructor(tcx); // force the destructor to be evaluated
924 check_representable(tcx, span, def_id);
927 pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
928 debug!("check_item_type(it.id={}, it.name={})",
930 tcx.item_path_str(tcx.hir.local_def_id(it.id)));
931 let _indenter = indenter();
933 // Consts can play a role in type-checking, so they are included here.
934 hir::ItemStatic(..) |
935 hir::ItemConst(..) => {
936 tcx.item_tables(tcx.hir.local_def_id(it.id));
938 hir::ItemEnum(ref enum_definition, _) => {
941 &enum_definition.variants,
944 hir::ItemFn(..) => {} // entirely within check_item_body
945 hir::ItemImpl(.., ref impl_item_refs) => {
946 debug!("ItemImpl {} with id {}", it.name, it.id);
947 let impl_def_id = tcx.hir.local_def_id(it.id);
948 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
949 check_impl_items_against_trait(tcx,
954 let trait_def_id = impl_trait_ref.def_id;
955 check_on_unimplemented(tcx, trait_def_id, it);
958 hir::ItemTrait(..) => {
959 let def_id = tcx.hir.local_def_id(it.id);
960 check_on_unimplemented(tcx, def_id, it);
962 hir::ItemStruct(..) => {
963 check_struct(tcx, it.id, it.span);
965 hir::ItemUnion(..) => {
966 check_union(tcx, it.id, it.span);
968 hir::ItemTy(_, ref generics) => {
969 let def_id = tcx.hir.local_def_id(it.id);
970 let pty_ty = tcx.item_type(def_id);
971 check_bounds_are_used(tcx, generics, pty_ty);
973 hir::ItemForeignMod(ref m) => {
974 check_abi(tcx, it.span, m.abi);
976 if m.abi == Abi::RustIntrinsic {
977 for item in &m.items {
978 intrinsic::check_intrinsic_type(tcx, item);
980 } else if m.abi == Abi::PlatformIntrinsic {
981 for item in &m.items {
982 intrinsic::check_platform_intrinsic_type(tcx, item);
985 for item in &m.items {
986 let generics = tcx.item_generics(tcx.hir.local_def_id(item.id));
987 if !generics.types.is_empty() {
988 let mut err = struct_span_err!(tcx.sess, item.span, E0044,
989 "foreign items may not have type parameters");
990 span_help!(&mut err, item.span,
991 "consider using specialization instead of \
996 if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
997 require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
1002 _ => {/* nothing to do */ }
1006 fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1009 let generics = tcx.item_generics(def_id);
1010 if let Some(ref attr) = item.attrs.iter().find(|a| {
1011 a.check_name("rustc_on_unimplemented")
1013 if let Some(istring) = attr.value_str() {
1014 let istring = istring.as_str();
1015 let parser = Parser::new(&istring);
1016 let types = &generics.types;
1017 for token in parser {
1019 Piece::String(_) => (), // Normal string, no need to check it
1020 Piece::NextArgument(a) => match a.position {
1021 // `{Self}` is allowed
1022 Position::ArgumentNamed(s) if s == "Self" => (),
1023 // So is `{A}` if A is a type parameter
1024 Position::ArgumentNamed(s) => match types.iter().find(|t| {
1029 let name = tcx.item_name(def_id);
1030 span_err!(tcx.sess, attr.span, E0230,
1031 "there is no type parameter \
1036 // `{:1}` and `{}` are not to be used
1037 Position::ArgumentIs(_) => {
1038 span_err!(tcx.sess, attr.span, E0231,
1039 "only named substitution \
1040 parameters are allowed");
1047 tcx.sess, attr.span, E0232,
1048 "this attribute must have a value")
1049 .span_label(attr.span, &format!("attribute requires a value"))
1050 .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
1056 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1057 impl_item: &hir::ImplItem,
1060 let mut err = struct_span_err!(
1061 tcx.sess, impl_item.span, E0520,
1062 "`{}` specializes an item from a parent `impl`, but \
1063 that item is not marked `default`",
1065 err.span_label(impl_item.span, &format!("cannot specialize default item `{}`",
1068 match tcx.span_of_impl(parent_impl) {
1070 err.span_label(span, &"parent `impl` is here");
1071 err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
1075 err.note(&format!("parent implementation is in crate `{}`", cname));
1082 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1083 trait_def: &ty::TraitDef,
1085 impl_item: &hir::ImplItem)
1087 let ancestors = trait_def.ancestors(impl_id);
1089 let kind = match impl_item.node {
1090 hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
1091 hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
1092 hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
1094 let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
1095 .map(|node_item| node_item.map(|parent| parent.defaultness));
1097 if let Some(parent) = parent {
1098 if parent.item.is_final() {
1099 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1105 fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1108 impl_trait_ref: ty::TraitRef<'tcx>,
1109 impl_item_refs: &[hir::ImplItemRef]) {
1110 // If the trait reference itself is erroneous (so the compilation is going
1111 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1112 // isn't populated for such impls.
1113 if impl_trait_ref.references_error() { return; }
1115 // Locate trait definition and items
1116 let trait_def = tcx.lookup_trait_def(impl_trait_ref.def_id);
1117 let mut overridden_associated_type = None;
1119 let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
1121 // Check existing impl methods to see if they are both present in trait
1122 // and compatible with trait signature
1123 for impl_item in impl_items() {
1124 let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
1125 let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
1126 .find(|ac| ac.name == ty_impl_item.name);
1128 // Check that impl definition matches trait definition
1129 if let Some(ty_trait_item) = ty_trait_item {
1130 match impl_item.node {
1131 hir::ImplItemKind::Const(..) => {
1132 // Find associated const definition.
1133 if ty_trait_item.kind == ty::AssociatedKind::Const {
1134 compare_const_impl(tcx,
1140 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1141 "item `{}` is an associated const, \
1142 which doesn't match its trait `{}`",
1145 err.span_label(impl_item.span, &format!("does not match trait"));
1146 // We can only get the spans from local trait definition
1147 // Same for E0324 and E0325
1148 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1149 err.span_label(trait_span, &format!("item in trait"));
1154 hir::ImplItemKind::Method(_, body_id) => {
1155 let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
1156 if ty_trait_item.kind == ty::AssociatedKind::Method {
1157 let err_count = tcx.sess.err_count();
1158 compare_impl_method(tcx,
1165 true); // start with old-broken-mode
1166 if err_count == tcx.sess.err_count() {
1167 // old broken mode did not report an error. Try with the new mode.
1168 compare_impl_method(tcx,
1175 false); // use the new mode
1178 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1179 "item `{}` is an associated method, \
1180 which doesn't match its trait `{}`",
1183 err.span_label(impl_item.span, &format!("does not match trait"));
1184 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1185 err.span_label(trait_span, &format!("item in trait"));
1190 hir::ImplItemKind::Type(_) => {
1191 if ty_trait_item.kind == ty::AssociatedKind::Type {
1192 if ty_trait_item.defaultness.has_value() {
1193 overridden_associated_type = Some(impl_item);
1196 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1197 "item `{}` is an associated type, \
1198 which doesn't match its trait `{}`",
1201 err.span_label(impl_item.span, &format!("does not match trait"));
1202 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1203 err.span_label(trait_span, &format!("item in trait"));
1211 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1214 // Check for missing items from trait
1215 let mut missing_items = Vec::new();
1216 let mut invalidated_items = Vec::new();
1217 let associated_type_overridden = overridden_associated_type.is_some();
1218 for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
1219 let is_implemented = trait_def.ancestors(impl_id)
1220 .defs(tcx, trait_item.name, trait_item.kind)
1222 .map(|node_item| !node_item.node.is_from_trait())
1225 if !is_implemented {
1226 if !trait_item.defaultness.has_value() {
1227 missing_items.push(trait_item);
1228 } else if associated_type_overridden {
1229 invalidated_items.push(trait_item.name);
1234 let signature = |item: &ty::AssociatedItem| {
1236 ty::AssociatedKind::Method => {
1237 format!("{}", tcx.item_type(item.def_id).fn_sig().0)
1239 ty::AssociatedKind::Type => format!("type {};", item.name.to_string()),
1240 ty::AssociatedKind::Const => {
1241 format!("const {}: {:?};", item.name.to_string(), tcx.item_type(item.def_id))
1246 if !missing_items.is_empty() {
1247 let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
1248 "not all trait items implemented, missing: `{}`",
1249 missing_items.iter()
1250 .map(|trait_item| trait_item.name.to_string())
1251 .collect::<Vec<_>>().join("`, `"));
1252 err.span_label(impl_span, &format!("missing `{}` in implementation",
1253 missing_items.iter()
1254 .map(|trait_item| trait_item.name.to_string())
1255 .collect::<Vec<_>>().join("`, `")));
1256 for trait_item in missing_items {
1257 if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
1258 err.span_label(span, &format!("`{}` from trait", trait_item.name));
1260 err.note(&format!("`{}` from trait: `{}`",
1262 signature(&trait_item)));
1268 if !invalidated_items.is_empty() {
1269 let invalidator = overridden_associated_type.unwrap();
1270 span_err!(tcx.sess, invalidator.span, E0399,
1271 "the following trait items need to be reimplemented \
1272 as `{}` was overridden: `{}`",
1274 invalidated_items.iter()
1275 .map(|name| name.to_string())
1276 .collect::<Vec<_>>().join("`, `"))
1280 /// Checks whether a type can be represented in memory. In particular, it
1281 /// identifies types that contain themselves without indirection through a
1282 /// pointer, which would mean their size is unbounded.
1283 fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1287 let rty = tcx.item_type(item_def_id);
1289 // Check that it is possible to represent this type. This call identifies
1290 // (1) types that contain themselves and (2) types that contain a different
1291 // recursive type. It is only necessary to throw an error on those that
1292 // contain themselves. For case 2, there must be an inner type that will be
1293 // caught by case 1.
1294 match rty.is_representable(tcx, sp) {
1295 Representability::SelfRecursive => {
1296 tcx.recursive_type_with_infinite_size_error(item_def_id).emit();
1299 Representability::Representable | Representability::ContainsRecursive => (),
1304 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1305 let t = tcx.item_type(def_id);
1307 ty::TyAdt(def, substs) if def.is_struct() => {
1308 let fields = &def.struct_variant().fields;
1309 if fields.is_empty() {
1310 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1313 let e = fields[0].ty(tcx, substs);
1314 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1315 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1316 .span_label(sp, &format!("SIMD elements must have the same type"))
1321 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1322 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1324 span_err!(tcx.sess, sp, E0077,
1325 "SIMD vector element type should be machine type");
1334 #[allow(trivial_numeric_casts)]
1335 pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1337 vs: &'tcx [hir::Variant],
1339 let def_id = tcx.hir.local_def_id(id);
1340 let def = tcx.lookup_adt_def(def_id);
1341 def.destructor(tcx); // force the destructor to be evaluated
1343 if vs.is_empty() && tcx.has_attr(def_id, "repr") {
1345 tcx.sess, sp, E0084,
1346 "unsupported representation for zero-variant enum")
1347 .span_label(sp, &format!("unsupported enum representation"))
1351 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1352 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1353 if !tcx.sess.features.borrow().i128_type {
1354 emit_feature_err(&tcx.sess.parse_sess,
1355 "i128_type", sp, GateIssue::Language, "128-bit type is unstable");
1360 if let Some(e) = v.node.disr_expr {
1361 tcx.item_tables(tcx.hir.local_def_id(e.node_id));
1365 let mut disr_vals: Vec<ConstInt> = Vec::new();
1366 for (discr, v) in def.discriminants(tcx).zip(vs) {
1367 // Check for duplicate discriminant values
1368 if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
1369 let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
1370 let variant_i = tcx.hir.expect_variant(variant_i_node_id);
1371 let i_span = match variant_i.node.disr_expr {
1372 Some(expr) => tcx.hir.span(expr.node_id),
1373 None => tcx.hir.span(variant_i_node_id)
1375 let span = match v.node.disr_expr {
1376 Some(expr) => tcx.hir.span(expr.node_id),
1379 struct_span_err!(tcx.sess, span, E0081,
1380 "discriminant value `{}` already exists", disr_vals[i])
1381 .span_label(i_span, &format!("first use of `{}`", disr_vals[i]))
1382 .span_label(span , &format!("enum already has `{}`", disr_vals[i]))
1385 disr_vals.push(discr);
1388 check_representable(tcx, sp, def_id);
1391 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1392 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1394 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> {
1395 &self.ast_ty_to_ty_cache
1398 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
1399 Some(&self.parameter_environment.free_substs)
1402 fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
1403 -> ty::GenericPredicates<'tcx>
1406 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1407 let item_id = tcx.hir.ty_param_owner(node_id);
1408 let item_def_id = tcx.hir.local_def_id(item_id);
1409 let generics = tcx.item_generics(item_def_id);
1410 let index = generics.type_param_to_index[&def_id.index];
1411 ty::GenericPredicates {
1413 predicates: self.parameter_environment.caller_bounds.iter().filter(|predicate| {
1415 ty::Predicate::Trait(ref data) => {
1416 data.0.self_ty().is_param(index)
1420 }).cloned().collect()
1424 fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
1425 -> Option<&'tcx ty::Region> {
1427 Some(def) => infer::EarlyBoundRegion(span, def.name, def.issue_32330),
1428 None => infer::MiscVariable(span)
1430 Some(self.next_region_var(v))
1433 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
1434 self.next_ty_var(TypeVariableOrigin::TypeInference(span))
1437 fn ty_infer_for_def(&self,
1438 ty_param_def: &ty::TypeParameterDef,
1439 substs: &[Kind<'tcx>],
1440 span: Span) -> Ty<'tcx> {
1441 self.type_var_for_def(span, ty_param_def, substs)
1444 fn projected_ty_from_poly_trait_ref(&self,
1446 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1447 item_name: ast::Name)
1450 let (trait_ref, _) =
1451 self.replace_late_bound_regions_with_fresh_var(
1453 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1456 self.tcx().mk_projection(trait_ref, item_name)
1459 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1460 if ty.has_escaping_regions() {
1461 ty // FIXME: normalization and escaping regions
1463 self.normalize_associated_types_in(span, &ty)
1467 fn set_tainted_by_errors(&self) {
1468 self.infcx.set_tainted_by_errors()
1472 /// Controls whether the arguments are tupled. This is used for the call
1475 /// Tupling means that all call-side arguments are packed into a tuple and
1476 /// passed as a single parameter. For example, if tupling is enabled, this
1479 /// fn f(x: (isize, isize))
1481 /// Can be called as:
1488 #[derive(Clone, Eq, PartialEq)]
1489 enum TupleArgumentsFlag {
1494 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1495 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1496 body_id: ast::NodeId)
1497 -> FnCtxt<'a, 'gcx, 'tcx> {
1499 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
1501 err_count_on_creation: inh.tcx.sess.err_count(),
1503 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
1504 ast::CRATE_NODE_ID)),
1505 diverges: Cell::new(Diverges::Maybe),
1506 has_errors: Cell::new(false),
1507 enclosing_breakables: RefCell::new(EnclosingBreakables {
1515 pub fn sess(&self) -> &Session {
1519 pub fn err_count_since_creation(&self) -> usize {
1520 self.tcx.sess.err_count() - self.err_count_on_creation
1523 /// Produce warning on the given node, if the current point in the
1524 /// function is unreachable, and there hasn't been another warning.
1525 fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
1526 if self.diverges.get() == Diverges::Always {
1527 self.diverges.set(Diverges::WarnedAlways);
1529 self.tables.borrow_mut().lints.add_lint(
1530 lint::builtin::UNREACHABLE_CODE,
1532 format!("unreachable {}", kind));
1538 code: ObligationCauseCode<'tcx>)
1539 -> ObligationCause<'tcx> {
1540 ObligationCause::new(span, self.body_id, code)
1543 pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
1544 self.cause(span, ObligationCauseCode::MiscObligation)
1547 /// Resolves type variables in `ty` if possible. Unlike the infcx
1548 /// version (resolve_type_vars_if_possible), this version will
1549 /// also select obligations if it seems useful, in an effort
1550 /// to get more type information.
1551 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1552 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1554 // No TyInfer()? Nothing needs doing.
1555 if !ty.has_infer_types() {
1556 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1560 // If `ty` is a type variable, see whether we already know what it is.
1561 ty = self.resolve_type_vars_if_possible(&ty);
1562 if !ty.has_infer_types() {
1563 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1567 // If not, try resolving pending obligations as much as
1568 // possible. This can help substantially when there are
1569 // indirect dependencies that don't seem worth tracking
1571 self.select_obligations_where_possible();
1572 ty = self.resolve_type_vars_if_possible(&ty);
1574 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1578 fn record_deferred_call_resolution(&self,
1579 closure_def_id: DefId,
1580 r: DeferredCallResolutionHandler<'gcx, 'tcx>) {
1581 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1582 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1585 fn remove_deferred_call_resolutions(&self,
1586 closure_def_id: DefId)
1587 -> Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>
1589 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1590 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(Vec::new())
1593 pub fn tag(&self) -> String {
1594 let self_ptr: *const FnCtxt = self;
1595 format!("{:?}", self_ptr)
1598 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1599 match self.locals.borrow().get(&nid) {
1602 span_bug!(span, "no type for local variable {}",
1603 self.tcx.hir.node_to_string(nid));
1609 pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
1610 debug!("write_ty({}, {:?}) in fcx {}",
1611 node_id, self.resolve_type_vars_if_possible(&ty), self.tag());
1612 self.tables.borrow_mut().node_types.insert(node_id, ty);
1614 if ty.references_error() {
1615 self.has_errors.set(true);
1616 self.set_tainted_by_errors();
1620 pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
1621 if !substs.substs.is_noop() {
1622 debug!("write_substs({}, {:?}) in fcx {}",
1627 self.tables.borrow_mut().item_substs.insert(node_id, substs);
1631 pub fn write_autoderef_adjustment(&self,
1632 node_id: ast::NodeId,
1634 adjusted_ty: Ty<'tcx>) {
1635 self.write_adjustment(node_id, adjustment::Adjustment {
1636 kind: adjustment::Adjust::DerefRef {
1645 pub fn write_adjustment(&self,
1646 node_id: ast::NodeId,
1647 adj: adjustment::Adjustment<'tcx>) {
1648 debug!("write_adjustment(node_id={}, adj={:?})", node_id, adj);
1650 if adj.is_identity() {
1654 self.tables.borrow_mut().adjustments.insert(node_id, adj);
1657 /// Basically whenever we are converting from a type scheme into
1658 /// the fn body space, we always want to normalize associated
1659 /// types as well. This function combines the two.
1660 fn instantiate_type_scheme<T>(&self,
1662 substs: &Substs<'tcx>,
1665 where T : TypeFoldable<'tcx>
1667 let value = value.subst(self.tcx, substs);
1668 let result = self.normalize_associated_types_in(span, &value);
1669 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1676 /// As `instantiate_type_scheme`, but for the bounds found in a
1677 /// generic type scheme.
1678 fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
1679 -> ty::InstantiatedPredicates<'tcx> {
1680 let bounds = self.tcx.item_predicates(def_id);
1681 let result = bounds.instantiate(self.tcx, substs);
1682 let result = self.normalize_associated_types_in(span, &result.predicates);
1683 debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
1687 ty::InstantiatedPredicates {
1692 /// Replace all anonymized types with fresh inference variables
1693 /// and record them for writeback.
1694 fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
1695 value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
1696 if let ty::TyAnon(def_id, substs) = ty.sty {
1697 // Use the same type variable if the exact same TyAnon appears more
1698 // than once in the return type (e.g. if it's pased to a type alias).
1699 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1700 if let Some(ty_var) = self.anon_types.borrow().get(&id) {
1703 let span = self.tcx.def_span(def_id);
1704 let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
1705 self.anon_types.borrow_mut().insert(id, ty_var);
1707 let item_predicates = self.tcx.item_predicates(def_id);
1708 let bounds = item_predicates.instantiate(self.tcx, substs);
1710 for predicate in bounds.predicates {
1711 // Change the predicate to refer to the type variable,
1712 // which will be the concrete type, instead of the TyAnon.
1713 // This also instantiates nested `impl Trait`.
1714 let predicate = self.instantiate_anon_types(&predicate);
1716 // Require that the predicate holds for the concrete type.
1717 let cause = traits::ObligationCause::new(span, self.body_id,
1718 traits::ReturnType);
1719 self.register_predicate(traits::Obligation::new(cause, predicate));
1729 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1730 where T : TypeFoldable<'tcx>
1732 self.inh.normalize_associated_types_in(span, self.body_id, value)
1735 pub fn write_nil(&self, node_id: ast::NodeId) {
1736 self.write_ty(node_id, self.tcx.mk_nil());
1739 pub fn write_error(&self, node_id: ast::NodeId) {
1740 self.write_ty(node_id, self.tcx.types.err);
1743 pub fn require_type_meets(&self,
1746 code: traits::ObligationCauseCode<'tcx>,
1749 self.register_bound(
1752 traits::ObligationCause::new(span, self.body_id, code));
1755 pub fn require_type_is_sized(&self,
1758 code: traits::ObligationCauseCode<'tcx>)
1760 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1761 self.require_type_meets(ty, span, code, lang_item);
1764 pub fn register_bound(&self,
1767 cause: traits::ObligationCause<'tcx>)
1769 self.fulfillment_cx.borrow_mut()
1770 .register_bound(self, ty, def_id, cause);
1773 pub fn register_predicate(&self,
1774 obligation: traits::PredicateObligation<'tcx>)
1776 debug!("register_predicate({:?})", obligation);
1777 if obligation.has_escaping_regions() {
1778 span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
1783 .register_predicate_obligation(self, obligation);
1786 pub fn register_predicates(&self,
1787 obligations: Vec<traits::PredicateObligation<'tcx>>)
1789 for obligation in obligations {
1790 self.register_predicate(obligation);
1794 pub fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
1795 self.register_predicates(infer_ok.obligations);
1799 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
1800 let t = AstConv::ast_ty_to_ty(self, ast_t);
1801 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1805 pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
1806 match self.tables.borrow().node_types.get(&id) {
1808 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1810 bug!("no type for node {}: {} in fcx {}",
1811 id, self.tcx.hir.node_to_string(id),
1817 pub fn opt_node_ty_substs<F>(&self,
1820 F: FnOnce(&ty::ItemSubsts<'tcx>),
1822 if let Some(s) = self.tables.borrow().item_substs.get(&id) {
1827 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1828 /// outlive the region `r`.
1829 pub fn register_region_obligation(&self,
1831 region: &'tcx ty::Region,
1832 cause: traits::ObligationCause<'tcx>)
1834 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
1835 fulfillment_cx.register_region_obligation(ty, region, cause);
1838 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1839 /// outlive the region `r`.
1840 pub fn register_wf_obligation(&self,
1843 code: traits::ObligationCauseCode<'tcx>)
1845 // WF obligations never themselves fail, so no real need to give a detailed cause:
1846 let cause = traits::ObligationCause::new(span, self.body_id, code);
1847 self.register_predicate(traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
1850 pub fn register_old_wf_obligation(&self,
1853 code: traits::ObligationCauseCode<'tcx>)
1855 // Registers an "old-style" WF obligation that uses the
1856 // implicator code. This is basically a buggy version of
1857 // `register_wf_obligation` that is being kept around
1858 // temporarily just to help with phasing in the newer rules.
1860 // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
1861 let cause = traits::ObligationCause::new(span, self.body_id, code);
1862 self.register_region_obligation(ty, self.tcx.mk_region(ty::ReEmpty), cause);
1865 /// Registers obligations that all types appearing in `substs` are well-formed.
1866 pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
1868 for ty in substs.types() {
1869 self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
1873 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
1874 /// type/region parameter was instantiated (`substs`), creates and registers suitable
1875 /// trait/region obligations.
1877 /// For example, if there is a function:
1880 /// fn foo<'a,T:'a>(...)
1883 /// and a reference:
1889 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
1890 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
1891 pub fn add_obligations_for_parameters(&self,
1892 cause: traits::ObligationCause<'tcx>,
1893 predicates: &ty::InstantiatedPredicates<'tcx>)
1895 assert!(!predicates.has_escaping_regions());
1897 debug!("add_obligations_for_parameters(predicates={:?})",
1900 for obligation in traits::predicates_for_generics(cause, predicates) {
1901 self.register_predicate(obligation);
1905 // FIXME(arielb1): use this instead of field.ty everywhere
1906 // Only for fields! Returns <none> for methods>
1907 // Indifferent to privacy flags
1908 pub fn field_ty(&self,
1910 field: &'tcx ty::FieldDef,
1911 substs: &Substs<'tcx>)
1914 self.normalize_associated_types_in(span,
1915 &field.ty(self.tcx, substs))
1918 fn check_casts(&self) {
1919 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1920 for cast in deferred_cast_checks.drain(..) {
1925 /// Apply "fallbacks" to some types
1926 /// unconstrained types get replaced with ! or () (depending on whether
1927 /// feature(never_type) is enabled), unconstrained ints with i32, and
1928 /// unconstrained floats with f64.
1929 fn default_type_parameters(&self) {
1930 use rustc::ty::error::UnconstrainedNumeric::Neither;
1931 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
1933 // Defaulting inference variables becomes very dubious if we have
1934 // encountered type-checking errors. Therefore, if we think we saw
1935 // some errors in this function, just resolve all uninstanted type
1936 // varibles to TyError.
1937 if self.is_tainted_by_errors() {
1938 for ty in &self.unsolved_variables() {
1939 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
1940 debug!("default_type_parameters: defaulting `{:?}` to error", ty);
1941 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
1947 for ty in &self.unsolved_variables() {
1948 let resolved = self.resolve_type_vars_if_possible(ty);
1949 if self.type_var_diverges(resolved) {
1950 debug!("default_type_parameters: defaulting `{:?}` to `!` because it diverges",
1952 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
1953 self.tcx.mk_diverging_default());
1955 match self.type_is_unconstrained_numeric(resolved) {
1956 UnconstrainedInt => {
1957 debug!("default_type_parameters: defaulting `{:?}` to `i32`",
1959 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
1961 UnconstrainedFloat => {
1962 debug!("default_type_parameters: defaulting `{:?}` to `f32`",
1964 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
1972 fn select_all_obligations_and_apply_defaults(&self) {
1973 if self.tcx.sess.features.borrow().default_type_parameter_fallback {
1974 self.new_select_all_obligations_and_apply_defaults();
1976 self.old_select_all_obligations_and_apply_defaults();
1980 // Implements old type inference fallback algorithm
1981 fn old_select_all_obligations_and_apply_defaults(&self) {
1982 self.select_obligations_where_possible();
1983 self.default_type_parameters();
1984 self.select_obligations_where_possible();
1987 fn new_select_all_obligations_and_apply_defaults(&self) {
1988 use rustc::ty::error::UnconstrainedNumeric::Neither;
1989 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
1991 // For the time being this errs on the side of being memory wasteful but provides better
1993 // let type_variables = self.type_variables.clone();
1995 // There is a possibility that this algorithm will have to run an arbitrary number of times
1996 // to terminate so we bound it by the compiler's recursion limit.
1997 for _ in 0..self.tcx.sess.recursion_limit.get() {
1998 // First we try to solve all obligations, it is possible that the last iteration
1999 // has made it possible to make more progress.
2000 self.select_obligations_where_possible();
2002 let mut conflicts = Vec::new();
2004 // Collect all unsolved type, integral and floating point variables.
2005 let unsolved_variables = self.unsolved_variables();
2007 // We must collect the defaults *before* we do any unification. Because we have
2008 // directly attached defaults to the type variables any unification that occurs
2009 // will erase defaults causing conflicting defaults to be completely ignored.
2010 let default_map: FxHashMap<Ty<'tcx>, _> =
2013 .filter_map(|t| self.default(t).map(|d| (*t, d)))
2016 let mut unbound_tyvars = FxHashSet();
2018 debug!("select_all_obligations_and_apply_defaults: defaults={:?}", default_map);
2020 // We loop over the unsolved variables, resolving them and if they are
2021 // and unconstrainted numeric type we add them to the set of unbound
2022 // variables. We do this so we only apply literal fallback to type
2023 // variables without defaults.
2024 for ty in &unsolved_variables {
2025 let resolved = self.resolve_type_vars_if_possible(ty);
2026 if self.type_var_diverges(resolved) {
2027 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
2028 self.tcx.mk_diverging_default());
2030 match self.type_is_unconstrained_numeric(resolved) {
2031 UnconstrainedInt | UnconstrainedFloat => {
2032 unbound_tyvars.insert(resolved);
2039 // We now remove any numeric types that also have defaults, and instead insert
2040 // the type variable with a defined fallback.
2041 for ty in &unsolved_variables {
2042 if let Some(_default) = default_map.get(ty) {
2043 let resolved = self.resolve_type_vars_if_possible(ty);
2045 debug!("select_all_obligations_and_apply_defaults: \
2046 ty: {:?} with default: {:?}",
2049 match resolved.sty {
2050 ty::TyInfer(ty::TyVar(_)) => {
2051 unbound_tyvars.insert(ty);
2054 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) => {
2055 unbound_tyvars.insert(ty);
2056 if unbound_tyvars.contains(resolved) {
2057 unbound_tyvars.remove(resolved);
2066 // If there are no more fallbacks to apply at this point we have applied all possible
2067 // defaults and type inference will proceed as normal.
2068 if unbound_tyvars.is_empty() {
2072 // Finally we go through each of the unbound type variables and unify them with
2073 // the proper fallback, reporting a conflicting default error if any of the
2074 // unifications fail. We know it must be a conflicting default because the
2075 // variable would only be in `unbound_tyvars` and have a concrete value if
2076 // it had been solved by previously applying a default.
2078 // We wrap this in a transaction for error reporting, if we detect a conflict
2079 // we will rollback the inference context to its prior state so we can probe
2080 // for conflicts and correctly report them.
2082 let _ = self.commit_if_ok(|_: &infer::CombinedSnapshot| {
2084 self.apply_defaults_and_return_conflicts(&unbound_tyvars, &default_map, None)
2087 // If there are conflicts we rollback, otherwise commit
2088 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.apply_defaults_and_return_conflicts(
2106 .unwrap_or(type_variable::Default {
2107 ty: self.next_ty_var(
2108 TypeVariableOrigin::MiscVariable(syntax_pos::DUMMY_SP)),
2109 origin_span: syntax_pos::DUMMY_SP,
2110 // what do I put here?
2111 def_id: self.tcx.hir.local_def_id(ast::CRATE_NODE_ID)
2114 // This is to ensure that we elimnate any non-determinism from the error
2115 // reporting by fixing an order, it doesn't matter what order we choose
2116 // just that it is consistent.
2117 let (first_default, second_default) =
2118 if default.def_id < conflicting_default.def_id {
2119 (default, conflicting_default)
2121 (conflicting_default, default)
2125 self.report_conflicting_default_types(
2126 first_default.origin_span,
2133 self.select_obligations_where_possible();
2136 // For use in error handling related to default type parameter fallback. We explicitly
2137 // apply the default that caused conflict first to a local version of the type variable
2138 // table then apply defaults until we find a conflict. That default must be the one
2139 // that caused conflict earlier.
2140 fn apply_defaults_and_return_conflicts<'b>(
2142 unbound_vars: &'b FxHashSet<Ty<'tcx>>,
2143 default_map: &'b FxHashMap<Ty<'tcx>, type_variable::Default<'tcx>>,
2144 conflict: Option<Ty<'tcx>>,
2145 ) -> impl Iterator<Item=(Ty<'tcx>, type_variable::Default<'tcx>)> + 'b {
2146 use rustc::ty::error::UnconstrainedNumeric::Neither;
2147 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
2149 conflict.into_iter().chain(unbound_vars.iter().cloned()).flat_map(move |ty| {
2150 if self.type_var_diverges(ty) {
2151 self.demand_eqtype(syntax_pos::DUMMY_SP, ty,
2152 self.tcx.mk_diverging_default());
2154 match self.type_is_unconstrained_numeric(ty) {
2155 UnconstrainedInt => {
2156 self.demand_eqtype(syntax_pos::DUMMY_SP, ty, self.tcx.types.i32)
2158 UnconstrainedFloat => {
2159 self.demand_eqtype(syntax_pos::DUMMY_SP, ty, self.tcx.types.f64)
2162 if let Some(default) = default_map.get(ty) {
2163 let default = default.clone();
2164 let default_ty = self.normalize_associated_types_in(
2165 default.origin_span, &default.ty);
2166 match self.eq_types(false,
2167 &self.misc(default.origin_span),
2170 Ok(ok) => self.register_infer_ok_obligations(ok),
2172 return Some((ty, default));
2184 fn select_all_obligations_or_error(&self) {
2185 debug!("select_all_obligations_or_error");
2187 // upvar inference should have ensured that all deferred call
2188 // resolutions are handled by now.
2189 assert!(self.deferred_call_resolutions.borrow().is_empty());
2191 self.select_all_obligations_and_apply_defaults();
2193 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2195 match fulfillment_cx.select_all_or_error(self) {
2197 Err(errors) => { self.report_fulfillment_errors(&errors); }
2201 /// Select as many obligations as we can at present.
2202 fn select_obligations_where_possible(&self) {
2203 match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
2205 Err(errors) => { self.report_fulfillment_errors(&errors); }
2209 /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2210 /// returns a type of `&T`, but the actual type we assign to the
2211 /// *expression* is `T`. So this function just peels off the return
2212 /// type by one layer to yield `T`.
2213 fn make_overloaded_lvalue_return_type(&self,
2214 method: MethodCallee<'tcx>)
2215 -> ty::TypeAndMut<'tcx>
2217 // extract method return type, which will be &T;
2218 // all LB regions should have been instantiated during method lookup
2219 let ret_ty = method.ty.fn_ret();
2220 let ret_ty = self.tcx.no_late_bound_regions(&ret_ty).unwrap();
2222 // method returns &T, but the type as visible to user is T, so deref
2223 ret_ty.builtin_deref(true, NoPreference).unwrap()
2226 fn lookup_indexing(&self,
2228 base_expr: &'gcx hir::Expr,
2231 lvalue_pref: LvaluePreference)
2232 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2234 // FIXME(#18741) -- this is almost but not quite the same as the
2235 // autoderef that normal method probing does. They could likely be
2238 let mut autoderef = self.autoderef(base_expr.span, base_ty);
2240 while let Some((adj_ty, autoderefs)) = autoderef.next() {
2241 if let Some(final_mt) = self.try_index_step(
2242 MethodCall::expr(expr.id),
2243 expr, base_expr, adj_ty, autoderefs,
2244 false, lvalue_pref, idx_ty)
2246 autoderef.finalize(lvalue_pref, Some(base_expr));
2247 return Some(final_mt);
2250 if let ty::TyArray(element_ty, _) = adj_ty.sty {
2251 autoderef.finalize(lvalue_pref, Some(base_expr));
2252 let adjusted_ty = self.tcx.mk_slice(element_ty);
2253 return self.try_index_step(
2254 MethodCall::expr(expr.id), expr, base_expr,
2255 adjusted_ty, autoderefs, true, lvalue_pref, idx_ty);
2258 autoderef.unambiguous_final_ty();
2262 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2263 /// (and otherwise adjust) `base_expr`, looking for a type which either
2264 /// supports builtin indexing or overloaded indexing.
2265 /// This loop implements one step in that search; the autoderef loop
2266 /// is implemented by `lookup_indexing`.
2267 fn try_index_step(&self,
2268 method_call: MethodCall,
2270 base_expr: &'gcx hir::Expr,
2271 adjusted_ty: Ty<'tcx>,
2274 lvalue_pref: LvaluePreference,
2276 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2279 debug!("try_index_step(expr={:?}, base_expr.id={:?}, adjusted_ty={:?}, \
2280 autoderefs={}, unsize={}, index_ty={:?})",
2288 let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_expr.span));
2290 // First, try built-in indexing.
2291 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2292 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2293 debug!("try_index_step: success, using built-in indexing");
2294 // If we had `[T; N]`, we should've caught it before unsizing to `[T]`.
2296 self.write_autoderef_adjustment(base_expr.id, autoderefs, adjusted_ty);
2297 return Some((tcx.types.usize, ty));
2302 // Try `IndexMut` first, if preferred.
2303 let method = match (lvalue_pref, tcx.lang_items.index_mut_trait()) {
2304 (PreferMutLvalue, Some(trait_did)) => {
2305 self.lookup_method_in_trait_adjusted(expr.span,
2307 Symbol::intern("index_mut"),
2312 Some(vec![input_ty]))
2317 // Otherwise, fall back to `Index`.
2318 let method = match (method, tcx.lang_items.index_trait()) {
2319 (None, Some(trait_did)) => {
2320 self.lookup_method_in_trait_adjusted(expr.span,
2322 Symbol::intern("index"),
2327 Some(vec![input_ty]))
2329 (method, _) => method,
2332 // If some lookup succeeds, write callee into table and extract index/element
2333 // type from the method signature.
2334 // If some lookup succeeded, install method in table
2335 method.map(|method| {
2336 debug!("try_index_step: success, using overloaded indexing");
2337 self.tables.borrow_mut().method_map.insert(method_call, method);
2338 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2342 fn check_method_argument_types(&self,
2344 method_fn_ty: Ty<'tcx>,
2345 callee_expr: &'gcx hir::Expr,
2346 args_no_rcvr: &'gcx [hir::Expr],
2347 tuple_arguments: TupleArgumentsFlag,
2348 expected: Expectation<'tcx>)
2350 if method_fn_ty.references_error() {
2351 let err_inputs = self.err_args(args_no_rcvr.len());
2353 let err_inputs = match tuple_arguments {
2354 DontTupleArguments => err_inputs,
2355 TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
2358 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2359 false, tuple_arguments, None);
2362 match method_fn_ty.sty {
2363 ty::TyFnDef(def_id, .., ref fty) => {
2364 // HACK(eddyb) ignore self in the definition (see above).
2365 let expected_arg_tys = self.expected_inputs_for_expected_output(
2369 &fty.0.inputs()[1..]
2371 self.check_argument_types(sp, &fty.0.inputs()[1..], &expected_arg_tys[..],
2372 args_no_rcvr, fty.0.variadic, tuple_arguments,
2373 self.tcx.hir.span_if_local(def_id));
2377 span_bug!(callee_expr.span, "method without bare fn type");
2383 /// Generic function that factors out common logic from function calls,
2384 /// method calls and overloaded operators.
2385 fn check_argument_types(&self,
2387 fn_inputs: &[Ty<'tcx>],
2388 expected_arg_tys: &[Ty<'tcx>],
2389 args: &'gcx [hir::Expr],
2391 tuple_arguments: TupleArgumentsFlag,
2392 def_span: Option<Span>) {
2395 // Grab the argument types, supplying fresh type variables
2396 // if the wrong number of arguments were supplied
2397 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2403 // All the input types from the fn signature must outlive the call
2404 // so as to validate implied bounds.
2405 for &fn_input_ty in fn_inputs {
2406 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2409 let mut expected_arg_tys = expected_arg_tys;
2410 let expected_arg_count = fn_inputs.len();
2412 let sp_args = if args.len() > 0 {
2413 let (first, args) = args.split_at(1);
2414 let mut sp_tmp = first[0].span;
2416 let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
2417 if ! sp_opt.is_some() {
2420 sp_tmp = sp_opt.unwrap();
2427 fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
2428 arg_count: usize, error_code: &str, variadic: bool,
2429 def_span: Option<Span>) {
2430 let mut err = sess.struct_span_err_with_code(sp,
2431 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2432 if variadic {"at least "} else {""},
2434 if expected_count == 1 {""} else {"s"},
2436 if arg_count == 1 {" was"} else {"s were"}),
2439 err.span_label(sp, &format!("expected {}{} parameter{}",
2440 if variadic {"at least "} else {""},
2442 if expected_count == 1 {""} else {"s"}));
2443 if let Some(def_s) = def_span {
2444 err.span_label(def_s, &format!("defined here"));
2449 let formal_tys = if tuple_arguments == TupleArguments {
2450 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2451 match tuple_type.sty {
2452 ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
2453 parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
2454 "E0057", false, def_span);
2455 expected_arg_tys = &[];
2456 self.err_args(args.len())
2458 ty::TyTuple(arg_types, _) => {
2459 expected_arg_tys = match expected_arg_tys.get(0) {
2460 Some(&ty) => match ty.sty {
2461 ty::TyTuple(ref tys, _) => &tys,
2469 span_err!(tcx.sess, sp, E0059,
2470 "cannot use call notation; the first type parameter \
2471 for the function trait is neither a tuple nor unit");
2472 expected_arg_tys = &[];
2473 self.err_args(args.len())
2476 } else if expected_arg_count == supplied_arg_count {
2478 } else if variadic {
2479 if supplied_arg_count >= expected_arg_count {
2482 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2483 supplied_arg_count, "E0060", true, def_span);
2484 expected_arg_tys = &[];
2485 self.err_args(supplied_arg_count)
2488 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2489 supplied_arg_count, "E0061", false, def_span);
2490 expected_arg_tys = &[];
2491 self.err_args(supplied_arg_count)
2494 debug!("check_argument_types: formal_tys={:?}",
2495 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2497 // Check the arguments.
2498 // We do this in a pretty awful way: first we typecheck any arguments
2499 // that are not closures, then we typecheck the closures. This is so
2500 // that we have more information about the types of arguments when we
2501 // typecheck the functions. This isn't really the right way to do this.
2502 for &check_closures in &[false, true] {
2503 debug!("check_closures={}", check_closures);
2505 // More awful hacks: before we check argument types, try to do
2506 // an "opportunistic" vtable resolution of any trait bounds on
2507 // the call. This helps coercions.
2509 self.select_obligations_where_possible();
2512 // For variadic functions, we don't have a declared type for all of
2513 // the arguments hence we only do our usual type checking with
2514 // the arguments who's types we do know.
2515 let t = if variadic {
2517 } else if tuple_arguments == TupleArguments {
2522 for (i, arg) in args.iter().take(t).enumerate() {
2523 // Warn only for the first loop (the "no closures" one).
2524 // Closure arguments themselves can't be diverging, but
2525 // a previous argument can, e.g. `foo(panic!(), || {})`.
2526 if !check_closures {
2527 self.warn_if_unreachable(arg.id, arg.span, "expression");
2530 let is_closure = match arg.node {
2531 hir::ExprClosure(..) => true,
2535 if is_closure != check_closures {
2539 debug!("checking the argument");
2540 let formal_ty = formal_tys[i];
2542 // The special-cased logic below has three functions:
2543 // 1. Provide as good of an expected type as possible.
2544 let expected = expected_arg_tys.get(i).map(|&ty| {
2545 Expectation::rvalue_hint(self, ty)
2548 let checked_ty = self.check_expr_with_expectation(&arg,
2549 expected.unwrap_or(ExpectHasType(formal_ty)));
2550 // 2. Coerce to the most detailed type that could be coerced
2551 // to, which is `expected_ty` if `rvalue_hint` returns an
2552 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2553 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2554 self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
2556 // 3. Relate the expected type and the formal one,
2557 // if the expected type was used for the coercion.
2558 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2562 // We also need to make sure we at least write the ty of the other
2563 // arguments which we skipped above.
2565 for arg in args.iter().skip(expected_arg_count) {
2566 let arg_ty = self.check_expr(&arg);
2568 // There are a few types which get autopromoted when passed via varargs
2569 // in C but we just error out instead and require explicit casts.
2570 let arg_ty = self.structurally_resolved_type(arg.span,
2573 ty::TyFloat(ast::FloatTy::F32) => {
2574 self.type_error_message(arg.span, |t| {
2575 format!("can't pass an `{}` to variadic \
2576 function, cast to `c_double`", t)
2579 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2580 self.type_error_message(arg.span, |t| {
2581 format!("can't pass `{}` to variadic \
2582 function, cast to `c_int`",
2586 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2587 self.type_error_message(arg.span, |t| {
2588 format!("can't pass `{}` to variadic \
2589 function, cast to `c_uint`",
2593 ty::TyFnDef(.., f) => {
2594 let ptr_ty = self.tcx.mk_fn_ptr(f);
2595 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2596 self.type_error_message(arg.span,
2598 format!("can't pass `{}` to variadic \
2599 function, cast to `{}`", t, ptr_ty)
2608 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2609 (0..len).map(|_| self.tcx.types.err).collect()
2612 // AST fragment checking
2615 expected: Expectation<'tcx>)
2621 ast::LitKind::Str(..) => tcx.mk_static_str(),
2622 ast::LitKind::ByteStr(ref v) => {
2623 tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic),
2624 tcx.mk_array(tcx.types.u8, v.len()))
2626 ast::LitKind::Byte(_) => tcx.types.u8,
2627 ast::LitKind::Char(_) => tcx.types.char,
2628 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2629 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2630 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2631 let opt_ty = expected.to_option(self).and_then(|ty| {
2633 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2634 ty::TyChar => Some(tcx.types.u8),
2635 ty::TyRawPtr(..) => Some(tcx.types.usize),
2636 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2640 opt_ty.unwrap_or_else(
2641 || tcx.mk_int_var(self.next_int_var_id()))
2643 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2644 ast::LitKind::FloatUnsuffixed(_) => {
2645 let opt_ty = expected.to_option(self).and_then(|ty| {
2647 ty::TyFloat(_) => Some(ty),
2651 opt_ty.unwrap_or_else(
2652 || tcx.mk_float_var(self.next_float_var_id()))
2654 ast::LitKind::Bool(_) => tcx.types.bool
2658 fn check_expr_eq_type(&self,
2659 expr: &'gcx hir::Expr,
2660 expected: Ty<'tcx>) {
2661 let ty = self.check_expr_with_hint(expr, expected);
2662 self.demand_eqtype(expr.span, expected, ty);
2665 pub fn check_expr_has_type(&self,
2666 expr: &'gcx hir::Expr,
2667 expected: Ty<'tcx>) -> Ty<'tcx> {
2668 let mut ty = self.check_expr_with_hint(expr, expected);
2670 // While we don't allow *arbitrary* coercions here, we *do* allow
2671 // coercions from ! to `expected`.
2673 assert!(!self.tables.borrow().adjustments.contains_key(&expr.id),
2674 "expression with never type wound up being adjusted");
2675 let adj_ty = self.next_diverging_ty_var(
2676 TypeVariableOrigin::AdjustmentType(expr.span));
2677 self.write_adjustment(expr.id, adjustment::Adjustment {
2678 kind: adjustment::Adjust::NeverToAny,
2684 self.demand_suptype(expr.span, expected, ty);
2688 fn check_expr_coercable_to_type(&self,
2689 expr: &'gcx hir::Expr,
2690 expected: Ty<'tcx>) -> Ty<'tcx> {
2691 let ty = self.check_expr_with_hint(expr, expected);
2692 self.demand_coerce(expr, ty, expected);
2696 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2697 expected: Ty<'tcx>) -> Ty<'tcx> {
2698 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2701 fn check_expr_with_expectation(&self,
2702 expr: &'gcx hir::Expr,
2703 expected: Expectation<'tcx>) -> Ty<'tcx> {
2704 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2707 fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
2708 self.check_expr_with_expectation(expr, NoExpectation)
2711 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2712 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2713 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2716 // determine the `self` type, using fresh variables for all variables
2717 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2718 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2720 pub fn impl_self_ty(&self,
2721 span: Span, // (potential) receiver for this impl
2723 -> TypeAndSubsts<'tcx> {
2724 let ity = self.tcx.item_type(did);
2725 debug!("impl_self_ty: ity={:?}", ity);
2727 let substs = self.fresh_substs_for_item(span, did);
2728 let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
2730 TypeAndSubsts { substs: substs, ty: substd_ty }
2733 /// Unifies the output type with the expected type early, for more coercions
2734 /// and forward type information on the input expressions.
2735 fn expected_inputs_for_expected_output(&self,
2737 expected_ret: Expectation<'tcx>,
2738 formal_ret: Ty<'tcx>,
2739 formal_args: &[Ty<'tcx>])
2741 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2742 self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
2743 // Attempt to apply a subtyping relationship between the formal
2744 // return type (likely containing type variables if the function
2745 // is polymorphic) and the expected return type.
2746 // No argument expectations are produced if unification fails.
2747 let origin = self.misc(call_span);
2748 let ures = self.sub_types(false, &origin, formal_ret, ret_ty);
2749 // FIXME(#15760) can't use try! here, FromError doesn't default
2750 // to identity so the resulting type is not constrained.
2752 Ok(ok) => self.register_infer_ok_obligations(ok),
2753 Err(e) => return Err(e),
2756 // Record all the argument types, with the substitutions
2757 // produced from the above subtyping unification.
2758 Ok(formal_args.iter().map(|ty| {
2759 self.resolve_type_vars_if_possible(ty)
2762 }).unwrap_or(vec![]);
2763 debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
2764 formal_args, formal_ret,
2765 expected_args, expected_ret);
2769 // Checks a method call.
2770 fn check_method_call(&self,
2771 expr: &'gcx hir::Expr,
2772 method_name: Spanned<ast::Name>,
2773 args: &'gcx [hir::Expr],
2775 expected: Expectation<'tcx>,
2776 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2777 let rcvr = &args[0];
2778 let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2780 // no need to check for bot/err -- callee does that
2781 let expr_t = self.structurally_resolved_type(expr.span, rcvr_t);
2783 let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2784 let fn_ty = match self.lookup_method(method_name.span,
2791 let method_ty = method.ty;
2792 let method_call = MethodCall::expr(expr.id);
2793 self.tables.borrow_mut().method_map.insert(method_call, method);
2797 if method_name.node != keywords::Invalid.name() {
2798 self.report_method_error(method_name.span,
2805 self.write_error(expr.id);
2810 // Call the generic checker.
2811 let ret_ty = self.check_method_argument_types(method_name.span, fn_ty,
2819 fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
2823 .unwrap_or_else(|| span_bug!(return_expr.span,
2824 "check_return_expr called outside fn body"));
2826 let ret_ty = ret_coercion.borrow().expected_ty();
2827 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
2828 ret_coercion.borrow_mut()
2830 &self.misc(return_expr.span),
2836 // A generic function for checking the then and else in an if
2838 fn check_then_else(&self,
2839 cond_expr: &'gcx hir::Expr,
2840 then_expr: &'gcx hir::Expr,
2841 opt_else_expr: Option<&'gcx hir::Expr>,
2843 expected: Expectation<'tcx>) -> Ty<'tcx> {
2844 let cond_ty = self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2845 let cond_diverges = self.diverges.get();
2846 self.diverges.set(Diverges::Maybe);
2848 let expected = expected.adjust_for_branches(self);
2849 let then_ty = self.check_expr_with_expectation(then_expr, expected);
2850 let then_diverges = self.diverges.get();
2851 self.diverges.set(Diverges::Maybe);
2853 // We've already taken the expected type's preferences
2854 // into account when typing the `then` branch. To figure
2855 // out the initial shot at a LUB, we thus only consider
2856 // `expected` if it represents a *hard* constraint
2857 // (`only_has_type`); otherwise, we just go with a
2858 // fresh type variable.
2859 let coerce_to_ty = expected.only_has_type_or_fresh_var(self, sp);
2860 let mut coerce = CoerceMany::new(coerce_to_ty);
2862 let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
2863 coerce.coerce(self, &if_cause, then_expr, then_ty);
2865 if let Some(else_expr) = opt_else_expr {
2866 let else_ty = self.check_expr_with_expectation(else_expr, expected);
2867 let else_diverges = self.diverges.get();
2869 coerce.coerce(self, &if_cause, else_expr, else_ty);
2871 // We won't diverge unless both branches do (or the condition does).
2872 self.diverges.set(cond_diverges | then_diverges & else_diverges);
2874 let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
2875 coerce.coerce_forced_unit(self, &else_cause);
2877 // If the condition is false we can't diverge.
2878 self.diverges.set(cond_diverges);
2881 let result_ty = coerce.complete(self);
2882 if cond_ty.references_error() {
2889 // Check field access expressions
2890 fn check_field(&self,
2891 expr: &'gcx hir::Expr,
2892 lvalue_pref: LvaluePreference,
2893 base: &'gcx hir::Expr,
2894 field: &Spanned<ast::Name>) -> Ty<'tcx> {
2895 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2896 let expr_t = self.structurally_resolved_type(expr.span,
2898 let mut private_candidate = None;
2899 let mut autoderef = self.autoderef(expr.span, expr_t);
2900 while let Some((base_t, autoderefs)) = autoderef.next() {
2902 ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
2903 debug!("struct named {:?}", base_t);
2904 if let Some(field) = base_def.struct_variant().find_field_named(field.node) {
2905 let field_ty = self.field_ty(expr.span, field, substs);
2906 if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
2907 autoderef.finalize(lvalue_pref, Some(base));
2908 self.write_autoderef_adjustment(base.id, autoderefs, base_t);
2910 self.tcx.check_stability(field.did, expr.id, expr.span);
2914 private_candidate = Some((base_def.did, field_ty));
2920 autoderef.unambiguous_final_ty();
2922 if let Some((did, field_ty)) = private_candidate {
2923 let struct_path = self.tcx().item_path_str(did);
2924 let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
2925 let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
2926 // Also check if an accessible method exists, which is often what is meant.
2927 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2928 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2933 } else if field.node == keywords::Invalid.name() {
2934 self.tcx().types.err
2935 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2936 self.type_error_struct(field.span, |actual| {
2937 format!("attempted to take value of method `{}` on type \
2938 `{}`", field.node, actual)
2940 .help("maybe a `()` to call it is missing? \
2941 If not, try an anonymous function")
2943 self.tcx().types.err
2945 let mut err = self.type_error_struct(field.span, |actual| {
2946 format!("no field `{}` on type `{}`",
2950 ty::TyAdt(def, _) if !def.is_enum() => {
2951 if let Some(suggested_field_name) =
2952 Self::suggest_field_name(def.struct_variant(), field, vec![]) {
2953 err.span_label(field.span,
2954 &format!("did you mean `{}`?", suggested_field_name));
2956 err.span_label(field.span,
2957 &format!("unknown field"));
2960 ty::TyRawPtr(..) => {
2961 err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
2963 self.tcx.hir.node_to_pretty_string(base.id),
2969 self.tcx().types.err
2973 // Return an hint about the closest match in field names
2974 fn suggest_field_name(variant: &'tcx ty::VariantDef,
2975 field: &Spanned<ast::Name>,
2976 skip : Vec<InternedString>)
2978 let name = field.node.as_str();
2979 let names = variant.fields.iter().filter_map(|field| {
2980 // ignore already set fields and private fields from non-local crates
2981 if skip.iter().any(|x| *x == field.name.as_str()) ||
2982 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
2989 // only find fits with at least one matching letter
2990 find_best_match_for_name(names, &name, Some(name.len()))
2993 // Check tuple index expressions
2994 fn check_tup_field(&self,
2995 expr: &'gcx hir::Expr,
2996 lvalue_pref: LvaluePreference,
2997 base: &'gcx hir::Expr,
2998 idx: codemap::Spanned<usize>) -> Ty<'tcx> {
2999 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
3000 let expr_t = self.structurally_resolved_type(expr.span,
3002 let mut private_candidate = None;
3003 let mut tuple_like = false;
3004 let mut autoderef = self.autoderef(expr.span, expr_t);
3005 while let Some((base_t, autoderefs)) = autoderef.next() {
3006 let field = match base_t.sty {
3007 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
3008 tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
3009 if !tuple_like { continue }
3011 debug!("tuple struct named {:?}", base_t);
3012 base_def.struct_variant().fields.get(idx.node).and_then(|field| {
3013 let field_ty = self.field_ty(expr.span, field, substs);
3014 private_candidate = Some((base_def.did, field_ty));
3015 if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
3016 self.tcx.check_stability(field.did, expr.id, expr.span);
3023 ty::TyTuple(ref v, _) => {
3025 v.get(idx.node).cloned()
3030 if let Some(field_ty) = field {
3031 autoderef.finalize(lvalue_pref, Some(base));
3032 self.write_autoderef_adjustment(base.id, autoderefs, base_t);
3036 autoderef.unambiguous_final_ty();
3038 if let Some((did, field_ty)) = private_candidate {
3039 let struct_path = self.tcx().item_path_str(did);
3040 let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3041 self.tcx().sess.span_err(expr.span, &msg);
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.tcx().types.err
3065 fn report_unknown_field(&self,
3067 variant: &'tcx ty::VariantDef,
3069 skip_fields: &[hir::Field],
3071 let mut err = self.type_error_struct_with_diag(
3073 |actual| match ty.sty {
3074 ty::TyAdt(adt, ..) if adt.is_enum() => {
3075 struct_span_err!(self.tcx.sess, field.name.span, E0559,
3076 "{} `{}::{}` has no field named `{}`",
3077 kind_name, actual, variant.name, field.name.node)
3080 struct_span_err!(self.tcx.sess, field.name.span, E0560,
3081 "{} `{}` has no field named `{}`",
3082 kind_name, actual, field.name.node)
3086 // prevent all specified fields from being suggested
3087 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3088 if let Some(field_name) = Self::suggest_field_name(variant,
3090 skip_fields.collect()) {
3091 err.span_label(field.name.span,
3092 &format!("field does not exist - did you mean `{}`?", field_name));
3095 ty::TyAdt(adt, ..) if adt.is_enum() => {
3096 err.span_label(field.name.span, &format!("`{}::{}` does not have this field",
3100 err.span_label(field.name.span, &format!("`{}` does not have this field", ty));
3107 fn check_expr_struct_fields(&self,
3109 expected: Expectation<'tcx>,
3110 expr_id: ast::NodeId,
3112 variant: &'tcx ty::VariantDef,
3113 ast_fields: &'gcx [hir::Field],
3114 check_completeness: bool) {
3118 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3119 .get(0).cloned().unwrap_or(adt_ty);
3121 let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
3122 (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
3123 (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
3125 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3128 let mut remaining_fields = FxHashMap();
3129 for field in &variant.fields {
3130 remaining_fields.insert(field.name, field);
3133 let mut seen_fields = FxHashMap();
3135 let mut error_happened = false;
3137 // Typecheck each field.
3138 for field in ast_fields {
3139 let final_field_type;
3140 let field_type_hint;
3142 if let Some(v_field) = remaining_fields.remove(&field.name.node) {
3143 final_field_type = self.field_ty(field.span, v_field, substs);
3144 field_type_hint = self.field_ty(field.span, v_field, hint_substs);
3146 seen_fields.insert(field.name.node, field.span);
3148 // we don't look at stability attributes on
3149 // struct-like enums (yet...), but it's definitely not
3150 // a bug to have construct one.
3151 if adt_kind != ty::AdtKind::Enum {
3152 tcx.check_stability(v_field.did, expr_id, field.span);
3155 error_happened = true;
3156 final_field_type = tcx.types.err;
3157 field_type_hint = tcx.types.err;
3158 if let Some(_) = variant.find_field_named(field.name.node) {
3159 let mut err = struct_span_err!(self.tcx.sess,
3162 "field `{}` specified more than once",
3165 err.span_label(field.name.span, &format!("used more than once"));
3167 if let Some(prev_span) = seen_fields.get(&field.name.node) {
3168 err.span_label(*prev_span, &format!("first use of `{}`", field.name.node));
3173 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3177 // Make sure to give a type to the field even if there's
3178 // an error, so we can continue typechecking
3179 let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
3180 self.demand_coerce(&field.expr, ty, final_field_type);
3183 // Make sure the programmer specified correct number of fields.
3184 if kind_name == "union" {
3185 if ast_fields.len() != 1 {
3186 tcx.sess.span_err(span, "union expressions should have exactly one field");
3188 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3189 let len = remaining_fields.len();
3191 let mut displayable_field_names = remaining_fields
3193 .map(|x| x.as_str())
3194 .collect::<Vec<_>>();
3196 displayable_field_names.sort();
3198 let truncated_fields_error = if len <= 3 {
3201 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3204 let remaining_fields_names = displayable_field_names.iter().take(3)
3205 .map(|n| format!("`{}`", n))
3206 .collect::<Vec<_>>()
3209 struct_span_err!(tcx.sess, span, E0063,
3210 "missing field{} {}{} in initializer of `{}`",
3211 if remaining_fields.len() == 1 {""} else {"s"},
3212 remaining_fields_names,
3213 truncated_fields_error,
3215 .span_label(span, &format!("missing {}{}",
3216 remaining_fields_names,
3217 truncated_fields_error))
3222 fn check_struct_fields_on_error(&self,
3223 fields: &'gcx [hir::Field],
3224 base_expr: &'gcx Option<P<hir::Expr>>) {
3225 for field in fields {
3226 self.check_expr(&field.expr);
3230 self.check_expr(&base);
3236 pub fn check_struct_path(&self,
3238 node_id: ast::NodeId)
3239 -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
3240 let path_span = match *qpath {
3241 hir::QPath::Resolved(_, ref path) => path.span,
3242 hir::QPath::TypeRelative(ref qself, _) => qself.span
3244 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3245 let variant = match def {
3247 self.set_tainted_by_errors();
3250 Def::Variant(..) => {
3252 ty::TyAdt(adt, substs) => {
3253 Some((adt.variant_of_def(def), adt.did, substs))
3255 _ => bug!("unexpected type: {:?}", ty.sty)
3258 Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3259 Def::AssociatedTy(..) | Def::SelfTy(..) => {
3261 ty::TyAdt(adt, substs) if !adt.is_enum() => {
3262 Some((adt.struct_variant(), adt.did, substs))
3267 _ => bug!("unexpected definition: {:?}", def)
3270 if let Some((variant, did, substs)) = variant {
3271 // Check bounds on type arguments used in the path.
3272 let bounds = self.instantiate_bounds(path_span, did, substs);
3273 let cause = traits::ObligationCause::new(path_span, self.body_id,
3274 traits::ItemObligation(did));
3275 self.add_obligations_for_parameters(cause, &bounds);
3279 struct_span_err!(self.tcx.sess, path_span, E0071,
3280 "expected struct, variant or union type, found {}",
3281 ty.sort_string(self.tcx))
3282 .span_label(path_span, &format!("not a struct"))
3288 fn check_expr_struct(&self,
3290 expected: Expectation<'tcx>,
3292 fields: &'gcx [hir::Field],
3293 base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3295 // Find the relevant variant
3296 let (variant, struct_ty) =
3297 if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3300 self.check_struct_fields_on_error(fields, base_expr);
3301 return self.tcx.types.err;
3304 let path_span = match *qpath {
3305 hir::QPath::Resolved(_, ref path) => path.span,
3306 hir::QPath::TypeRelative(ref qself, _) => qself.span
3309 self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3310 base_expr.is_none());
3311 if let &Some(ref base_expr) = base_expr {
3312 self.check_expr_has_type(base_expr, struct_ty);
3313 match struct_ty.sty {
3314 ty::TyAdt(adt, substs) if adt.is_struct() => {
3315 self.tables.borrow_mut().fru_field_types.insert(
3317 adt.struct_variant().fields.iter().map(|f| {
3318 self.normalize_associated_types_in(
3319 expr.span, &f.ty(self.tcx, substs)
3325 span_err!(self.tcx.sess, base_expr.span, E0436,
3326 "functional record update syntax requires a struct");
3330 self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3336 /// If an expression has any sub-expressions that result in a type error,
3337 /// inspecting that expression's type with `ty.references_error()` will return
3338 /// true. Likewise, if an expression is known to diverge, inspecting its
3339 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3340 /// strict, _|_ can appear in the type of an expression that does not,
3341 /// itself, diverge: for example, fn() -> _|_.)
3342 /// Note that inspecting a type's structure *directly* may expose the fact
3343 /// that there are actually multiple representations for `TyError`, so avoid
3344 /// that when err needs to be handled differently.
3345 fn check_expr_with_expectation_and_lvalue_pref(&self,
3346 expr: &'gcx hir::Expr,
3347 expected: Expectation<'tcx>,
3348 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3349 debug!(">> typechecking: expr={:?} expected={:?}",
3352 // Warn for expressions after diverging siblings.
3353 self.warn_if_unreachable(expr.id, expr.span, "expression");
3355 // Hide the outer diverging and has_errors flags.
3356 let old_diverges = self.diverges.get();
3357 let old_has_errors = self.has_errors.get();
3358 self.diverges.set(Diverges::Maybe);
3359 self.has_errors.set(false);
3361 let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3363 // Warn for non-block expressions with diverging children.
3366 hir::ExprLoop(..) | hir::ExprWhile(..) |
3367 hir::ExprIf(..) | hir::ExprMatch(..) => {}
3369 _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3372 // Any expression that produces a value of type `!` must have diverged
3374 self.diverges.set(self.diverges.get() | Diverges::Always);
3377 // Record the type, which applies it effects.
3378 // We need to do this after the warning above, so that
3379 // we don't warn for the diverging expression itself.
3380 self.write_ty(expr.id, ty);
3382 // Combine the diverging and has_error flags.
3383 self.diverges.set(self.diverges.get() | old_diverges);
3384 self.has_errors.set(self.has_errors.get() | old_has_errors);
3386 debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3387 debug!("... {:?}, expected is {:?}", ty, expected);
3392 fn check_expr_kind(&self,
3393 expr: &'gcx hir::Expr,
3394 expected: Expectation<'tcx>,
3395 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3399 hir::ExprBox(ref subexpr) => {
3400 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3402 ty::TyAdt(def, _) if def.is_box()
3403 => Expectation::rvalue_hint(self, ty.boxed_ty()),
3407 let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3408 tcx.mk_box(referent_ty)
3411 hir::ExprLit(ref lit) => {
3412 self.check_lit(&lit, expected)
3414 hir::ExprBinary(op, ref lhs, ref rhs) => {
3415 self.check_binop(expr, op, lhs, rhs)
3417 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3418 self.check_binop_assign(expr, op, lhs, rhs)
3420 hir::ExprUnary(unop, ref oprnd) => {
3421 let expected_inner = match unop {
3422 hir::UnNot | hir::UnNeg => {
3429 let lvalue_pref = match unop {
3430 hir::UnDeref => lvalue_pref,
3433 let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3437 if !oprnd_t.references_error() {
3440 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3442 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3444 } else if let Some(method) = self.try_overloaded_deref(
3445 expr.span, Some(&oprnd), oprnd_t, lvalue_pref) {
3446 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3447 self.tables.borrow_mut().method_map.insert(MethodCall::expr(expr.id),
3450 self.type_error_message(expr.span, |actual| {
3451 format!("type `{}` cannot be \
3452 dereferenced", actual)
3454 oprnd_t = tcx.types.err;
3458 oprnd_t = self.structurally_resolved_type(oprnd.span,
3460 let result = self.check_user_unop("!", "not",
3461 tcx.lang_items.not_trait(),
3462 expr, &oprnd, oprnd_t, unop);
3463 // If it's builtin, we can reuse the type, this helps inference.
3464 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3469 oprnd_t = self.structurally_resolved_type(oprnd.span,
3471 let result = self.check_user_unop("-", "neg",
3472 tcx.lang_items.neg_trait(),
3473 expr, &oprnd, oprnd_t, unop);
3474 // If it's builtin, we can reuse the type, this helps inference.
3475 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3483 hir::ExprAddrOf(mutbl, ref oprnd) => {
3484 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3486 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3487 if self.tcx.expr_is_lval(&oprnd) {
3488 // Lvalues may legitimately have unsized types.
3489 // For example, dereferences of a fat pointer and
3490 // the last field of a struct can be unsized.
3491 ExpectHasType(mt.ty)
3493 Expectation::rvalue_hint(self, mt.ty)
3499 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3500 let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3502 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3503 if tm.ty.references_error() {
3506 // Note: at this point, we cannot say what the best lifetime
3507 // is to use for resulting pointer. We want to use the
3508 // shortest lifetime possible so as to avoid spurious borrowck
3509 // errors. Moreover, the longest lifetime will depend on the
3510 // precise details of the value whose address is being taken
3511 // (and how long it is valid), which we don't know yet until type
3512 // inference is complete.
3514 // Therefore, here we simply generate a region variable. The
3515 // region inferencer will then select the ultimate value.
3516 // Finally, borrowck is charged with guaranteeing that the
3517 // value whose address was taken can actually be made to live
3518 // as long as it needs to live.
3519 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3520 tcx.mk_ref(region, tm)
3523 hir::ExprPath(ref qpath) => {
3524 let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3525 expr.id, expr.span);
3526 let ty = if def != Def::Err {
3527 self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3529 self.set_tainted_by_errors();
3533 // We always require that the type provided as the value for
3534 // a type parameter outlives the moment of instantiation.
3535 self.opt_node_ty_substs(expr.id, |item_substs| {
3536 self.add_wf_bounds(&item_substs.substs, expr);
3541 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3542 for output in outputs {
3543 self.check_expr(output);
3545 for input in inputs {
3546 self.check_expr(input);
3550 hir::ExprBreak(destination, ref expr_opt) => {
3551 if let Some(target_id) = destination.target_id.opt_id() {
3553 if let Some(ref e) = *expr_opt {
3554 // If this is a break with a value, we need to type-check
3555 // the expression. Get an expected type from the loop context.
3556 let opt_coerce_to = {
3557 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3558 enclosing_breakables.find_breakable(target_id)
3561 .map(|coerce| coerce.expected_ty())
3564 // If the loop context is not a `loop { }`, then break with
3565 // a value is illegal, and `opt_coerce_to` will be `None`.
3566 // Just set expectation to error in that case.
3567 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3569 // Recurse without `enclosing_breakables` borrowed.
3570 e_ty = self.check_expr_with_hint(e, coerce_to);
3571 cause = self.misc(e.span);
3573 // Otherwise, this is a break *without* a value. That's
3574 // always legal, and is equivalent to `break ()`.
3575 e_ty = tcx.mk_nil();
3576 cause = self.misc(expr.span);
3579 // Now that we have type-checked `expr_opt`, borrow
3580 // the `enclosing_loops` field and let's coerce the
3581 // type of `expr_opt` into what is expected.
3582 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3583 let ctxt = enclosing_breakables.find_breakable(target_id);
3584 if let Some(ref mut coerce) = ctxt.coerce {
3585 if let Some(ref e) = *expr_opt {
3586 coerce.coerce(self, &cause, e, e_ty);
3588 assert!(e_ty.is_nil());
3589 coerce.coerce_forced_unit(self, &cause);
3592 // If `ctxt.coerce` is `None`, we can just ignore
3593 // the type of the expresison. This is because
3594 // either this was a break *without* a value, in
3595 // which case it is always a legal type (`()`), or
3596 // else an error would have been flagged by the
3597 // `loops` pass for using break with an expression
3598 // where you are not supposed to.
3599 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3602 ctxt.may_break = true;
3604 // Otherwise, we failed to find the enclosing loop; this can only happen if the
3605 // `break` was not inside a loop at all, which is caught by the loop-checking pass.
3606 assert!(self.tcx.sess.err_count() > 0);
3609 // the type of a `break` is always `!`, since it diverges
3612 hir::ExprAgain(_) => { tcx.types.never }
3613 hir::ExprRet(ref expr_opt) => {
3614 if self.ret_coercion.is_none() {
3615 struct_span_err!(self.tcx.sess, expr.span, E0572,
3616 "return statement outside of function body").emit();
3617 } else if let Some(ref e) = *expr_opt {
3618 self.check_return_expr(e);
3620 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3621 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3622 coercion.coerce_forced_unit(self, &cause);
3626 hir::ExprAssign(ref lhs, ref rhs) => {
3627 let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3630 if !tcx.expr_is_lval(&lhs) {
3632 tcx.sess, expr.span, E0070,
3633 "invalid left-hand side expression")
3636 &format!("left-hand of expression not valid"))
3640 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3642 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3644 if lhs_ty.references_error() || rhs_ty.references_error() {
3650 hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3651 self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3652 expr.span, expected)
3654 hir::ExprWhile(ref cond, ref body, _) => {
3655 let ctxt = BreakableCtxt {
3656 // cannot use break with a value from a while loop
3661 self.with_breakable_ctxt(expr.id, ctxt, || {
3662 self.check_expr_has_type(&cond, tcx.types.bool);
3663 let cond_diverging = self.diverges.get();
3664 self.check_block_no_value(&body);
3666 // We may never reach the body so it diverging means nothing.
3667 self.diverges.set(cond_diverging);
3672 hir::ExprLoop(ref body, _, source) => {
3673 let coerce = match source {
3674 // you can only use break with a value from a normal `loop { }`
3675 hir::LoopSource::Loop => {
3676 let coerce_to = expected.only_has_type_or_fresh_var(self, body.span);
3677 Some(CoerceMany::new(coerce_to))
3680 hir::LoopSource::WhileLet |
3681 hir::LoopSource::ForLoop => {
3686 let ctxt = BreakableCtxt {
3688 may_break: false, // will get updated if/when we find a `break`
3691 let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3692 self.check_block_no_value(&body);
3696 // No way to know whether it's diverging because
3697 // of a `break` or an outer `break` or `return.
3698 self.diverges.set(Diverges::Maybe);
3701 // If we permit break with a value, then result type is
3702 // the LUB of the breaks (possibly ! if none); else, it
3703 // is nil. This makes sense because infinite loops
3704 // (which would have type !) are only possible iff we
3705 // permit break with a value [1].
3706 assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3707 ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3709 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3710 self.check_match(expr, &discrim, arms, expected, match_src)
3712 hir::ExprClosure(capture, ref decl, body_id, _) => {
3713 self.check_expr_closure(expr, capture, &decl, body_id, expected)
3715 hir::ExprBlock(ref body) => {
3716 self.check_block_with_expected(&body, expected)
3718 hir::ExprCall(ref callee, ref args) => {
3719 self.check_call(expr, &callee, args, expected)
3721 hir::ExprMethodCall(name, ref tps, ref args) => {
3722 self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
3724 hir::ExprCast(ref e, ref t) => {
3725 // Find the type of `e`. Supply hints based on the type we are casting to,
3727 let t_cast = self.to_ty(t);
3728 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3729 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3730 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3732 // Eagerly check for some obvious errors.
3733 if t_expr.references_error() || t_cast.references_error() {
3736 // Defer other checks until we're done type checking.
3737 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3738 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
3740 deferred_cast_checks.push(cast_check);
3743 Err(ErrorReported) => {
3749 hir::ExprType(ref e, ref t) => {
3750 let typ = self.to_ty(&t);
3751 self.check_expr_eq_type(&e, typ);
3754 hir::ExprArray(ref args) => {
3755 let uty = expected.to_option(self).and_then(|uty| {
3757 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3762 let element_ty = if !args.is_empty() {
3763 let coerce_to = uty.unwrap_or_else(
3764 || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3765 let mut coerce = CoerceMany::new(coerce_to);
3767 let e_ty = self.check_expr_with_hint(e, coerce_to);
3768 let cause = self.misc(e.span);
3769 coerce.coerce(self, &cause, e, e_ty);
3771 coerce.complete(self)
3773 self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3775 tcx.mk_array(element_ty, args.len())
3777 hir::ExprRepeat(ref element, count) => {
3778 let count = eval_length(self.tcx.global_tcx(), count, "repeat count")
3781 let uty = match expected {
3782 ExpectHasType(uty) => {
3784 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3791 let (element_ty, t) = match uty {
3793 self.check_expr_coercable_to_type(&element, uty);
3797 let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3798 let element_ty = self.check_expr_has_type(&element, t);
3804 // For [foo, ..n] where n > 1, `foo` must have
3806 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3807 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3810 if element_ty.references_error() {
3813 tcx.mk_array(t, count)
3816 hir::ExprTup(ref elts) => {
3817 let flds = expected.only_has_type(self).and_then(|ty| {
3819 ty::TyTuple(ref flds, _) => Some(&flds[..]),
3824 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3825 let t = match flds {
3826 Some(ref fs) if i < fs.len() => {
3828 self.check_expr_coercable_to_type(&e, ety);
3832 self.check_expr_with_expectation(&e, NoExpectation)
3837 let tuple = tcx.mk_tup(elt_ts_iter, false);
3838 if tuple.references_error() {
3844 hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3845 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3847 hir::ExprField(ref base, ref field) => {
3848 self.check_field(expr, lvalue_pref, &base, field)
3850 hir::ExprTupField(ref base, idx) => {
3851 self.check_tup_field(expr, lvalue_pref, &base, idx)
3853 hir::ExprIndex(ref base, ref idx) => {
3854 let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3855 let idx_t = self.check_expr(&idx);
3857 if base_t.references_error() {
3859 } else if idx_t.references_error() {
3862 let base_t = self.structurally_resolved_type(expr.span, base_t);
3863 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3864 Some((index_ty, element_ty)) => {
3865 self.demand_coerce(idx, idx_t, index_ty);
3869 self.check_expr_has_type(&idx, self.tcx.types.err);
3870 let mut err = self.type_error_struct(
3873 format!("cannot index a value of type `{}`",
3877 // Try to give some advice about indexing tuples.
3878 if let ty::TyTuple(..) = base_t.sty {
3879 let mut needs_note = true;
3880 // If the index is an integer, we can show the actual
3881 // fixed expression:
3882 if let hir::ExprLit(ref lit) = idx.node {
3883 if let ast::LitKind::Int(i,
3884 ast::LitIntType::Unsuffixed) = lit.node {
3885 let snip = tcx.sess.codemap().span_to_snippet(base.span);
3886 if let Ok(snip) = snip {
3887 err.span_suggestion(expr.span,
3888 "to access tuple elements, \
3889 use tuple indexing syntax \
3891 format!("{}.{}", snip, i));
3897 err.help("to access tuple elements, use tuple indexing \
3898 syntax (e.g. `tuple.0`)");
3910 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3911 // The newly resolved definition is written into `type_relative_path_defs`.
3912 fn finish_resolving_struct_path(&self,
3915 node_id: ast::NodeId)
3919 hir::QPath::Resolved(ref maybe_qself, ref path) => {
3920 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
3921 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
3924 hir::QPath::TypeRelative(ref qself, ref segment) => {
3925 let ty = self.to_ty(qself);
3927 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
3932 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
3935 // Write back the new resolution.
3936 self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
3943 // Resolve associated value path into a base type and associated constant or method definition.
3944 // The newly resolved definition is written into `type_relative_path_defs`.
3945 pub fn resolve_ty_and_def_ufcs<'b>(&self,
3946 qpath: &'b hir::QPath,
3947 node_id: ast::NodeId,
3949 -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3951 let (ty, item_segment) = match *qpath {
3952 hir::QPath::Resolved(ref opt_qself, ref path) => {
3954 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
3955 &path.segments[..]);
3957 hir::QPath::TypeRelative(ref qself, ref segment) => {
3958 (self.to_ty(qself), segment)
3961 let item_name = item_segment.name;
3962 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3965 let def = match error {
3966 method::MethodError::PrivateMatch(def) => def,
3969 if item_name != keywords::Invalid.name() {
3970 self.report_method_error(span, ty, item_name, None, error, None);
3976 // Write back the new resolution.
3977 self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
3978 (def, Some(ty), slice::ref_slice(&**item_segment))
3981 pub fn check_decl_initializer(&self,
3982 local: &'gcx hir::Local,
3983 init: &'gcx hir::Expr) -> Ty<'tcx>
3985 let ref_bindings = local.pat.contains_ref_binding();
3987 let local_ty = self.local_ty(init.span, local.id);
3988 if let Some(m) = ref_bindings {
3989 // Somewhat subtle: if we have a `ref` binding in the pattern,
3990 // we want to avoid introducing coercions for the RHS. This is
3991 // both because it helps preserve sanity and, in the case of
3992 // ref mut, for soundness (issue #23116). In particular, in
3993 // the latter case, we need to be clear that the type of the
3994 // referent for the reference that results is *equal to* the
3995 // type of the lvalue it is referencing, and not some
3996 // supertype thereof.
3997 let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
3998 self.demand_eqtype(init.span, init_ty, local_ty);
4001 self.check_expr_coercable_to_type(init, local_ty)
4005 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
4006 let t = self.local_ty(local.span, local.id);
4007 self.write_ty(local.id, t);
4009 if let Some(ref init) = local.init {
4010 let init_ty = self.check_decl_initializer(local, &init);
4011 if init_ty.references_error() {
4012 self.write_ty(local.id, init_ty);
4016 self.check_pat(&local.pat, t);
4017 let pat_ty = self.node_ty(local.pat.id);
4018 if pat_ty.references_error() {
4019 self.write_ty(local.id, pat_ty);
4023 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4024 // Don't do all the complex logic below for DeclItem.
4026 hir::StmtDecl(ref decl, id) => {
4028 hir::DeclLocal(_) => {}
4029 hir::DeclItem(_) => {
4035 hir::StmtExpr(..) | hir::StmtSemi(..) => {}
4038 self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
4040 // Hide the outer diverging and has_errors flags.
4041 let old_diverges = self.diverges.get();
4042 let old_has_errors = self.has_errors.get();
4043 self.diverges.set(Diverges::Maybe);
4044 self.has_errors.set(false);
4046 let (node_id, _span) = match stmt.node {
4047 hir::StmtDecl(ref decl, id) => {
4048 let span = match decl.node {
4049 hir::DeclLocal(ref l) => {
4050 self.check_decl_local(&l);
4053 hir::DeclItem(_) => {/* ignore for now */
4059 hir::StmtExpr(ref expr, id) => {
4060 // Check with expected type of ()
4061 self.check_expr_has_type(&expr, self.tcx.mk_nil());
4064 hir::StmtSemi(ref expr, id) => {
4065 self.check_expr(&expr);
4070 if self.has_errors.get() {
4071 self.write_error(node_id);
4073 self.write_nil(node_id);
4076 // Combine the diverging and has_error flags.
4077 self.diverges.set(self.diverges.get() | old_diverges);
4078 self.has_errors.set(self.has_errors.get() | old_has_errors);
4081 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
4082 let unit = self.tcx.mk_nil();
4083 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4085 // if the block produces a `!` value, that can always be
4086 // (effectively) coerced to unit.
4088 self.demand_suptype(blk.span, unit, ty);
4092 fn check_block_with_expected(&self,
4093 blk: &'gcx hir::Block,
4094 expected: Expectation<'tcx>) -> Ty<'tcx> {
4096 let mut fcx_ps = self.ps.borrow_mut();
4097 let unsafety_state = fcx_ps.recurse(blk);
4098 replace(&mut *fcx_ps, unsafety_state)
4101 let mut ty = if blk.targeted_by_break {
4102 let unified = self.next_ty_var(TypeVariableOrigin::TypeInference(blk.span));
4103 let coerce_to = expected.only_has_type(self).unwrap_or(unified);
4104 let ctxt = BreakableCtxt {
4106 coerce_to: coerce_to,
4107 break_exprs: vec![],
4111 let (mut ctxt, (e_ty, cause)) = self.with_breakable_ctxt(blk.id, ctxt, || {
4112 for s in &blk.stmts {
4116 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4117 enclosing_breakables.find_breakable(blk.id).coerce_to
4123 e_ty = self.check_expr_with_hint(e, coerce_to);
4124 cause = self.misc(e.span);
4127 e_ty = if self.diverges.get().always() {
4128 self.tcx.types.never
4132 cause = self.misc(blk.span);
4139 if let ExpectHasType(ety) = expected {
4140 if let Some(ref e) = blk.expr {
4141 let result = if !ctxt.may_break {
4142 self.try_coerce(e, e_ty, ctxt.coerce_to)
4144 self.try_find_coercion_lub(&cause, || ctxt.break_exprs.iter().cloned(),
4145 ctxt.unified, e, e_ty)
4148 Ok(ty) => ctxt.unified = ty,
4150 self.report_mismatched_types(&cause, ctxt.unified, e_ty, err).emit(),
4152 } else if self.diverges.get().always() {
4153 // No tail expression and the body diverges; ignore
4154 // the expected type, and keep `!` as the type of the
4157 self.check_block_no_expr(blk, self.tcx.mk_nil(), e_ty);
4162 for s in &blk.stmts {
4166 let mut ty = match blk.expr {
4167 Some(ref e) => self.check_expr_with_expectation(e, expected),
4168 None => if self.diverges.get().always() {
4169 self.tcx.types.never
4175 if let ExpectHasType(ety) = expected {
4176 if let Some(ref e) = blk.expr {
4177 // Coerce the tail expression to the right type.
4178 self.demand_coerce(e, ty, ety);
4180 // We already applied the type (and potentially errored),
4181 // use the expected type to avoid further errors out.
4183 } else if self.diverges.get().always() {
4184 // No tail expression and the body diverges; ignore
4185 // the expected type, and keep `!` as the type of the
4188 self.check_block_no_expr(blk, ty, ety);
4190 // We already applied the type (and potentially errored),
4191 // use the expected type to avoid further errors out.
4198 if self.has_errors.get() || ty.references_error() {
4199 ty = self.tcx.types.err
4202 self.write_ty(blk.id, ty);
4204 *self.ps.borrow_mut() = prev;
4208 pub fn check_block_no_expr(&self, blk: &'gcx hir::Block, ty: Ty<'tcx>, ety: Ty<'tcx>) {
4209 // We're not diverging and there's an expected type, which,
4210 // in case it's not `()`, could result in an error higher-up.
4211 // We have a chance to error here early and be more helpful.
4212 let cause = self.misc(blk.span);
4213 let trace = TypeTrace::types(&cause, false, ty, ety);
4214 match self.sub_types(false, &cause, ty, ety) {
4215 Ok(InferOk { obligations, .. }) => {
4216 // FIXME(#32730) propagate obligations
4217 assert!(obligations.is_empty());
4220 let mut err = self.report_and_explain_type_error(trace, &err);
4222 // Be helpful when the user wrote `{... expr;}` and
4223 // taking the `;` off is enough to fix the error.
4224 let mut extra_semi = None;
4225 if let Some(stmt) = blk.stmts.last() {
4226 if let hir::StmtSemi(ref e, _) = stmt.node {
4227 if self.can_sub_types(self.node_ty(e.id), ety).is_ok() {
4228 extra_semi = Some(stmt);
4232 if let Some(last_stmt) = extra_semi {
4233 let original_span = original_sp(last_stmt.span, blk.span);
4234 let span_semi = Span {
4235 lo: original_span.hi - BytePos(1),
4236 hi: original_span.hi,
4237 ctxt: original_span.ctxt,
4239 err.span_help(span_semi, "consider removing this semicolon:");
4247 // Instantiates the given path, which must refer to an item with the given
4248 // number of type parameters and type.
4249 pub fn instantiate_value_path(&self,
4250 segments: &[hir::PathSegment],
4251 opt_self_ty: Option<Ty<'tcx>>,
4254 node_id: ast::NodeId)
4256 debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4261 // We need to extract the type parameters supplied by the user in
4262 // the path `path`. Due to the current setup, this is a bit of a
4263 // tricky-process; the problem is that resolve only tells us the
4264 // end-point of the path resolution, and not the intermediate steps.
4265 // Luckily, we can (at least for now) deduce the intermediate steps
4266 // just from the end-point.
4268 // There are basically four cases to consider:
4270 // 1. Reference to a constructor of enum variant or struct:
4272 // struct Foo<T>(...)
4273 // enum E<T> { Foo(...) }
4275 // In these cases, the parameters are declared in the type
4278 // 2. Reference to a fn item or a free constant:
4282 // In this case, the path will again always have the form
4283 // `a::b::foo::<T>` where only the final segment should have
4284 // type parameters. However, in this case, those parameters are
4285 // declared on a value, and hence are in the `FnSpace`.
4287 // 3. Reference to a method or an associated constant:
4289 // impl<A> SomeStruct<A> {
4293 // Here we can have a path like
4294 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4295 // may appear in two places. The penultimate segment,
4296 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4297 // final segment, `foo::<B>` contains parameters in fn space.
4299 // 4. Reference to a local variable
4301 // Local variables can't have any type parameters.
4303 // The first step then is to categorize the segments appropriately.
4305 assert!(!segments.is_empty());
4307 let mut ufcs_associated = None;
4308 let mut type_segment = None;
4309 let mut fn_segment = None;
4311 // Case 1. Reference to a struct/variant constructor.
4312 Def::StructCtor(def_id, ..) |
4313 Def::VariantCtor(def_id, ..) => {
4314 // Everything but the final segment should have no
4315 // parameters at all.
4316 let mut generics = self.tcx.item_generics(def_id);
4317 if let Some(def_id) = generics.parent {
4318 // Variant and struct constructors use the
4319 // generics of their parent type definition.
4320 generics = self.tcx.item_generics(def_id);
4322 type_segment = Some((segments.last().unwrap(), generics));
4325 // Case 2. Reference to a top-level value.
4327 Def::Const(def_id) |
4328 Def::Static(def_id, _) => {
4329 fn_segment = Some((segments.last().unwrap(),
4330 self.tcx.item_generics(def_id)));
4333 // Case 3. Reference to a method or associated const.
4334 Def::Method(def_id) |
4335 Def::AssociatedConst(def_id) => {
4336 let container = self.tcx.associated_item(def_id).container;
4338 ty::TraitContainer(trait_did) => {
4339 callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4341 ty::ImplContainer(_) => {}
4344 let generics = self.tcx.item_generics(def_id);
4345 if segments.len() >= 2 {
4346 let parent_generics = self.tcx.item_generics(generics.parent.unwrap());
4347 type_segment = Some((&segments[segments.len() - 2], parent_generics));
4349 // `<T>::assoc` will end up here, and so can `T::assoc`.
4350 let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4351 ufcs_associated = Some((container, self_ty));
4353 fn_segment = Some((segments.last().unwrap(), generics));
4356 // Case 4. Local variable, no generics.
4357 Def::Local(..) | Def::Upvar(..) => {}
4359 _ => bug!("unexpected definition: {:?}", def),
4362 debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4364 // Now that we have categorized what space the parameters for each
4365 // segment belong to, let's sort out the parameters that the user
4366 // provided (if any) into their appropriate spaces. We'll also report
4367 // errors if type parameters are provided in an inappropriate place.
4368 let poly_segments = type_segment.is_some() as usize +
4369 fn_segment.is_some() as usize;
4370 AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4373 Def::Local(def_id) | Def::Upvar(def_id, ..) => {
4374 let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
4375 let ty = self.local_ty(span, nid);
4376 let ty = self.normalize_associated_types_in(span, &ty);
4377 self.write_ty(node_id, ty);
4378 self.write_substs(node_id, ty::ItemSubsts {
4379 substs: self.tcx.intern_substs(&[])
4386 // Now we have to compare the types that the user *actually*
4387 // provided against the types that were *expected*. If the user
4388 // did not provide any types, then we want to substitute inference
4389 // variables. If the user provided some types, we may still need
4390 // to add defaults. If the user provided *too many* types, that's
4392 self.check_path_parameter_count(span, &mut type_segment);
4393 self.check_path_parameter_count(span, &mut fn_segment);
4395 let (fn_start, has_self) = match (type_segment, fn_segment) {
4396 (_, Some((_, generics))) => {
4397 (generics.parent_count(), generics.has_self)
4399 (Some((_, generics)), None) => {
4400 (generics.own_count(), generics.has_self)
4402 (None, None) => (0, false)
4404 let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4405 let mut i = def.index as usize;
4407 let segment = if i < fn_start {
4408 i -= has_self as usize;
4414 let lifetimes = match segment.map(|(s, _)| &s.parameters) {
4415 Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
4416 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4420 if let Some(lifetime) = lifetimes.get(i) {
4421 AstConv::ast_region_to_region(self, lifetime, Some(def))
4423 self.re_infer(span, Some(def)).unwrap()
4426 let mut i = def.index as usize;
4428 let segment = if i < fn_start {
4429 // Handle Self first, so we can adjust the index to match the AST.
4430 if has_self && i == 0 {
4431 return opt_self_ty.unwrap_or_else(|| {
4432 self.type_var_for_def(span, def, substs)
4435 i -= has_self as usize;
4441 let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
4442 Some(&hir::AngleBracketedParameters(ref data)) => {
4443 (&data.types[..], data.infer_types)
4445 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4446 None => (&[][..], true)
4449 // Skip over the lifetimes in the same segment.
4450 if let Some((_, generics)) = segment {
4451 i -= generics.regions.len();
4454 if let Some(ast_ty) = types.get(i) {
4455 // A provided type parameter.
4457 } else if !infer_types && def.has_default {
4458 // No type parameter provided, but a default exists.
4459 let default = self.tcx.item_type(def.def_id);
4462 default.subst_spanned(self.tcx, substs, Some(span))
4465 // No type parameters were provided, we can infer all.
4466 // This can also be reached in some error cases:
4467 // We prefer to use inference variables instead of
4468 // TyError to let type inference recover somewhat.
4469 self.type_var_for_def(span, def, substs)
4473 // The things we are substituting into the type should not contain
4474 // escaping late-bound regions, and nor should the base type scheme.
4475 let ty = self.tcx.item_type(def.def_id());
4476 assert!(!substs.has_escaping_regions());
4477 assert!(!ty.has_escaping_regions());
4479 // Add all the obligations that are required, substituting and
4480 // normalized appropriately.
4481 let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4482 self.add_obligations_for_parameters(
4483 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4486 // Substitute the values for the type parameters into the type of
4487 // the referenced item.
4488 let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4490 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4491 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4492 // is inherent, there is no `Self` parameter, instead, the impl needs
4493 // type parameters, which we can infer by unifying the provided `Self`
4494 // with the substituted impl type.
4495 let ty = self.tcx.item_type(impl_def_id);
4497 let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4498 match self.sub_types(false, &self.misc(span), self_ty, impl_ty) {
4499 Ok(ok) => self.register_infer_ok_obligations(ok),
4502 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4509 debug!("instantiate_value_path: type of {:?} is {:?}",
4512 self.write_substs(node_id, ty::ItemSubsts {
4518 /// Report errors if the provided parameters are too few or too many.
4519 fn check_path_parameter_count(&self,
4521 segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
4522 let (lifetimes, types, infer_types, bindings) = {
4523 match segment.map(|(s, _)| &s.parameters) {
4524 Some(&hir::AngleBracketedParameters(ref data)) => {
4525 (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
4527 Some(&hir::ParenthesizedParameters(_)) => {
4528 span_bug!(span, "parenthesized parameters cannot appear in ExprPath");
4530 None => (&[][..], &[][..], true, &[][..])
4534 let count_lifetime_params = |n| {
4535 format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4537 let count_type_params = |n| {
4538 format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4541 // Check provided lifetime parameters.
4542 let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4543 if lifetimes.len() > lifetime_defs.len() {
4544 let expected_text = count_lifetime_params(lifetime_defs.len());
4545 let actual_text = count_lifetime_params(lifetimes.len());
4546 struct_span_err!(self.tcx.sess, span, E0088,
4547 "too many lifetime parameters provided: \
4548 expected at most {}, found {}",
4549 expected_text, actual_text)
4550 .span_label(span, &format!("expected {}", expected_text))
4552 } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
4553 let expected_text = count_lifetime_params(lifetime_defs.len());
4554 let actual_text = count_lifetime_params(lifetimes.len());
4555 struct_span_err!(self.tcx.sess, span, E0090,
4556 "too few lifetime parameters provided: \
4557 expected {}, found {}",
4558 expected_text, actual_text)
4559 .span_label(span, &format!("expected {}", expected_text))
4563 // The case where there is not enough lifetime parameters is not checked,
4564 // because this is not possible - a function never takes lifetime parameters.
4565 // See discussion for Pull Request 36208.
4567 // Check provided type parameters.
4568 let type_defs = segment.map_or(&[][..], |(_, generics)| {
4569 if generics.parent.is_none() {
4570 &generics.types[generics.has_self as usize..]
4575 let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4576 if types.len() > type_defs.len() {
4577 let span = types[type_defs.len()].span;
4578 let expected_text = count_type_params(type_defs.len());
4579 let actual_text = count_type_params(types.len());
4580 struct_span_err!(self.tcx.sess, span, E0087,
4581 "too many type parameters provided: \
4582 expected at most {}, found {}",
4583 expected_text, actual_text)
4584 .span_label(span, &format!("expected {}", expected_text))
4587 // To prevent derived errors to accumulate due to extra
4588 // type parameters, we force instantiate_value_path to
4589 // use inference variables instead of the provided types.
4591 } else if !infer_types && types.len() < required_len {
4592 let expected_text = count_type_params(required_len);
4593 let actual_text = count_type_params(types.len());
4594 struct_span_err!(self.tcx.sess, span, E0089,
4595 "too few type parameters provided: \
4596 expected {}, found {}",
4597 expected_text, actual_text)
4598 .span_label(span, &format!("expected {}", expected_text))
4602 if !bindings.is_empty() {
4603 span_err!(self.tcx.sess, bindings[0].span, E0182,
4604 "unexpected binding of associated item in expression path \
4605 (only allowed in type paths)");
4609 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4611 where F: Fn() -> Ty<'tcx>
4613 let mut ty = self.resolve_type_vars_with_obligations(ty);
4616 let alternative = f();
4619 if alternative.is_ty_var() || alternative.references_error() {
4620 if !self.is_tainted_by_errors() {
4621 self.type_error_message(sp, |_actual| {
4622 "the type of this value must be known in this context".to_string()
4625 self.demand_suptype(sp, self.tcx.types.err, ty);
4626 ty = self.tcx.types.err;
4628 self.demand_suptype(sp, alternative, ty);
4636 // Resolves `typ` by a single level if `typ` is a type variable. If no
4637 // resolution is possible, then an error is reported.
4638 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4639 self.structurally_resolve_type_or_else(sp, ty, || {
4644 fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4645 ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4646 -> (BreakableCtxt<'gcx, 'tcx>, R) {
4649 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4650 index = enclosing_breakables.stack.len();
4651 enclosing_breakables.by_id.insert(id, index);
4652 enclosing_breakables.stack.push(ctxt);
4656 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4657 debug_assert!(enclosing_breakables.stack.len() == index + 1);
4658 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4659 enclosing_breakables.stack.pop().expect("missing breakable context")
4665 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4666 generics: &hir::Generics,
4668 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4669 generics.ty_params.len(), ty);
4671 // make a vector of booleans initially false, set to true when used
4672 if generics.ty_params.is_empty() { return; }
4673 let mut tps_used = vec![false; generics.ty_params.len()];
4675 for leaf_ty in ty.walk() {
4676 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4677 debug!("Found use of ty param num {}", idx);
4678 tps_used[idx as usize - generics.lifetimes.len()] = true;
4682 for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4684 struct_span_err!(tcx.sess, param.span, E0091,
4685 "type parameter `{}` is unused",
4687 .span_label(param.span, &format!("unused type parameter"))