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.node_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::autoderef::Autoderef;
81 use self::callee::DeferredCallResolution;
82 use self::coercion::{CoerceMany, DynamicCoerceMany};
83 pub use self::compare_method::{compare_impl_method, compare_const_impl};
84 use self::method::MethodCallee;
85 use self::TupleArgumentsFlag::*;
88 use hir::def::{Def, CtorKind};
89 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
90 use rustc_back::slice::ref_slice;
91 use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
92 use rustc::infer::type_variable::{TypeVariableOrigin};
93 use rustc::middle::region;
94 use rustc::ty::subst::{Kind, Subst, Substs};
95 use rustc::traits::{self, FulfillmentContext, ObligationCause, ObligationCauseCode};
96 use rustc::ty::{ParamTy, LvaluePreference, NoPreference, PreferMutLvalue};
97 use rustc::ty::{self, Ty, TyCtxt, Visibility};
98 use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
99 use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
100 use rustc::ty::maps::Providers;
101 use rustc::ty::util::{Representability, IntTypeExt};
102 use errors::DiagnosticBuilder;
103 use require_c_abi_if_variadic;
104 use session::{CompileIncomplete, Session};
107 use util::common::{ErrorReported, indenter};
108 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
110 use std::cell::{Cell, RefCell, Ref, RefMut};
111 use std::collections::hash_map::Entry;
113 use std::fmt::Display;
114 use std::mem::replace;
115 use std::ops::{self, Deref};
116 use syntax::abi::Abi;
118 use syntax::codemap::{self, original_sp, Spanned};
119 use syntax::feature_gate::{GateIssue, emit_feature_err};
121 use syntax::symbol::{Symbol, InternedString, keywords};
122 use syntax::util::lev_distance::find_best_match_for_name;
123 use syntax_pos::{self, BytePos, Span, MultiSpan};
125 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
126 use rustc::hir::itemlikevisit::ItemLikeVisitor;
127 use rustc::hir::map::Node;
128 use rustc::hir::{self, PatKind};
129 use rustc::middle::lang_items;
130 use rustc_back::slice;
131 use rustc_const_math::ConstInt;
147 mod generator_interior;
151 /// A wrapper for InferCtxt's `in_progress_tables` field.
152 #[derive(Copy, Clone)]
153 struct MaybeInProgressTables<'a, 'tcx: 'a> {
154 maybe_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
157 impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> {
158 fn borrow(self) -> Ref<'a, ty::TypeckTables<'tcx>> {
159 match self.maybe_tables {
160 Some(tables) => tables.borrow(),
162 bug!("MaybeInProgressTables: inh/fcx.tables.borrow() with no tables")
167 fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
168 match self.maybe_tables {
169 Some(tables) => tables.borrow_mut(),
171 bug!("MaybeInProgressTables: inh/fcx.tables.borrow_mut() with no tables")
178 /// closures defined within the function. For example:
181 /// bar(move|| { ... })
184 /// Here, the function `foo()` and the closure passed to
185 /// `bar()` will each have their own `FnCtxt`, but they will
186 /// share the inherited fields.
187 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
188 infcx: InferCtxt<'a, 'gcx, 'tcx>,
190 tables: MaybeInProgressTables<'a, 'tcx>,
192 locals: RefCell<NodeMap<Ty<'tcx>>>,
194 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
196 // When we process a call like `c()` where `c` is a closure type,
197 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
198 // `FnOnce` closure. In that case, we defer full resolution of the
199 // call until upvar inference can kick in and make the
200 // decision. We keep these deferred resolutions grouped by the
201 // def-id of the closure, so that once we decide, we can easily go
202 // back and process them.
203 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'gcx, 'tcx>>>>,
205 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
207 deferred_generator_interiors: RefCell<Vec<(hir::BodyId, Ty<'tcx>)>>,
209 // Anonymized types found in explicit return types and their
210 // associated fresh inference variable. Writeback resolves these
211 // variables to get the concrete type, which can be used to
212 // deanonymize TyAnon, after typeck is done with all functions.
213 anon_types: RefCell<NodeMap<Ty<'tcx>>>,
215 /// Each type parameter has an implicit region bound that
216 /// indicates it must outlive at least the function body (the user
217 /// may specify stronger requirements). This field indicates the
218 /// region of the callee. If it is `None`, then the parameter
219 /// environment is for an item or something where the "callee" is
221 implicit_region_bound: Option<ty::Region<'tcx>>,
223 body_id: Option<hir::BodyId>,
226 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
227 type Target = InferCtxt<'a, 'gcx, 'tcx>;
228 fn deref(&self) -> &Self::Target {
233 /// When type-checking an expression, we propagate downward
234 /// whatever type hint we are able in the form of an `Expectation`.
235 #[derive(Copy, Clone, Debug)]
236 pub enum Expectation<'tcx> {
237 /// We know nothing about what type this expression should have.
240 /// This expression is an `if` condition, it must resolve to `bool`.
243 /// This expression should have the type given (or some subtype)
244 ExpectHasType(Ty<'tcx>),
246 /// This expression will be cast to the `Ty`
247 ExpectCastableToType(Ty<'tcx>),
249 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
250 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
251 ExpectRvalueLikeUnsized(Ty<'tcx>),
254 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
255 // Disregard "castable to" expectations because they
256 // can lead us astray. Consider for example `if cond
257 // {22} else {c} as u8` -- if we propagate the
258 // "castable to u8" constraint to 22, it will pick the
259 // type 22u8, which is overly constrained (c might not
260 // be a u8). In effect, the problem is that the
261 // "castable to" expectation is not the tightest thing
262 // we can say, so we want to drop it in this case.
263 // The tightest thing we can say is "must unify with
264 // else branch". Note that in the case of a "has type"
265 // constraint, this limitation does not hold.
267 // If the expected type is just a type variable, then don't use
268 // an expected type. Otherwise, we might write parts of the type
269 // when checking the 'then' block which are incompatible with the
271 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
273 ExpectHasType(ety) => {
274 let ety = fcx.shallow_resolve(ety);
275 if !ety.is_ty_var() {
281 ExpectRvalueLikeUnsized(ety) => {
282 ExpectRvalueLikeUnsized(ety)
288 /// Provide an expectation for an rvalue expression given an *optional*
289 /// hint, which is not required for type safety (the resulting type might
290 /// be checked higher up, as is the case with `&expr` and `box expr`), but
291 /// is useful in determining the concrete type.
293 /// The primary use case is where the expected type is a fat pointer,
294 /// like `&[isize]`. For example, consider the following statement:
296 /// let x: &[isize] = &[1, 2, 3];
298 /// In this case, the expected type for the `&[1, 2, 3]` expression is
299 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
300 /// expectation `ExpectHasType([isize])`, that would be too strong --
301 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
302 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
303 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
304 /// which still is useful, because it informs integer literals and the like.
305 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
306 /// for examples of where this comes up,.
307 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
308 match fcx.tcx.struct_tail(ty).sty {
309 ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
310 ExpectRvalueLikeUnsized(ty)
312 _ => ExpectHasType(ty)
316 // Resolves `expected` by a single level if it is a variable. If
317 // there is no expected type or resolution is not possible (e.g.,
318 // no constraints yet present), just returns `None`.
319 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
321 NoExpectation => NoExpectation,
322 ExpectIfCondition => ExpectIfCondition,
323 ExpectCastableToType(t) => {
324 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
326 ExpectHasType(t) => {
327 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
329 ExpectRvalueLikeUnsized(t) => {
330 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
335 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
336 match self.resolve(fcx) {
337 NoExpectation => None,
338 ExpectIfCondition => Some(fcx.tcx.types.bool),
339 ExpectCastableToType(ty) |
341 ExpectRvalueLikeUnsized(ty) => Some(ty),
345 /// It sometimes happens that we want to turn an expectation into
346 /// a **hard constraint** (i.e., something that must be satisfied
347 /// for the program to type-check). `only_has_type` will return
348 /// such a constraint, if it exists.
349 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
350 match self.resolve(fcx) {
351 ExpectHasType(ty) => Some(ty),
352 ExpectIfCondition => Some(fcx.tcx.types.bool),
353 NoExpectation | ExpectCastableToType(_) | ExpectRvalueLikeUnsized(_) => None,
357 /// Like `only_has_type`, but instead of returning `None` if no
358 /// hard constraint exists, creates a fresh type variable.
359 fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
360 self.only_has_type(fcx)
361 .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
365 #[derive(Copy, Clone)]
366 pub struct UnsafetyState {
367 pub def: ast::NodeId,
368 pub unsafety: hir::Unsafety,
369 pub unsafe_push_count: u32,
374 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
375 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
378 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
379 match self.unsafety {
380 // If this unsafe, then if the outer function was already marked as
381 // unsafe we shouldn't attribute the unsafe'ness to the block. This
382 // way the block can be warned about instead of ignoring this
383 // extraneous block (functions are never warned about).
384 hir::Unsafety::Unsafe if self.from_fn => *self,
387 let (unsafety, def, count) = match blk.rules {
388 hir::PushUnsafeBlock(..) =>
389 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
390 hir::PopUnsafeBlock(..) =>
391 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
392 hir::UnsafeBlock(..) =>
393 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
395 (unsafety, self.def, self.unsafe_push_count),
399 unsafe_push_count: count,
406 #[derive(Debug, Copy, Clone)]
412 /// Tracks whether executing a node may exit normally (versus
413 /// return/break/panic, which "diverge", leaving dead code in their
414 /// wake). Tracked semi-automatically (through type variables marked
415 /// as diverging), with some manual adjustments for control-flow
416 /// primitives (approximating a CFG).
417 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
419 /// Potentially unknown, some cases converge,
420 /// others require a CFG to determine them.
423 /// Definitely known to diverge and therefore
424 /// not reach the next sibling or its parent.
427 /// Same as `Always` but with a reachability
428 /// warning already emitted
432 // Convenience impls for combinig `Diverges`.
434 impl ops::BitAnd for Diverges {
436 fn bitand(self, other: Self) -> Self {
437 cmp::min(self, other)
441 impl ops::BitOr for Diverges {
443 fn bitor(self, other: Self) -> Self {
444 cmp::max(self, other)
448 impl ops::BitAndAssign for Diverges {
449 fn bitand_assign(&mut self, other: Self) {
450 *self = *self & other;
454 impl ops::BitOrAssign for Diverges {
455 fn bitor_assign(&mut self, other: Self) {
456 *self = *self | other;
461 fn always(self) -> bool {
462 self >= Diverges::Always
466 pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
469 // this is `null` for loops where break with a value is illegal,
470 // such as `while`, `for`, and `while let`
471 coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>,
474 pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
475 stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
476 by_id: NodeMap<usize>,
479 impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
480 fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
481 let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
482 bug!("could not find enclosing breakable with id {}", target_id);
488 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
489 body_id: ast::NodeId,
491 /// The parameter environment used for proving trait obligations
492 /// in this function. This can change when we descend into
493 /// closures (as they bring new things into scope), hence it is
494 /// not part of `Inherited` (as of the time of this writing,
495 /// closures do not yet change the environment, but they will
497 param_env: ty::ParamEnv<'tcx>,
499 // Number of errors that had been reported when we started
500 // checking this function. On exit, if we find that *more* errors
501 // have been reported, we will skip regionck and other work that
502 // expects the types within the function to be consistent.
503 err_count_on_creation: usize,
505 ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>,
507 yield_ty: Option<Ty<'tcx>>,
509 ps: RefCell<UnsafetyState>,
511 /// Whether the last checked node generates a divergence (e.g.,
512 /// `return` will set this to Always). In general, when entering
513 /// an expression or other node in the tree, the initial value
514 /// indicates whether prior parts of the containing expression may
515 /// have diverged. It is then typically set to `Maybe` (and the
516 /// old value remembered) for processing the subparts of the
517 /// current expression. As each subpart is processed, they may set
518 /// the flag to `Always` etc. Finally, at the end, we take the
519 /// result and "union" it with the original value, so that when we
520 /// return the flag indicates if any subpart of the the parent
521 /// expression (up to and including this part) has diverged. So,
522 /// if you read it after evaluating a subexpression `X`, the value
523 /// you get indicates whether any subexpression that was
524 /// evaluating up to and including `X` diverged.
526 /// We use this flag for two purposes:
528 /// - To warn about unreachable code: if, after processing a
529 /// sub-expression but before we have applied the effects of the
530 /// current node, we see that the flag is set to `Always`, we
531 /// can issue a warning. This corresponds to something like
532 /// `foo(return)`; we warn on the `foo()` expression. (We then
533 /// update the flag to `WarnedAlways` to suppress duplicate
534 /// reports.) Similarly, if we traverse to a fresh statement (or
535 /// tail expression) from a `Always` setting, we will issue a
536 /// warning. This corresponds to something like `{return;
537 /// foo();}` or `{return; 22}`, where we would warn on the
540 /// - To permit assignment into a local variable or other lvalue
541 /// (including the "return slot") of type `!`. This is allowed
542 /// if **either** the type of value being assigned is `!`, which
543 /// means the current code is dead, **or** the expression's
544 /// diverging flag is true, which means that a diverging value was
545 /// wrapped (e.g., `let x: ! = foo(return)`).
547 /// To repeat the last point: an expression represents dead-code
548 /// if, after checking it, **either** its type is `!` OR the
549 /// diverges flag is set to something other than `Maybe`.
550 diverges: Cell<Diverges>,
552 /// Whether any child nodes have any type errors.
553 has_errors: Cell<bool>,
555 enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
557 inh: &'a Inherited<'a, 'gcx, 'tcx>,
560 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
561 type Target = Inherited<'a, 'gcx, 'tcx>;
562 fn deref(&self) -> &Self::Target {
567 /// Helper type of a temporary returned by Inherited::build(...).
568 /// Necessary because we can't write the following bound:
569 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
570 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
571 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>,
575 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
576 pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId)
577 -> InheritedBuilder<'a, 'gcx, 'tcx> {
578 let hir_id_root = if def_id.is_local() {
579 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
580 let hir_id = tcx.hir.definitions().node_to_hir_id(node_id);
581 DefId::local(hir_id.owner)
587 infcx: tcx.infer_ctxt().with_fresh_in_progress_tables(hir_id_root),
593 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
594 fn enter<F, R>(&'tcx mut self, f: F) -> R
595 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
597 let def_id = self.def_id;
598 self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
602 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
603 fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> Self {
605 let item_id = tcx.hir.as_local_node_id(def_id);
606 let body_id = item_id.and_then(|id| tcx.hir.maybe_body_owned_by(id));
607 let implicit_region_bound = body_id.map(|body_id| {
608 let body = tcx.hir.body(body_id);
609 tcx.mk_region(ty::ReScope(region::Scope::CallSite(body.value.hir_id.local_id)))
613 tables: MaybeInProgressTables {
614 maybe_tables: infcx.in_progress_tables,
617 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
618 locals: RefCell::new(NodeMap()),
619 deferred_call_resolutions: RefCell::new(DefIdMap()),
620 deferred_cast_checks: RefCell::new(Vec::new()),
621 deferred_generator_interiors: RefCell::new(Vec::new()),
622 anon_types: RefCell::new(NodeMap()),
623 implicit_region_bound,
628 fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
629 debug!("register_predicate({:?})", obligation);
630 if obligation.has_escaping_regions() {
631 span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
636 .register_predicate_obligation(self, obligation);
639 fn register_predicates<I>(&self, obligations: I)
640 where I: IntoIterator<Item = traits::PredicateObligation<'tcx>> {
641 for obligation in obligations {
642 self.register_predicate(obligation);
646 fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
647 self.register_predicates(infer_ok.obligations);
651 fn normalize_associated_types_in<T>(&self,
653 body_id: ast::NodeId,
654 param_env: ty::ParamEnv<'tcx>,
656 where T : TypeFoldable<'tcx>
658 let ok = self.normalize_associated_types_in_as_infer_ok(span, body_id, param_env, value);
659 self.register_infer_ok_obligations(ok)
662 fn normalize_associated_types_in_as_infer_ok<T>(&self,
664 body_id: ast::NodeId,
665 param_env: ty::ParamEnv<'tcx>,
668 where T : TypeFoldable<'tcx>
670 debug!("normalize_associated_types_in(value={:?})", value);
671 let mut selcx = traits::SelectionContext::new(self);
672 let cause = ObligationCause::misc(span, body_id);
673 let traits::Normalized { value, obligations } =
674 traits::normalize(&mut selcx, param_env, cause, value);
675 debug!("normalize_associated_types_in: result={:?} predicates={:?}",
678 InferOk { value, obligations }
681 /// Replace any late-bound regions bound in `value` with
682 /// free variants attached to `all_outlive_scope`.
683 fn liberate_late_bound_regions<T>(&self,
684 all_outlive_scope: DefId,
685 value: &ty::Binder<T>)
687 where T: TypeFoldable<'tcx>
689 self.tcx.replace_late_bound_regions(value, |br| {
690 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
691 scope: all_outlive_scope,
698 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
700 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
701 fn visit_item(&mut self, i: &'tcx hir::Item) {
702 check_item_type(self.tcx, i);
704 fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
705 fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
708 pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> {
709 tcx.sess.track_errors(|| {
710 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
711 tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor());
715 pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> {
716 tcx.sess.track_errors(|| {
717 tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx });
721 pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), CompileIncomplete> {
722 tcx.typeck_item_bodies(LOCAL_CRATE)
725 fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum)
726 -> Result<(), CompileIncomplete>
728 debug_assert!(crate_num == LOCAL_CRATE);
729 Ok(tcx.sess.track_errors(|| {
730 for body_owner_def_id in tcx.body_owners() {
731 tcx.typeck_tables_of(body_owner_def_id);
736 pub fn provide(providers: &mut Providers) {
737 *providers = Providers {
748 fn generator_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
750 -> Option<ty::PolyGenSig<'tcx>> {
751 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
752 let hir_id = tcx.hir.node_to_hir_id(node_id);
753 tcx.typeck_tables_of(def_id).generator_sigs()[hir_id].map(|s| ty::Binder(s))
756 fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
759 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
760 let hir_id = tcx.hir.node_to_hir_id(node_id);
761 tcx.typeck_tables_of(def_id).closure_kinds()[hir_id].0
764 fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
766 -> Option<ty::Destructor> {
767 tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
770 /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))`
771 /// with information about it's body-id and fn-decl (if any). Otherwise,
774 /// If this function returns "some", then `typeck_tables(def_id)` will
775 /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or
776 /// may not succeed. In some cases where this function returns `None`
777 /// (notably closures), `typeck_tables(def_id)` would wind up
778 /// redirecting to the owning function.
779 fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
781 -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)>
783 match tcx.hir.get(id) {
784 hir::map::NodeItem(item) => {
786 hir::ItemConst(_, body) |
787 hir::ItemStatic(_, _, body) =>
789 hir::ItemFn(ref decl, .., body) =>
790 Some((body, Some(decl))),
795 hir::map::NodeTraitItem(item) => {
797 hir::TraitItemKind::Const(_, Some(body)) =>
799 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) =>
800 Some((body, Some(&sig.decl))),
805 hir::map::NodeImplItem(item) => {
807 hir::ImplItemKind::Const(_, body) =>
809 hir::ImplItemKind::Method(ref sig, body) =>
810 Some((body, Some(&sig.decl))),
815 hir::map::NodeExpr(expr) => {
816 // FIXME(eddyb) Closures should have separate
817 // function definition IDs and expression IDs.
818 // Type-checking should not let closures get
819 // this far in a constant position.
820 // Assume that everything other than closures
821 // is a constant "initializer" expression.
823 hir::ExprClosure(..) =>
826 Some((hir::BodyId { node_id: expr.id }, None)),
833 fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
836 // Closures' tables come from their outermost function,
837 // as they are part of the same "inference environment".
838 let outer_def_id = tcx.closure_base_def_id(def_id);
839 if outer_def_id != def_id {
840 return tcx.has_typeck_tables(outer_def_id);
843 let id = tcx.hir.as_local_node_id(def_id).unwrap();
844 primary_body_of(tcx, id).is_some()
847 fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
849 -> &'tcx ty::TypeckTables<'tcx> {
850 // Closures' tables come from their outermost function,
851 // as they are part of the same "inference environment".
852 let outer_def_id = tcx.closure_base_def_id(def_id);
853 if outer_def_id != def_id {
854 return tcx.typeck_tables_of(outer_def_id);
857 let id = tcx.hir.as_local_node_id(def_id).unwrap();
858 let span = tcx.hir.span(id);
860 // Figure out what primary body this item has.
861 let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| {
862 span_bug!(span, "can't type-check body of {:?}", def_id);
864 let body = tcx.hir.body(body_id);
866 let tables = Inherited::build(tcx, def_id).enter(|inh| {
867 let param_env = tcx.param_env(def_id);
868 let fcx = if let Some(decl) = fn_decl {
869 let fn_sig = tcx.fn_sig(def_id);
871 check_abi(tcx, span, fn_sig.abi());
873 // Compute the fty from point of view of inside fn.
875 inh.liberate_late_bound_regions(def_id, &fn_sig);
877 inh.normalize_associated_types_in(body.value.span,
882 check_fn(&inh, param_env, fn_sig, decl, id, body, false).0
884 let fcx = FnCtxt::new(&inh, param_env, body.value.id);
885 let expected_type = tcx.type_of(def_id);
886 let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
887 fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
889 // Gather locals in statics (because of block expressions).
890 // This is technically unnecessary because locals in static items are forbidden,
891 // but prevents type checking from blowing up before const checking can properly
893 GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
895 fcx.check_expr_coercable_to_type(&body.value, expected_type);
900 fcx.select_all_obligations_and_apply_defaults();
901 fcx.closure_analyze(body);
902 fcx.select_obligations_where_possible();
904 fcx.resolve_generator_interiors(def_id);
905 fcx.select_all_obligations_or_error();
907 if fn_decl.is_some() {
908 fcx.regionck_fn(id, body);
910 fcx.regionck_expr(body);
913 fcx.resolve_type_vars_in_body(body)
916 // Consistency check our TypeckTables instance can hold all ItemLocalIds
917 // it will need to hold.
918 assert_eq!(tables.local_id_root,
919 Some(DefId::local(tcx.hir.definitions().node_to_hir_id(id).owner)));
923 fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
924 if !tcx.sess.target.target.is_abi_supported(abi) {
925 struct_span_err!(tcx.sess, span, E0570,
926 "The ABI `{}` is not supported for the current target", abi).emit()
930 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
931 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
934 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
935 fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
938 // infer the variable's type
939 let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
940 self.fcx.locals.borrow_mut().insert(nid, var_ty);
944 // take type that the user specified
945 self.fcx.locals.borrow_mut().insert(nid, typ);
952 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
953 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
954 NestedVisitorMap::None
957 // Add explicitly-declared locals.
958 fn visit_local(&mut self, local: &'gcx hir::Local) {
959 let o_ty = match local.ty {
960 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
963 self.assign(local.span, local.id, o_ty);
964 debug!("Local variable {:?} is assigned type {}",
966 self.fcx.ty_to_string(
967 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
968 intravisit::walk_local(self, local);
971 // Add pattern bindings.
972 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
973 if let PatKind::Binding(_, _, ref path1, _) = p.node {
974 let var_ty = self.assign(p.span, p.id, None);
976 self.fcx.require_type_is_sized(var_ty, p.span,
977 traits::VariableType(p.id));
979 debug!("Pattern binding {} is assigned to {} with type {:?}",
981 self.fcx.ty_to_string(
982 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
985 intravisit::walk_pat(self, p);
988 // Don't descend into the bodies of nested closures
989 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
990 _: hir::BodyId, _: Span, _: ast::NodeId) { }
993 /// Helper used for fns and closures. Does the grungy work of checking a function
994 /// body and returns the function context used for that purpose, since in the case of a fn item
995 /// there is still a bit more to do.
998 /// * inherited: other fields inherited from the enclosing fn (if any)
999 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
1000 param_env: ty::ParamEnv<'tcx>,
1001 fn_sig: ty::FnSig<'tcx>,
1002 decl: &'gcx hir::FnDecl,
1004 body: &'gcx hir::Body,
1005 can_be_generator: bool)
1006 -> (FnCtxt<'a, 'gcx, 'tcx>, Option<ty::GeneratorInterior<'tcx>>)
1008 let mut fn_sig = fn_sig.clone();
1010 debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env);
1012 // Create the function context. This is either derived from scratch or,
1013 // in the case of function expressions, based on the outer context.
1014 let mut fcx = FnCtxt::new(inherited, param_env, body.value.id);
1015 *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
1017 let ret_ty = fn_sig.output();
1018 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::SizedReturnType);
1019 let ret_ty = fcx.instantiate_anon_types(&ret_ty);
1020 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
1021 fn_sig = fcx.tcx.mk_fn_sig(
1022 fn_sig.inputs().iter().cloned(),
1029 let span = body.value.span;
1031 if body.is_generator && can_be_generator {
1032 fcx.yield_ty = Some(fcx.next_ty_var(TypeVariableOrigin::TypeInference(span)));
1035 GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
1037 // Add formal parameters.
1038 for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
1039 // Check the pattern.
1040 fcx.check_pat_arg(&arg.pat, arg_ty, true);
1042 // Check that argument is Sized.
1043 // The check for a non-trivial pattern is a hack to avoid duplicate warnings
1044 // for simple cases like `fn foo(x: Trait)`,
1045 // where we would error once on the parameter as a whole, and once on the binding `x`.
1046 if arg.pat.simple_name().is_none() {
1047 fcx.require_type_is_sized(arg_ty, decl.output.span(), traits::MiscObligation);
1050 fcx.write_ty(arg.hir_id, arg_ty);
1053 let fn_hir_id = fcx.tcx.hir.node_to_hir_id(fn_id);
1054 let gen_ty = if can_be_generator && body.is_generator {
1055 let gen_sig = ty::GenSig {
1056 yield_ty: fcx.yield_ty.unwrap(),
1059 inherited.tables.borrow_mut().generator_sigs_mut().insert(fn_hir_id, Some(gen_sig));
1061 let witness = fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span));
1062 fcx.deferred_generator_interiors.borrow_mut().push((body.id(), witness));
1063 let interior = ty::GeneratorInterior::new(witness);
1065 inherited.tables.borrow_mut().generator_interiors_mut().insert(fn_hir_id, interior);
1069 inherited.tables.borrow_mut().generator_sigs_mut().insert(fn_hir_id, None);
1072 inherited.tables.borrow_mut().liberated_fn_sigs_mut().insert(fn_hir_id, fn_sig);
1074 fcx.check_return_expr(&body.value);
1076 // Finalize the return check by taking the LUB of the return types
1077 // we saw and assigning it to the expected return type. This isn't
1078 // really expected to fail, since the coercions would have failed
1079 // earlier when trying to find a LUB.
1081 // However, the behavior around `!` is sort of complex. In the
1082 // event that the `actual_return_ty` comes back as `!`, that
1083 // indicates that the fn either does not return or "returns" only
1084 // values of type `!`. In this case, if there is an expected
1085 // return type that is *not* `!`, that should be ok. But if the
1086 // return type is being inferred, we want to "fallback" to `!`:
1088 // let x = move || panic!();
1090 // To allow for that, I am creating a type variable with diverging
1091 // fallback. This was deemed ever so slightly better than unifying
1092 // the return value with `!` because it allows for the caller to
1093 // make more assumptions about the return type (e.g., they could do
1095 // let y: Option<u32> = Some(x());
1097 // which would then cause this return type to become `u32`, not
1099 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
1100 let mut actual_return_ty = coercion.complete(&fcx);
1101 if actual_return_ty.is_never() {
1102 actual_return_ty = fcx.next_diverging_ty_var(
1103 TypeVariableOrigin::DivergingFn(span));
1105 fcx.demand_suptype(span, ret_ty, actual_return_ty);
1110 fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1113 let def_id = tcx.hir.local_def_id(id);
1114 let def = tcx.adt_def(def_id);
1115 def.destructor(tcx); // force the destructor to be evaluated
1116 check_representable(tcx, span, def_id);
1118 if def.repr.simd() {
1119 check_simd(tcx, span, def_id);
1122 check_packed(tcx, span, def_id);
1125 fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1128 let def_id = tcx.hir.local_def_id(id);
1129 let def = tcx.adt_def(def_id);
1130 def.destructor(tcx); // force the destructor to be evaluated
1131 check_representable(tcx, span, def_id);
1133 check_packed(tcx, span, def_id);
1136 pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
1137 debug!("check_item_type(it.id={}, it.name={})",
1139 tcx.item_path_str(tcx.hir.local_def_id(it.id)));
1140 let _indenter = indenter();
1142 // Consts can play a role in type-checking, so they are included here.
1143 hir::ItemStatic(..) |
1144 hir::ItemConst(..) => {
1145 tcx.typeck_tables_of(tcx.hir.local_def_id(it.id));
1147 hir::ItemEnum(ref enum_definition, _) => {
1150 &enum_definition.variants,
1153 hir::ItemFn(..) => {} // entirely within check_item_body
1154 hir::ItemImpl(.., ref impl_item_refs) => {
1155 debug!("ItemImpl {} with id {}", it.name, it.id);
1156 let impl_def_id = tcx.hir.local_def_id(it.id);
1157 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1158 check_impl_items_against_trait(tcx,
1163 let trait_def_id = impl_trait_ref.def_id;
1164 check_on_unimplemented(tcx, trait_def_id, it);
1167 hir::ItemTrait(..) => {
1168 let def_id = tcx.hir.local_def_id(it.id);
1169 check_on_unimplemented(tcx, def_id, it);
1171 hir::ItemStruct(..) => {
1172 check_struct(tcx, it.id, it.span);
1174 hir::ItemUnion(..) => {
1175 check_union(tcx, it.id, it.span);
1177 hir::ItemTy(_, ref generics) => {
1178 let def_id = tcx.hir.local_def_id(it.id);
1179 let pty_ty = tcx.type_of(def_id);
1180 check_bounds_are_used(tcx, generics, pty_ty);
1182 hir::ItemForeignMod(ref m) => {
1183 check_abi(tcx, it.span, m.abi);
1185 if m.abi == Abi::RustIntrinsic {
1186 for item in &m.items {
1187 intrinsic::check_intrinsic_type(tcx, item);
1189 } else if m.abi == Abi::PlatformIntrinsic {
1190 for item in &m.items {
1191 intrinsic::check_platform_intrinsic_type(tcx, item);
1194 for item in &m.items {
1195 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
1196 if !generics.types.is_empty() {
1197 let mut err = struct_span_err!(tcx.sess, item.span, E0044,
1198 "foreign items may not have type parameters");
1199 span_help!(&mut err, item.span,
1200 "consider using specialization instead of \
1205 if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
1206 require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
1211 _ => {/* nothing to do */ }
1215 fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1216 trait_def_id: DefId,
1218 let item_def_id = tcx.hir.local_def_id(item.id);
1219 // an error would be reported if this fails.
1220 let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id);
1223 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1224 impl_item: &hir::ImplItem,
1227 let mut err = struct_span_err!(
1228 tcx.sess, impl_item.span, E0520,
1229 "`{}` specializes an item from a parent `impl`, but \
1230 that item is not marked `default`",
1232 err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
1235 match tcx.span_of_impl(parent_impl) {
1237 err.span_label(span, "parent `impl` is here");
1238 err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
1242 err.note(&format!("parent implementation is in crate `{}`", cname));
1249 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1250 trait_def: &ty::TraitDef,
1252 impl_item: &hir::ImplItem)
1254 let ancestors = trait_def.ancestors(tcx, impl_id);
1256 let kind = match impl_item.node {
1257 hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
1258 hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
1259 hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
1261 let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
1262 .map(|node_item| node_item.map(|parent| parent.defaultness));
1264 if let Some(parent) = parent {
1265 if tcx.impl_item_is_final(&parent) {
1266 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1272 fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1275 impl_trait_ref: ty::TraitRef<'tcx>,
1276 impl_item_refs: &[hir::ImplItemRef]) {
1277 // If the trait reference itself is erroneous (so the compilation is going
1278 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1279 // isn't populated for such impls.
1280 if impl_trait_ref.references_error() { return; }
1282 // Locate trait definition and items
1283 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1284 let mut overridden_associated_type = None;
1286 let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
1288 // Check existing impl methods to see if they are both present in trait
1289 // and compatible with trait signature
1290 for impl_item in impl_items() {
1291 let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
1292 let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
1293 .find(|ac| ac.name == ty_impl_item.name);
1295 // Check that impl definition matches trait definition
1296 if let Some(ty_trait_item) = ty_trait_item {
1297 match impl_item.node {
1298 hir::ImplItemKind::Const(..) => {
1299 // Find associated const definition.
1300 if ty_trait_item.kind == ty::AssociatedKind::Const {
1301 compare_const_impl(tcx,
1307 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1308 "item `{}` is an associated const, \
1309 which doesn't match its trait `{}`",
1312 err.span_label(impl_item.span, "does not match trait");
1313 // We can only get the spans from local trait definition
1314 // Same for E0324 and E0325
1315 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1316 err.span_label(trait_span, "item in trait");
1321 hir::ImplItemKind::Method(..) => {
1322 let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
1323 if ty_trait_item.kind == ty::AssociatedKind::Method {
1324 let err_count = tcx.sess.err_count();
1325 compare_impl_method(tcx,
1331 true); // start with old-broken-mode
1332 if err_count == tcx.sess.err_count() {
1333 // old broken mode did not report an error. Try with the new mode.
1334 compare_impl_method(tcx,
1340 false); // use the new mode
1343 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1344 "item `{}` is an associated method, \
1345 which doesn't match its trait `{}`",
1348 err.span_label(impl_item.span, "does not match trait");
1349 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1350 err.span_label(trait_span, "item in trait");
1355 hir::ImplItemKind::Type(_) => {
1356 if ty_trait_item.kind == ty::AssociatedKind::Type {
1357 if ty_trait_item.defaultness.has_value() {
1358 overridden_associated_type = Some(impl_item);
1361 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1362 "item `{}` is an associated type, \
1363 which doesn't match its trait `{}`",
1366 err.span_label(impl_item.span, "does not match trait");
1367 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1368 err.span_label(trait_span, "item in trait");
1376 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1379 // Check for missing items from trait
1380 let mut missing_items = Vec::new();
1381 let mut invalidated_items = Vec::new();
1382 let associated_type_overridden = overridden_associated_type.is_some();
1383 for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
1384 let is_implemented = trait_def.ancestors(tcx, impl_id)
1385 .defs(tcx, trait_item.name, trait_item.kind)
1387 .map(|node_item| !node_item.node.is_from_trait())
1390 if !is_implemented {
1391 if !trait_item.defaultness.has_value() {
1392 missing_items.push(trait_item);
1393 } else if associated_type_overridden {
1394 invalidated_items.push(trait_item.name);
1399 if !missing_items.is_empty() {
1400 let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
1401 "not all trait items implemented, missing: `{}`",
1402 missing_items.iter()
1403 .map(|trait_item| trait_item.name.to_string())
1404 .collect::<Vec<_>>().join("`, `"));
1405 err.span_label(impl_span, format!("missing `{}` in implementation",
1406 missing_items.iter()
1407 .map(|trait_item| trait_item.name.to_string())
1408 .collect::<Vec<_>>().join("`, `")));
1409 for trait_item in missing_items {
1410 if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
1411 err.span_label(span, format!("`{}` from trait", trait_item.name));
1413 err.note_trait_signature(trait_item.name.to_string(),
1414 trait_item.signature(&tcx));
1420 if !invalidated_items.is_empty() {
1421 let invalidator = overridden_associated_type.unwrap();
1422 span_err!(tcx.sess, invalidator.span, E0399,
1423 "the following trait items need to be reimplemented \
1424 as `{}` was overridden: `{}`",
1426 invalidated_items.iter()
1427 .map(|name| name.to_string())
1428 .collect::<Vec<_>>().join("`, `"))
1432 /// Checks whether a type can be represented in memory. In particular, it
1433 /// identifies types that contain themselves without indirection through a
1434 /// pointer, which would mean their size is unbounded.
1435 fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1439 let rty = tcx.type_of(item_def_id);
1441 // Check that it is possible to represent this type. This call identifies
1442 // (1) types that contain themselves and (2) types that contain a different
1443 // recursive type. It is only necessary to throw an error on those that
1444 // contain themselves. For case 2, there must be an inner type that will be
1445 // caught by case 1.
1446 match rty.is_representable(tcx, sp) {
1447 Representability::SelfRecursive(spans) => {
1448 let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
1450 err.span_label(span, "recursive without indirection");
1455 Representability::Representable | Representability::ContainsRecursive => (),
1460 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1461 let t = tcx.type_of(def_id);
1463 ty::TyAdt(def, substs) if def.is_struct() => {
1464 let fields = &def.struct_variant().fields;
1465 if fields.is_empty() {
1466 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1469 let e = fields[0].ty(tcx, substs);
1470 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1471 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1472 .span_label(sp, "SIMD elements must have the same type")
1477 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1478 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1480 span_err!(tcx.sess, sp, E0077,
1481 "SIMD vector element type should be machine type");
1490 fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1491 if tcx.adt_def(def_id).repr.packed() {
1492 if tcx.adt_def(def_id).repr.align > 0 {
1493 struct_span_err!(tcx.sess, sp, E0587,
1494 "type has conflicting packed and align representation hints").emit();
1496 else if check_packed_inner(tcx, def_id, &mut Vec::new()) {
1497 struct_span_err!(tcx.sess, sp, E0588,
1498 "packed type cannot transitively contain a `[repr(align)]` type").emit();
1503 fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1505 stack: &mut Vec<DefId>) -> bool {
1506 let t = tcx.type_of(def_id);
1507 if stack.contains(&def_id) {
1508 debug!("check_packed_inner: {:?} is recursive", t);
1512 ty::TyAdt(def, substs) if def.is_struct() || def.is_union() => {
1513 if tcx.adt_def(def.did).repr.align > 0 {
1516 // push struct def_id before checking fields
1518 for field in &def.struct_variant().fields {
1519 let f = field.ty(tcx, substs);
1521 ty::TyAdt(def, _) => {
1522 if check_packed_inner(tcx, def.did, stack) {
1529 // only need to pop if not early out
1537 #[allow(trivial_numeric_casts)]
1538 pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1540 vs: &'tcx [hir::Variant],
1542 let def_id = tcx.hir.local_def_id(id);
1543 let def = tcx.adt_def(def_id);
1544 def.destructor(tcx); // force the destructor to be evaluated
1546 if vs.is_empty() && tcx.has_attr(def_id, "repr") {
1548 tcx.sess, sp, E0084,
1549 "unsupported representation for zero-variant enum")
1550 .span_label(sp, "unsupported enum representation")
1554 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1555 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1556 if !tcx.sess.features.borrow().repr128 {
1557 emit_feature_err(&tcx.sess.parse_sess,
1560 GateIssue::Language,
1561 "repr with 128-bit type is unstable");
1566 if let Some(e) = v.node.disr_expr {
1567 tcx.typeck_tables_of(tcx.hir.local_def_id(e.node_id));
1571 let mut disr_vals: Vec<ConstInt> = Vec::new();
1572 for (discr, v) in def.discriminants(tcx).zip(vs) {
1573 // Check for duplicate discriminant values
1574 if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
1575 let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
1576 let variant_i = tcx.hir.expect_variant(variant_i_node_id);
1577 let i_span = match variant_i.node.disr_expr {
1578 Some(expr) => tcx.hir.span(expr.node_id),
1579 None => tcx.hir.span(variant_i_node_id)
1581 let span = match v.node.disr_expr {
1582 Some(expr) => tcx.hir.span(expr.node_id),
1585 struct_span_err!(tcx.sess, span, E0081,
1586 "discriminant value `{}` already exists", disr_vals[i])
1587 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1588 .span_label(span , format!("enum already has `{}`", disr_vals[i]))
1591 disr_vals.push(discr);
1594 check_representable(tcx, sp, def_id);
1597 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1598 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1600 fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
1601 -> ty::GenericPredicates<'tcx>
1604 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1605 let item_id = tcx.hir.ty_param_owner(node_id);
1606 let item_def_id = tcx.hir.local_def_id(item_id);
1607 let generics = tcx.generics_of(item_def_id);
1608 let index = generics.type_param_to_index[&def_id.index];
1609 ty::GenericPredicates {
1611 predicates: self.param_env.caller_bounds.iter().filter(|predicate| {
1613 ty::Predicate::Trait(ref data) => {
1614 data.0.self_ty().is_param(index)
1618 }).cloned().collect()
1622 fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
1623 -> Option<ty::Region<'tcx>> {
1625 Some(def) => infer::EarlyBoundRegion(span, def.name),
1626 None => infer::MiscVariable(span)
1628 Some(self.next_region_var(v))
1631 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
1632 self.next_ty_var(TypeVariableOrigin::TypeInference(span))
1635 fn ty_infer_for_def(&self,
1636 ty_param_def: &ty::TypeParameterDef,
1637 substs: &[Kind<'tcx>],
1638 span: Span) -> Ty<'tcx> {
1639 self.type_var_for_def(span, ty_param_def, substs)
1642 fn projected_ty_from_poly_trait_ref(&self,
1645 poly_trait_ref: ty::PolyTraitRef<'tcx>)
1648 let (trait_ref, _) =
1649 self.replace_late_bound_regions_with_fresh_var(
1651 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_def_id),
1654 self.tcx().mk_projection(item_def_id, trait_ref.substs)
1657 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1658 if ty.has_escaping_regions() {
1659 ty // FIXME: normalization and escaping regions
1661 self.normalize_associated_types_in(span, &ty)
1665 fn set_tainted_by_errors(&self) {
1666 self.infcx.set_tainted_by_errors()
1670 /// Controls whether the arguments are tupled. This is used for the call
1673 /// Tupling means that all call-side arguments are packed into a tuple and
1674 /// passed as a single parameter. For example, if tupling is enabled, this
1677 /// fn f(x: (isize, isize))
1679 /// Can be called as:
1686 #[derive(Clone, Eq, PartialEq)]
1687 enum TupleArgumentsFlag {
1692 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1693 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1694 param_env: ty::ParamEnv<'tcx>,
1695 body_id: ast::NodeId)
1696 -> FnCtxt<'a, 'gcx, 'tcx> {
1700 err_count_on_creation: inh.tcx.sess.err_count(),
1703 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
1704 ast::CRATE_NODE_ID)),
1705 diverges: Cell::new(Diverges::Maybe),
1706 has_errors: Cell::new(false),
1707 enclosing_breakables: RefCell::new(EnclosingBreakables {
1715 pub fn sess(&self) -> &Session {
1719 pub fn err_count_since_creation(&self) -> usize {
1720 self.tcx.sess.err_count() - self.err_count_on_creation
1723 /// Produce warning on the given node, if the current point in the
1724 /// function is unreachable, and there hasn't been another warning.
1725 fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
1726 if self.diverges.get() == Diverges::Always {
1727 self.diverges.set(Diverges::WarnedAlways);
1729 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
1731 self.tcx().lint_node(
1732 lint::builtin::UNREACHABLE_CODE,
1734 &format!("unreachable {}", kind));
1740 code: ObligationCauseCode<'tcx>)
1741 -> ObligationCause<'tcx> {
1742 ObligationCause::new(span, self.body_id, code)
1745 pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
1746 self.cause(span, ObligationCauseCode::MiscObligation)
1749 /// Resolves type variables in `ty` if possible. Unlike the infcx
1750 /// version (resolve_type_vars_if_possible), this version will
1751 /// also select obligations if it seems useful, in an effort
1752 /// to get more type information.
1753 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1754 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1756 // No TyInfer()? Nothing needs doing.
1757 if !ty.has_infer_types() {
1758 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1762 // If `ty` is a type variable, see whether we already know what it is.
1763 ty = self.resolve_type_vars_if_possible(&ty);
1764 if !ty.has_infer_types() {
1765 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1769 // If not, try resolving pending obligations as much as
1770 // possible. This can help substantially when there are
1771 // indirect dependencies that don't seem worth tracking
1773 self.select_obligations_where_possible();
1774 ty = self.resolve_type_vars_if_possible(&ty);
1776 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1780 fn record_deferred_call_resolution(&self,
1781 closure_def_id: DefId,
1782 r: DeferredCallResolution<'gcx, 'tcx>) {
1783 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1784 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1787 fn remove_deferred_call_resolutions(&self,
1788 closure_def_id: DefId)
1789 -> Vec<DeferredCallResolution<'gcx, 'tcx>>
1791 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1792 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![])
1795 pub fn tag(&self) -> String {
1796 let self_ptr: *const FnCtxt = self;
1797 format!("{:?}", self_ptr)
1800 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1801 match self.locals.borrow().get(&nid) {
1804 span_bug!(span, "no type for local variable {}",
1805 self.tcx.hir.node_to_string(nid));
1811 pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) {
1812 debug!("write_ty({:?}, {:?}) in fcx {}",
1813 id, self.resolve_type_vars_if_possible(&ty), self.tag());
1814 self.tables.borrow_mut().node_types_mut().insert(id, ty);
1816 if ty.references_error() {
1817 self.has_errors.set(true);
1818 self.set_tainted_by_errors();
1822 // The NodeId and the ItemLocalId must identify the same item. We just pass
1823 // both of them for consistency checking.
1824 pub fn write_method_call(&self,
1826 method: MethodCallee<'tcx>) {
1829 .type_dependent_defs_mut()
1830 .insert(hir_id, Def::Method(method.def_id));
1831 self.write_substs(hir_id, method.substs);
1834 pub fn write_substs(&self, node_id: hir::HirId, substs: &'tcx Substs<'tcx>) {
1835 if !substs.is_noop() {
1836 debug!("write_substs({:?}, {:?}) in fcx {}",
1841 self.tables.borrow_mut().node_substs_mut().insert(node_id, substs);
1845 pub fn apply_adjustments(&self, expr: &hir::Expr, adj: Vec<Adjustment<'tcx>>) {
1846 debug!("apply_adjustments(expr={:?}, adj={:?})", expr, adj);
1852 match self.tables.borrow_mut().adjustments_mut().entry(expr.hir_id) {
1853 Entry::Vacant(entry) => { entry.insert(adj); },
1854 Entry::Occupied(mut entry) => {
1855 debug!(" - composing on top of {:?}", entry.get());
1856 match (&entry.get()[..], &adj[..]) {
1857 // Applying any adjustment on top of a NeverToAny
1858 // is a valid NeverToAny adjustment, because it can't
1860 (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return,
1862 Adjustment { kind: Adjust::Deref(_), .. },
1863 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
1865 Adjustment { kind: Adjust::Deref(_), .. },
1866 .. // Any following adjustments are allowed.
1868 // A reborrow has no effect before a dereference.
1870 // FIXME: currently we never try to compose autoderefs
1871 // and ReifyFnPointer/UnsafeFnPointer, but we could.
1873 bug!("while adjusting {:?}, can't compose {:?} and {:?}",
1874 expr, entry.get(), adj)
1876 *entry.get_mut() = adj;
1881 /// Basically whenever we are converting from a type scheme into
1882 /// the fn body space, we always want to normalize associated
1883 /// types as well. This function combines the two.
1884 fn instantiate_type_scheme<T>(&self,
1886 substs: &Substs<'tcx>,
1889 where T : TypeFoldable<'tcx>
1891 let value = value.subst(self.tcx, substs);
1892 let result = self.normalize_associated_types_in(span, &value);
1893 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1900 /// As `instantiate_type_scheme`, but for the bounds found in a
1901 /// generic type scheme.
1902 fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
1903 -> ty::InstantiatedPredicates<'tcx> {
1904 let bounds = self.tcx.predicates_of(def_id);
1905 let result = bounds.instantiate(self.tcx, substs);
1906 let result = self.normalize_associated_types_in(span, &result);
1907 debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
1914 /// Replace all anonymized types with fresh inference variables
1915 /// and record them for writeback.
1916 fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
1917 value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
1918 if let ty::TyAnon(def_id, substs) = ty.sty {
1919 // Use the same type variable if the exact same TyAnon appears more
1920 // than once in the return type (e.g. if it's passed to a type alias).
1921 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1922 if let Some(ty_var) = self.anon_types.borrow().get(&id) {
1925 let span = self.tcx.def_span(def_id);
1926 let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
1927 self.anon_types.borrow_mut().insert(id, ty_var);
1929 let predicates_of = self.tcx.predicates_of(def_id);
1930 let bounds = predicates_of.instantiate(self.tcx, substs);
1932 for predicate in bounds.predicates {
1933 // Change the predicate to refer to the type variable,
1934 // which will be the concrete type, instead of the TyAnon.
1935 // This also instantiates nested `impl Trait`.
1936 let predicate = self.instantiate_anon_types(&predicate);
1938 // Require that the predicate holds for the concrete type.
1939 let cause = traits::ObligationCause::new(span, self.body_id,
1940 traits::SizedReturnType);
1941 self.register_predicate(traits::Obligation::new(cause,
1953 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1954 where T : TypeFoldable<'tcx>
1956 self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value)
1959 fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T)
1961 where T : TypeFoldable<'tcx>
1963 self.inh.normalize_associated_types_in_as_infer_ok(span,
1969 pub fn require_type_meets(&self,
1972 code: traits::ObligationCauseCode<'tcx>,
1975 self.register_bound(
1978 traits::ObligationCause::new(span, self.body_id, code));
1981 pub fn require_type_is_sized(&self,
1984 code: traits::ObligationCauseCode<'tcx>)
1986 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1987 self.require_type_meets(ty, span, code, lang_item);
1990 pub fn register_bound(&self,
1993 cause: traits::ObligationCause<'tcx>)
1995 self.fulfillment_cx.borrow_mut()
1996 .register_bound(self, self.param_env, ty, def_id, cause);
1999 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
2000 let t = AstConv::ast_ty_to_ty(self, ast_t);
2001 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
2005 pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> {
2006 match self.tables.borrow().node_types().get(id) {
2008 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
2010 let node_id = self.tcx.hir.definitions().find_node_for_hir_id(id);
2011 bug!("no type for node {}: {} in fcx {}",
2012 node_id, self.tcx.hir.node_to_string(node_id),
2018 /// Registers an obligation for checking later, during regionck, that the type `ty` must
2019 /// outlive the region `r`.
2020 pub fn register_wf_obligation(&self,
2023 code: traits::ObligationCauseCode<'tcx>)
2025 // WF obligations never themselves fail, so no real need to give a detailed cause:
2026 let cause = traits::ObligationCause::new(span, self.body_id, code);
2027 self.register_predicate(traits::Obligation::new(cause,
2029 ty::Predicate::WellFormed(ty)));
2032 /// Registers obligations that all types appearing in `substs` are well-formed.
2033 pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
2035 for ty in substs.types() {
2036 self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
2040 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
2041 /// type/region parameter was instantiated (`substs`), creates and registers suitable
2042 /// trait/region obligations.
2044 /// For example, if there is a function:
2047 /// fn foo<'a,T:'a>(...)
2050 /// and a reference:
2056 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
2057 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
2058 pub fn add_obligations_for_parameters(&self,
2059 cause: traits::ObligationCause<'tcx>,
2060 predicates: &ty::InstantiatedPredicates<'tcx>)
2062 assert!(!predicates.has_escaping_regions());
2064 debug!("add_obligations_for_parameters(predicates={:?})",
2067 for obligation in traits::predicates_for_generics(cause, self.param_env, predicates) {
2068 self.register_predicate(obligation);
2072 // FIXME(arielb1): use this instead of field.ty everywhere
2073 // Only for fields! Returns <none> for methods>
2074 // Indifferent to privacy flags
2075 pub fn field_ty(&self,
2077 field: &'tcx ty::FieldDef,
2078 substs: &Substs<'tcx>)
2081 self.normalize_associated_types_in(span,
2082 &field.ty(self.tcx, substs))
2085 fn check_casts(&self) {
2086 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
2087 for cast in deferred_cast_checks.drain(..) {
2092 fn resolve_generator_interiors(&self, def_id: DefId) {
2093 let mut deferred_generator_interiors = self.deferred_generator_interiors.borrow_mut();
2094 for (body_id, witness) in deferred_generator_interiors.drain(..) {
2095 generator_interior::resolve_interior(self, def_id, body_id, witness);
2099 /// Apply "fallbacks" to some types
2100 /// unconstrained types get replaced with ! or () (depending on whether
2101 /// feature(never_type) is enabled), unconstrained ints with i32, and
2102 /// unconstrained floats with f64.
2103 fn default_type_parameters(&self) {
2104 use rustc::ty::error::UnconstrainedNumeric::Neither;
2105 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
2107 // Defaulting inference variables becomes very dubious if we have
2108 // encountered type-checking errors. Therefore, if we think we saw
2109 // some errors in this function, just resolve all uninstanted type
2110 // varibles to TyError.
2111 if self.is_tainted_by_errors() {
2112 for ty in &self.unsolved_variables() {
2113 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
2114 debug!("default_type_parameters: defaulting `{:?}` to error", ty);
2115 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
2121 for ty in &self.unsolved_variables() {
2122 let resolved = self.resolve_type_vars_if_possible(ty);
2123 if self.type_var_diverges(resolved) {
2124 debug!("default_type_parameters: defaulting `{:?}` to `!` because it diverges",
2126 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
2127 self.tcx.mk_diverging_default());
2129 match self.type_is_unconstrained_numeric(resolved) {
2130 UnconstrainedInt => {
2131 debug!("default_type_parameters: defaulting `{:?}` to `i32`",
2133 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
2135 UnconstrainedFloat => {
2136 debug!("default_type_parameters: defaulting `{:?}` to `f32`",
2138 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
2146 // Implements type inference fallback algorithm
2147 fn select_all_obligations_and_apply_defaults(&self) {
2148 self.select_obligations_where_possible();
2149 self.default_type_parameters();
2150 self.select_obligations_where_possible();
2153 fn select_all_obligations_or_error(&self) {
2154 debug!("select_all_obligations_or_error");
2156 // upvar inference should have ensured that all deferred call
2157 // resolutions are handled by now.
2158 assert!(self.deferred_call_resolutions.borrow().is_empty());
2160 self.select_all_obligations_and_apply_defaults();
2162 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2164 match fulfillment_cx.select_all_or_error(self) {
2166 Err(errors) => { self.report_fulfillment_errors(&errors, self.inh.body_id); }
2170 /// Select as many obligations as we can at present.
2171 fn select_obligations_where_possible(&self) {
2172 match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
2174 Err(errors) => { self.report_fulfillment_errors(&errors, self.inh.body_id); }
2178 /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2179 /// returns a type of `&T`, but the actual type we assign to the
2180 /// *expression* is `T`. So this function just peels off the return
2181 /// type by one layer to yield `T`.
2182 fn make_overloaded_lvalue_return_type(&self,
2183 method: MethodCallee<'tcx>)
2184 -> ty::TypeAndMut<'tcx>
2186 // extract method return type, which will be &T;
2187 let ret_ty = method.sig.output();
2189 // method returns &T, but the type as visible to user is T, so deref
2190 ret_ty.builtin_deref(true, NoPreference).unwrap()
2193 fn lookup_indexing(&self,
2195 base_expr: &'gcx hir::Expr,
2198 lvalue_pref: LvaluePreference)
2199 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2201 // FIXME(#18741) -- this is almost but not quite the same as the
2202 // autoderef that normal method probing does. They could likely be
2205 let mut autoderef = self.autoderef(base_expr.span, base_ty);
2206 let mut result = None;
2207 while result.is_none() && autoderef.next().is_some() {
2208 result = self.try_index_step(expr, base_expr, &autoderef, lvalue_pref, idx_ty);
2210 autoderef.finalize();
2214 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2215 /// (and otherwise adjust) `base_expr`, looking for a type which either
2216 /// supports builtin indexing or overloaded indexing.
2217 /// This loop implements one step in that search; the autoderef loop
2218 /// is implemented by `lookup_indexing`.
2219 fn try_index_step(&self,
2221 base_expr: &hir::Expr,
2222 autoderef: &Autoderef<'a, 'gcx, 'tcx>,
2223 lvalue_pref: LvaluePreference,
2225 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2227 let adjusted_ty = autoderef.unambiguous_final_ty();
2228 debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
2236 // First, try built-in indexing.
2237 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2238 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2239 debug!("try_index_step: success, using built-in indexing");
2240 let adjustments = autoderef.adjust_steps(lvalue_pref);
2241 self.apply_adjustments(base_expr, adjustments);
2242 return Some((self.tcx.types.usize, ty));
2247 for &unsize in &[false, true] {
2248 let mut self_ty = adjusted_ty;
2250 // We only unsize arrays here.
2251 if let ty::TyArray(element_ty, _) = adjusted_ty.sty {
2252 self_ty = self.tcx.mk_slice(element_ty);
2258 // If some lookup succeeds, write callee into table and extract index/element
2259 // type from the method signature.
2260 // If some lookup succeeded, install method in table
2261 let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_expr.span));
2262 let method = self.try_overloaded_lvalue_op(
2263 expr.span, self_ty, &[input_ty], lvalue_pref, LvalueOp::Index);
2265 let result = method.map(|ok| {
2266 debug!("try_index_step: success, using overloaded indexing");
2267 let method = self.register_infer_ok_obligations(ok);
2269 let mut adjustments = autoderef.adjust_steps(lvalue_pref);
2270 if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
2271 adjustments.push(Adjustment {
2272 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
2273 target: self.tcx.mk_ref(region, ty::TypeAndMut {
2280 adjustments.push(Adjustment {
2281 kind: Adjust::Unsize,
2282 target: method.sig.inputs()[0]
2285 self.apply_adjustments(base_expr, adjustments);
2287 self.write_method_call(expr.hir_id, method);
2288 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2290 if result.is_some() {
2298 fn resolve_lvalue_op(&self, op: LvalueOp, is_mut: bool) -> (Option<DefId>, Symbol) {
2299 let (tr, name) = match (op, is_mut) {
2300 (LvalueOp::Deref, false) =>
2301 (self.tcx.lang_items().deref_trait(), "deref"),
2302 (LvalueOp::Deref, true) =>
2303 (self.tcx.lang_items().deref_mut_trait(), "deref_mut"),
2304 (LvalueOp::Index, false) =>
2305 (self.tcx.lang_items().index_trait(), "index"),
2306 (LvalueOp::Index, true) =>
2307 (self.tcx.lang_items().index_mut_trait(), "index_mut"),
2309 (tr, Symbol::intern(name))
2312 fn try_overloaded_lvalue_op(&self,
2315 arg_tys: &[Ty<'tcx>],
2316 lvalue_pref: LvaluePreference,
2318 -> Option<InferOk<'tcx, MethodCallee<'tcx>>>
2320 debug!("try_overloaded_lvalue_op({:?},{:?},{:?},{:?})",
2326 // Try Mut first, if preferred.
2327 let (mut_tr, mut_op) = self.resolve_lvalue_op(op, true);
2328 let method = match (lvalue_pref, mut_tr) {
2329 (PreferMutLvalue, Some(trait_did)) => {
2330 self.lookup_method_in_trait(span, mut_op, trait_did, base_ty, Some(arg_tys))
2335 // Otherwise, fall back to the immutable version.
2336 let (imm_tr, imm_op) = self.resolve_lvalue_op(op, false);
2337 let method = match (method, imm_tr) {
2338 (None, Some(trait_did)) => {
2339 self.lookup_method_in_trait(span, imm_op, trait_did, base_ty, Some(arg_tys))
2341 (method, _) => method,
2347 fn check_method_argument_types(&self,
2349 method: Result<MethodCallee<'tcx>, ()>,
2350 args_no_rcvr: &'gcx [hir::Expr],
2351 tuple_arguments: TupleArgumentsFlag,
2352 expected: Expectation<'tcx>)
2354 let has_error = match method {
2356 method.substs.references_error() || method.sig.references_error()
2361 let err_inputs = self.err_args(args_no_rcvr.len());
2363 let err_inputs = match tuple_arguments {
2364 DontTupleArguments => err_inputs,
2365 TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
2368 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2369 false, tuple_arguments, None);
2370 return self.tcx.types.err;
2373 let method = method.unwrap();
2374 // HACK(eddyb) ignore self in the definition (see above).
2375 let expected_arg_tys = self.expected_inputs_for_expected_output(
2378 method.sig.output(),
2379 &method.sig.inputs()[1..]
2381 self.check_argument_types(sp, &method.sig.inputs()[1..], &expected_arg_tys[..],
2382 args_no_rcvr, method.sig.variadic, tuple_arguments,
2383 self.tcx.hir.span_if_local(method.def_id));
2387 /// Generic function that factors out common logic from function calls,
2388 /// method calls and overloaded operators.
2389 fn check_argument_types(&self,
2391 fn_inputs: &[Ty<'tcx>],
2392 expected_arg_tys: &[Ty<'tcx>],
2393 args: &'gcx [hir::Expr],
2395 tuple_arguments: TupleArgumentsFlag,
2396 def_span: Option<Span>) {
2399 // Grab the argument types, supplying fresh type variables
2400 // if the wrong number of arguments were supplied
2401 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2407 // All the input types from the fn signature must outlive the call
2408 // so as to validate implied bounds.
2409 for &fn_input_ty in fn_inputs {
2410 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2413 let mut expected_arg_tys = expected_arg_tys;
2414 let expected_arg_count = fn_inputs.len();
2416 let sp_args = if args.len() > 0 {
2417 let (first, args) = args.split_at(1);
2418 let mut sp_tmp = first[0].span;
2420 let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
2421 if ! sp_opt.is_some() {
2424 sp_tmp = sp_opt.unwrap();
2431 fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
2432 arg_count: usize, error_code: &str, variadic: bool,
2433 def_span: Option<Span>, sugg_unit: bool) {
2434 let mut err = sess.struct_span_err_with_code(sp,
2435 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2436 if variadic {"at least "} else {""},
2438 if expected_count == 1 {""} else {"s"},
2440 if arg_count == 1 {" was"} else {"s were"}),
2443 if let Some(def_s) = def_span {
2444 err.span_label(def_s, "defined here");
2447 let sugg_span = sp.end_point();
2448 // remove closing `)` from the span
2449 let sugg_span = sugg_span.with_hi(sugg_span.lo());
2450 err.span_suggestion(
2452 "expected the unit value `()`. You can create one with a pair of parenthesis",
2453 String::from("()"));
2455 err.span_label(sp, format!("expected {}{} parameter{}",
2456 if variadic {"at least "} else {""},
2458 if expected_count == 1 {""} else {"s"}));
2463 let formal_tys = if tuple_arguments == TupleArguments {
2464 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2465 match tuple_type.sty {
2466 ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
2467 parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
2468 "E0057", false, def_span, false);
2469 expected_arg_tys = &[];
2470 self.err_args(args.len())
2472 ty::TyTuple(arg_types, _) => {
2473 expected_arg_tys = match expected_arg_tys.get(0) {
2474 Some(&ty) => match ty.sty {
2475 ty::TyTuple(ref tys, _) => &tys,
2483 span_err!(tcx.sess, sp, E0059,
2484 "cannot use call notation; the first type parameter \
2485 for the function trait is neither a tuple nor unit");
2486 expected_arg_tys = &[];
2487 self.err_args(args.len())
2490 } else if expected_arg_count == supplied_arg_count {
2492 } else if variadic {
2493 if supplied_arg_count >= expected_arg_count {
2496 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2497 supplied_arg_count, "E0060", true, def_span, false);
2498 expected_arg_tys = &[];
2499 self.err_args(supplied_arg_count)
2502 // is the missing argument of type `()`?
2503 let sugg_unit = if expected_arg_tys.len() == 1 && supplied_arg_count == 0 {
2504 self.resolve_type_vars_if_possible(&expected_arg_tys[0]).is_nil()
2505 } else if fn_inputs.len() == 1 && supplied_arg_count == 0 {
2506 self.resolve_type_vars_if_possible(&fn_inputs[0]).is_nil()
2510 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2511 supplied_arg_count, "E0061", false, def_span, sugg_unit);
2512 expected_arg_tys = &[];
2513 self.err_args(supplied_arg_count)
2516 debug!("check_argument_types: formal_tys={:?}",
2517 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2519 // Check the arguments.
2520 // We do this in a pretty awful way: first we typecheck any arguments
2521 // that are not closures, then we typecheck the closures. This is so
2522 // that we have more information about the types of arguments when we
2523 // typecheck the functions. This isn't really the right way to do this.
2524 for &check_closures in &[false, true] {
2525 debug!("check_closures={}", check_closures);
2527 // More awful hacks: before we check argument types, try to do
2528 // an "opportunistic" vtable resolution of any trait bounds on
2529 // the call. This helps coercions.
2531 self.select_obligations_where_possible();
2534 // For variadic functions, we don't have a declared type for all of
2535 // the arguments hence we only do our usual type checking with
2536 // the arguments who's types we do know.
2537 let t = if variadic {
2539 } else if tuple_arguments == TupleArguments {
2544 for (i, arg) in args.iter().take(t).enumerate() {
2545 // Warn only for the first loop (the "no closures" one).
2546 // Closure arguments themselves can't be diverging, but
2547 // a previous argument can, e.g. `foo(panic!(), || {})`.
2548 if !check_closures {
2549 self.warn_if_unreachable(arg.id, arg.span, "expression");
2552 let is_closure = match arg.node {
2553 hir::ExprClosure(..) => true,
2557 if is_closure != check_closures {
2561 debug!("checking the argument");
2562 let formal_ty = formal_tys[i];
2564 // The special-cased logic below has three functions:
2565 // 1. Provide as good of an expected type as possible.
2566 let expected = expected_arg_tys.get(i).map(|&ty| {
2567 Expectation::rvalue_hint(self, ty)
2570 let checked_ty = self.check_expr_with_expectation(
2572 expected.unwrap_or(ExpectHasType(formal_ty)));
2574 // 2. Coerce to the most detailed type that could be coerced
2575 // to, which is `expected_ty` if `rvalue_hint` returns an
2576 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2577 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2578 self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
2580 // 3. Relate the expected type and the formal one,
2581 // if the expected type was used for the coercion.
2582 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2586 // We also need to make sure we at least write the ty of the other
2587 // arguments which we skipped above.
2589 fn variadic_error<'tcx>(s: &Session, span: Span, t: Ty<'tcx>, cast_ty: &str) {
2590 type_error_struct!(s, span, t, E0617,
2591 "can't pass `{}` to variadic function, cast to `{}`",
2595 for arg in args.iter().skip(expected_arg_count) {
2596 let arg_ty = self.check_expr(&arg);
2598 // There are a few types which get autopromoted when passed via varargs
2599 // in C but we just error out instead and require explicit casts.
2600 let arg_ty = self.structurally_resolved_type(arg.span, arg_ty);
2602 ty::TyFloat(ast::FloatTy::F32) => {
2603 variadic_error(tcx.sess, arg.span, arg_ty, "c_double");
2605 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2606 variadic_error(tcx.sess, arg.span, arg_ty, "c_int");
2608 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2609 variadic_error(tcx.sess, arg.span, arg_ty, "c_uint");
2611 ty::TyFnDef(..) => {
2612 let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx));
2613 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2614 variadic_error(tcx.sess, arg.span, arg_ty, &format!("{}", ptr_ty));
2622 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2623 (0..len).map(|_| self.tcx.types.err).collect()
2626 // AST fragment checking
2629 expected: Expectation<'tcx>)
2635 ast::LitKind::Str(..) => tcx.mk_static_str(),
2636 ast::LitKind::ByteStr(ref v) => {
2637 tcx.mk_imm_ref(tcx.types.re_static,
2638 tcx.mk_array(tcx.types.u8, v.len() as u64))
2640 ast::LitKind::Byte(_) => tcx.types.u8,
2641 ast::LitKind::Char(_) => tcx.types.char,
2642 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2643 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2644 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2645 let opt_ty = expected.to_option(self).and_then(|ty| {
2647 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2648 ty::TyChar => Some(tcx.types.u8),
2649 ty::TyRawPtr(..) => Some(tcx.types.usize),
2650 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2654 opt_ty.unwrap_or_else(
2655 || tcx.mk_int_var(self.next_int_var_id()))
2657 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2658 ast::LitKind::FloatUnsuffixed(_) => {
2659 let opt_ty = expected.to_option(self).and_then(|ty| {
2661 ty::TyFloat(_) => Some(ty),
2665 opt_ty.unwrap_or_else(
2666 || tcx.mk_float_var(self.next_float_var_id()))
2668 ast::LitKind::Bool(_) => tcx.types.bool
2672 fn check_expr_eq_type(&self,
2673 expr: &'gcx hir::Expr,
2674 expected: Ty<'tcx>) {
2675 let ty = self.check_expr_with_hint(expr, expected);
2676 self.demand_eqtype(expr.span, expected, ty);
2679 pub fn check_expr_has_type_or_error(&self,
2680 expr: &'gcx hir::Expr,
2681 expected: Ty<'tcx>) -> Ty<'tcx> {
2682 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected))
2685 fn check_expr_meets_expectation_or_error(&self,
2686 expr: &'gcx hir::Expr,
2687 expected: Expectation<'tcx>) -> Ty<'tcx> {
2688 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
2689 let mut ty = self.check_expr_with_expectation(expr, expected);
2691 // While we don't allow *arbitrary* coercions here, we *do* allow
2692 // coercions from ! to `expected`.
2694 assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
2695 "expression with never type wound up being adjusted");
2696 let adj_ty = self.next_diverging_ty_var(
2697 TypeVariableOrigin::AdjustmentType(expr.span));
2698 self.apply_adjustments(expr, vec![Adjustment {
2699 kind: Adjust::NeverToAny,
2705 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
2706 // Add help to type error if this is an `if` condition with an assignment
2707 match (expected, &expr.node) {
2708 (ExpectIfCondition, &hir::ExprAssign(ref lhs, ref rhs)) => {
2709 let msg = "try comparing for equality";
2710 if let (Ok(left), Ok(right)) = (
2711 self.tcx.sess.codemap().span_to_snippet(lhs.span),
2712 self.tcx.sess.codemap().span_to_snippet(rhs.span))
2714 err.span_suggestion(expr.span, msg, format!("{} == {}", left, right));
2726 fn check_expr_coercable_to_type(&self,
2727 expr: &'gcx hir::Expr,
2728 expected: Ty<'tcx>) -> Ty<'tcx> {
2729 let ty = self.check_expr_with_hint(expr, expected);
2730 self.demand_coerce(expr, ty, expected);
2734 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2735 expected: Ty<'tcx>) -> Ty<'tcx> {
2736 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2739 fn check_expr_with_expectation(&self,
2740 expr: &'gcx hir::Expr,
2741 expected: Expectation<'tcx>) -> Ty<'tcx> {
2742 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2745 fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
2746 self.check_expr_with_expectation(expr, NoExpectation)
2749 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2750 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2751 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2754 // determine the `self` type, using fresh variables for all variables
2755 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2756 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2758 pub fn impl_self_ty(&self,
2759 span: Span, // (potential) receiver for this impl
2761 -> TypeAndSubsts<'tcx> {
2762 let ity = self.tcx.type_of(did);
2763 debug!("impl_self_ty: ity={:?}", ity);
2765 let substs = self.fresh_substs_for_item(span, did);
2766 let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
2768 TypeAndSubsts { substs: substs, ty: substd_ty }
2771 /// Unifies the output type with the expected type early, for more coercions
2772 /// and forward type information on the input expressions.
2773 fn expected_inputs_for_expected_output(&self,
2775 expected_ret: Expectation<'tcx>,
2776 formal_ret: Ty<'tcx>,
2777 formal_args: &[Ty<'tcx>])
2779 let formal_ret = self.resolve_type_vars_with_obligations(formal_ret);
2780 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2781 self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
2782 // Attempt to apply a subtyping relationship between the formal
2783 // return type (likely containing type variables if the function
2784 // is polymorphic) and the expected return type.
2785 // No argument expectations are produced if unification fails.
2786 let origin = self.misc(call_span);
2787 let ures = self.at(&origin, self.param_env).sup(ret_ty, formal_ret);
2789 // FIXME(#15760) can't use try! here, FromError doesn't default
2790 // to identity so the resulting type is not constrained.
2793 // Process any obligations locally as much as
2794 // we can. We don't care if some things turn
2795 // out unconstrained or ambiguous, as we're
2796 // just trying to get hints here.
2797 let result = self.save_and_restore_in_snapshot_flag(|_| {
2798 let mut fulfill = FulfillmentContext::new();
2799 let ok = ok; // FIXME(#30046)
2800 for obligation in ok.obligations {
2801 fulfill.register_predicate_obligation(self, obligation);
2803 fulfill.select_where_possible(self)
2808 Err(_) => return Err(()),
2811 Err(_) => return Err(()),
2814 // Record all the argument types, with the substitutions
2815 // produced from the above subtyping unification.
2816 Ok(formal_args.iter().map(|ty| {
2817 self.resolve_type_vars_if_possible(ty)
2820 }).unwrap_or(vec![]);
2821 debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
2822 formal_args, formal_ret,
2823 expected_args, expected_ret);
2827 // Checks a method call.
2828 fn check_method_call(&self,
2829 expr: &'gcx hir::Expr,
2830 segment: &hir::PathSegment,
2832 args: &'gcx [hir::Expr],
2833 expected: Expectation<'tcx>,
2834 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2835 let rcvr = &args[0];
2836 let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2837 // no need to check for bot/err -- callee does that
2838 let rcvr_t = self.structurally_resolved_type(expr.span, rcvr_t);
2840 let method = match self.lookup_method(rcvr_t,
2846 self.write_method_call(expr.hir_id, method);
2850 if segment.name != keywords::Invalid.name() {
2851 self.report_method_error(span,
2862 // Call the generic checker.
2863 self.check_method_argument_types(span, method,
2869 fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
2873 .unwrap_or_else(|| span_bug!(return_expr.span,
2874 "check_return_expr called outside fn body"));
2876 let ret_ty = ret_coercion.borrow().expected_ty();
2877 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
2878 ret_coercion.borrow_mut()
2880 &self.cause(return_expr.span,
2881 ObligationCauseCode::ReturnType(return_expr.id)),
2884 self.diverges.get());
2888 // A generic function for checking the then and else in an if
2890 fn check_then_else(&self,
2891 cond_expr: &'gcx hir::Expr,
2892 then_expr: &'gcx hir::Expr,
2893 opt_else_expr: Option<&'gcx hir::Expr>,
2895 expected: Expectation<'tcx>) -> Ty<'tcx> {
2896 let cond_ty = self.check_expr_meets_expectation_or_error(cond_expr, ExpectIfCondition);
2897 let cond_diverges = self.diverges.get();
2898 self.diverges.set(Diverges::Maybe);
2900 let expected = expected.adjust_for_branches(self);
2901 let then_ty = self.check_expr_with_expectation(then_expr, expected);
2902 let then_diverges = self.diverges.get();
2903 self.diverges.set(Diverges::Maybe);
2905 // We've already taken the expected type's preferences
2906 // into account when typing the `then` branch. To figure
2907 // out the initial shot at a LUB, we thus only consider
2908 // `expected` if it represents a *hard* constraint
2909 // (`only_has_type`); otherwise, we just go with a
2910 // fresh type variable.
2911 let coerce_to_ty = expected.coercion_target_type(self, sp);
2912 let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty);
2914 let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
2915 coerce.coerce(self, &if_cause, then_expr, then_ty, then_diverges);
2917 if let Some(else_expr) = opt_else_expr {
2918 let else_ty = self.check_expr_with_expectation(else_expr, expected);
2919 let else_diverges = self.diverges.get();
2921 coerce.coerce(self, &if_cause, else_expr, else_ty, else_diverges);
2923 // We won't diverge unless both branches do (or the condition does).
2924 self.diverges.set(cond_diverges | then_diverges & else_diverges);
2926 let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
2927 coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true);
2929 // If the condition is false we can't diverge.
2930 self.diverges.set(cond_diverges);
2933 let result_ty = coerce.complete(self);
2934 if cond_ty.references_error() {
2941 // Check field access expressions
2942 fn check_field(&self,
2943 expr: &'gcx hir::Expr,
2944 lvalue_pref: LvaluePreference,
2945 base: &'gcx hir::Expr,
2946 field: &Spanned<ast::Name>) -> Ty<'tcx> {
2947 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2948 let expr_t = self.structurally_resolved_type(expr.span,
2950 let mut private_candidate = None;
2951 let mut autoderef = self.autoderef(expr.span, expr_t);
2952 while let Some((base_t, _)) = autoderef.next() {
2954 ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
2955 debug!("struct named {:?}", base_t);
2956 let (ident, def_scope) =
2957 self.tcx.adjust(field.node, base_def.did, self.body_id);
2958 let fields = &base_def.struct_variant().fields;
2959 if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
2960 let field_ty = self.field_ty(expr.span, field, substs);
2961 if field.vis.is_accessible_from(def_scope, self.tcx) {
2962 let adjustments = autoderef.adjust_steps(lvalue_pref);
2963 self.apply_adjustments(base, adjustments);
2964 autoderef.finalize();
2966 self.tcx.check_stability(field.did, expr.id, expr.span);
2970 private_candidate = Some((base_def.did, field_ty));
2976 autoderef.unambiguous_final_ty();
2978 if let Some((did, field_ty)) = private_candidate {
2979 let struct_path = self.tcx().item_path_str(did);
2980 let mut err = struct_span_err!(self.tcx().sess, expr.span, E0616,
2981 "field `{}` of struct `{}` is private",
2982 field.node, struct_path);
2983 // Also check if an accessible method exists, which is often what is meant.
2984 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2985 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2990 } else if field.node == keywords::Invalid.name() {
2991 self.tcx().types.err
2992 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2993 type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
2994 "attempted to take value of method `{}` on type `{}`",
2996 .help("maybe a `()` to call it is missing?")
2998 self.tcx().types.err
3000 if !expr_t.is_primitive_ty() {
3001 let mut err = self.no_such_field_err(field.span, &field.node, expr_t);
3004 ty::TyAdt(def, _) if !def.is_enum() => {
3005 if let Some(suggested_field_name) =
3006 Self::suggest_field_name(def.struct_variant(), field, vec![]) {
3007 err.span_label(field.span,
3008 format!("did you mean `{}`?", suggested_field_name));
3010 err.span_label(field.span, "unknown field");
3011 let struct_variant_def = def.struct_variant();
3012 let field_names = self.available_field_names(struct_variant_def);
3013 if !field_names.is_empty() {
3014 err.note(&format!("available fields are: {}",
3015 self.name_series_display(field_names)));
3019 ty::TyRawPtr(..) => {
3020 err.note(&format!("`{0}` is a native pointer; perhaps you need to deref \
3022 self.tcx.hir.node_to_pretty_string(base.id),
3029 type_error_struct!(self.tcx().sess, field.span, expr_t, E0610,
3030 "`{}` is a primitive type and therefore doesn't have fields",
3033 self.tcx().types.err
3037 // Return an hint about the closest match in field names
3038 fn suggest_field_name(variant: &'tcx ty::VariantDef,
3039 field: &Spanned<ast::Name>,
3040 skip: Vec<InternedString>)
3042 let name = field.node.as_str();
3043 let names = variant.fields.iter().filter_map(|field| {
3044 // ignore already set fields and private fields from non-local crates
3045 if skip.iter().any(|x| *x == field.name.as_str()) ||
3046 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
3053 find_best_match_for_name(names, &name, None)
3056 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
3057 let mut available = Vec::new();
3058 for field in variant.fields.iter() {
3059 let (_, def_scope) = self.tcx.adjust(field.name, variant.did, self.body_id);
3060 if field.vis.is_accessible_from(def_scope, self.tcx) {
3061 available.push(field.name);
3067 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
3068 // dynamic limit, to never omit just one field
3069 let limit = if names.len() == 6 { 6 } else { 5 };
3070 let mut display = names.iter().take(limit)
3071 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
3072 if names.len() > limit {
3073 display = format!("{} ... and {} others", display, names.len() - limit);
3078 // Check tuple index expressions
3079 fn check_tup_field(&self,
3080 expr: &'gcx hir::Expr,
3081 lvalue_pref: LvaluePreference,
3082 base: &'gcx hir::Expr,
3083 idx: codemap::Spanned<usize>) -> Ty<'tcx> {
3084 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
3085 let expr_t = self.structurally_resolved_type(expr.span,
3087 let mut private_candidate = None;
3088 let mut tuple_like = false;
3089 let mut autoderef = self.autoderef(expr.span, expr_t);
3090 while let Some((base_t, _)) = autoderef.next() {
3091 let field = match base_t.sty {
3092 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
3093 tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
3094 if !tuple_like { continue }
3096 debug!("tuple struct named {:?}", base_t);
3097 let ident = ast::Ident {
3098 name: Symbol::intern(&idx.node.to_string()),
3099 ctxt: idx.span.ctxt().modern(),
3101 let (ident, def_scope) =
3102 self.tcx.adjust_ident(ident, base_def.did, self.body_id);
3103 let fields = &base_def.struct_variant().fields;
3104 if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
3105 let field_ty = self.field_ty(expr.span, field, substs);
3106 if field.vis.is_accessible_from(def_scope, self.tcx) {
3107 self.tcx.check_stability(field.did, expr.id, expr.span);
3110 private_candidate = Some((base_def.did, field_ty));
3117 ty::TyTuple(ref v, _) => {
3119 v.get(idx.node).cloned()
3124 if let Some(field_ty) = field {
3125 let adjustments = autoderef.adjust_steps(lvalue_pref);
3126 self.apply_adjustments(base, adjustments);
3127 autoderef.finalize();
3131 autoderef.unambiguous_final_ty();
3133 if let Some((did, field_ty)) = private_candidate {
3134 let struct_path = self.tcx().item_path_str(did);
3135 struct_span_err!(self.tcx().sess, expr.span, E0611,
3136 "field `{}` of tuple-struct `{}` is private",
3137 idx.node, struct_path).emit();
3142 type_error_struct!(self.tcx().sess, expr.span, expr_t, E0612,
3143 "attempted out-of-bounds tuple index `{}` on type `{}`",
3144 idx.node, expr_t).emit();
3146 self.no_such_field_err(expr.span, idx.node, expr_t).emit();
3149 self.tcx().types.err
3152 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS)
3153 -> DiagnosticBuilder {
3154 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
3155 "no field `{}` on type `{}`",
3159 fn report_unknown_field(&self,
3161 variant: &'tcx ty::VariantDef,
3163 skip_fields: &[hir::Field],
3165 let mut err = self.type_error_struct_with_diag(
3167 |actual| match ty.sty {
3168 ty::TyAdt(adt, ..) if adt.is_enum() => {
3169 struct_span_err!(self.tcx.sess, field.name.span, E0559,
3170 "{} `{}::{}` has no field named `{}`",
3171 kind_name, actual, variant.name, field.name.node)
3174 struct_span_err!(self.tcx.sess, field.name.span, E0560,
3175 "{} `{}` has no field named `{}`",
3176 kind_name, actual, field.name.node)
3180 // prevent all specified fields from being suggested
3181 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3182 if let Some(field_name) = Self::suggest_field_name(variant,
3184 skip_fields.collect()) {
3185 err.span_label(field.name.span,
3186 format!("field does not exist - did you mean `{}`?", field_name));
3189 ty::TyAdt(adt, ..) => {
3191 err.span_label(field.name.span,
3192 format!("`{}::{}` does not have this field",
3195 err.span_label(field.name.span,
3196 format!("`{}` does not have this field", ty));
3198 let available_field_names = self.available_field_names(variant);
3199 if !available_field_names.is_empty() {
3200 err.note(&format!("available fields are: {}",
3201 self.name_series_display(available_field_names)));
3204 _ => bug!("non-ADT passed to report_unknown_field")
3210 fn check_expr_struct_fields(&self,
3212 expected: Expectation<'tcx>,
3213 expr_id: ast::NodeId,
3215 variant: &'tcx ty::VariantDef,
3216 ast_fields: &'gcx [hir::Field],
3217 check_completeness: bool) {
3221 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3222 .get(0).cloned().unwrap_or(adt_ty);
3223 // re-link the regions that EIfEO can erase.
3224 self.demand_eqtype(span, adt_ty_hint, adt_ty);
3226 let (substs, adt_kind, kind_name) = match &adt_ty.sty{
3227 &ty::TyAdt(adt, substs) => {
3228 (substs, adt.adt_kind(), adt.variant_descr())
3230 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3233 let mut remaining_fields = FxHashMap();
3234 for field in &variant.fields {
3235 remaining_fields.insert(field.name.to_ident(), field);
3238 let mut seen_fields = FxHashMap();
3240 let mut error_happened = false;
3242 // Typecheck each field.
3243 for field in ast_fields {
3244 let ident = tcx.adjust(field.name.node, variant.did, self.body_id).0;
3245 let field_type = if let Some(v_field) = remaining_fields.remove(&ident) {
3246 seen_fields.insert(field.name.node, field.span);
3248 // we don't look at stability attributes on
3249 // struct-like enums (yet...), but it's definitely not
3250 // a bug to have construct one.
3251 if adt_kind != ty::AdtKind::Enum {
3252 tcx.check_stability(v_field.did, expr_id, field.span);
3255 self.field_ty(field.span, v_field, substs)
3257 error_happened = true;
3258 if let Some(_) = variant.find_field_named(field.name.node) {
3259 let mut err = struct_span_err!(self.tcx.sess,
3262 "field `{}` specified more than once",
3265 err.span_label(field.name.span, "used more than once");
3267 if let Some(prev_span) = seen_fields.get(&field.name.node) {
3268 err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
3273 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3279 // Make sure to give a type to the field even if there's
3280 // an error, so we can continue typechecking
3281 self.check_expr_coercable_to_type(&field.expr, field_type);
3284 // Make sure the programmer specified correct number of fields.
3285 if kind_name == "union" {
3286 if ast_fields.len() != 1 {
3287 tcx.sess.span_err(span, "union expressions should have exactly one field");
3289 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3290 let len = remaining_fields.len();
3292 let mut displayable_field_names = remaining_fields
3294 .map(|ident| ident.name.as_str())
3295 .collect::<Vec<_>>();
3297 displayable_field_names.sort();
3299 let truncated_fields_error = if len <= 3 {
3302 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3305 let remaining_fields_names = displayable_field_names.iter().take(3)
3306 .map(|n| format!("`{}`", n))
3307 .collect::<Vec<_>>()
3310 struct_span_err!(tcx.sess, span, E0063,
3311 "missing field{} {}{} in initializer of `{}`",
3312 if remaining_fields.len() == 1 { "" } else { "s" },
3313 remaining_fields_names,
3314 truncated_fields_error,
3316 .span_label(span, format!("missing {}{}",
3317 remaining_fields_names,
3318 truncated_fields_error))
3323 fn check_struct_fields_on_error(&self,
3324 fields: &'gcx [hir::Field],
3325 base_expr: &'gcx Option<P<hir::Expr>>) {
3326 for field in fields {
3327 self.check_expr(&field.expr);
3331 self.check_expr(&base);
3337 pub fn check_struct_path(&self,
3339 node_id: ast::NodeId)
3340 -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
3341 let path_span = match *qpath {
3342 hir::QPath::Resolved(_, ref path) => path.span,
3343 hir::QPath::TypeRelative(ref qself, _) => qself.span
3345 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3346 let variant = match def {
3348 self.set_tainted_by_errors();
3351 Def::Variant(..) => {
3353 ty::TyAdt(adt, substs) => {
3354 Some((adt.variant_of_def(def), adt.did, substs))
3356 _ => bug!("unexpected type: {:?}", ty.sty)
3359 Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3360 Def::AssociatedTy(..) | Def::SelfTy(..) => {
3362 ty::TyAdt(adt, substs) if !adt.is_enum() => {
3363 Some((adt.struct_variant(), adt.did, substs))
3368 _ => bug!("unexpected definition: {:?}", def)
3371 if let Some((variant, did, substs)) = variant {
3372 // Check bounds on type arguments used in the path.
3373 let bounds = self.instantiate_bounds(path_span, did, substs);
3374 let cause = traits::ObligationCause::new(path_span, self.body_id,
3375 traits::ItemObligation(did));
3376 self.add_obligations_for_parameters(cause, &bounds);
3380 struct_span_err!(self.tcx.sess, path_span, E0071,
3381 "expected struct, variant or union type, found {}",
3382 ty.sort_string(self.tcx))
3383 .span_label(path_span, "not a struct")
3389 fn check_expr_struct(&self,
3391 expected: Expectation<'tcx>,
3393 fields: &'gcx [hir::Field],
3394 base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3396 // Find the relevant variant
3397 let (variant, struct_ty) =
3398 if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3401 self.check_struct_fields_on_error(fields, base_expr);
3402 return self.tcx.types.err;
3405 let path_span = match *qpath {
3406 hir::QPath::Resolved(_, ref path) => path.span,
3407 hir::QPath::TypeRelative(ref qself, _) => qself.span
3410 self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3411 base_expr.is_none());
3412 if let &Some(ref base_expr) = base_expr {
3413 self.check_expr_has_type_or_error(base_expr, struct_ty);
3414 match struct_ty.sty {
3415 ty::TyAdt(adt, substs) if adt.is_struct() => {
3416 let fru_field_types = adt.struct_variant().fields.iter().map(|f| {
3417 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
3422 .fru_field_types_mut()
3423 .insert(expr.hir_id, fru_field_types);
3426 span_err!(self.tcx.sess, base_expr.span, E0436,
3427 "functional record update syntax requires a struct");
3431 self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3437 /// If an expression has any sub-expressions that result in a type error,
3438 /// inspecting that expression's type with `ty.references_error()` will return
3439 /// true. Likewise, if an expression is known to diverge, inspecting its
3440 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3441 /// strict, _|_ can appear in the type of an expression that does not,
3442 /// itself, diverge: for example, fn() -> _|_.)
3443 /// Note that inspecting a type's structure *directly* may expose the fact
3444 /// that there are actually multiple representations for `TyError`, so avoid
3445 /// that when err needs to be handled differently.
3446 fn check_expr_with_expectation_and_lvalue_pref(&self,
3447 expr: &'gcx hir::Expr,
3448 expected: Expectation<'tcx>,
3449 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3450 debug!(">> typechecking: expr={:?} expected={:?}",
3453 // Warn for expressions after diverging siblings.
3454 self.warn_if_unreachable(expr.id, expr.span, "expression");
3456 // Hide the outer diverging and has_errors flags.
3457 let old_diverges = self.diverges.get();
3458 let old_has_errors = self.has_errors.get();
3459 self.diverges.set(Diverges::Maybe);
3460 self.has_errors.set(false);
3462 let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3464 // Warn for non-block expressions with diverging children.
3467 hir::ExprLoop(..) | hir::ExprWhile(..) |
3468 hir::ExprIf(..) | hir::ExprMatch(..) => {}
3470 _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3473 // Any expression that produces a value of type `!` must have diverged
3475 self.diverges.set(self.diverges.get() | Diverges::Always);
3478 // Record the type, which applies it effects.
3479 // We need to do this after the warning above, so that
3480 // we don't warn for the diverging expression itself.
3481 self.write_ty(expr.hir_id, ty);
3483 // Combine the diverging and has_error flags.
3484 self.diverges.set(self.diverges.get() | old_diverges);
3485 self.has_errors.set(self.has_errors.get() | old_has_errors);
3487 debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3488 debug!("... {:?}, expected is {:?}", ty, expected);
3493 fn check_expr_kind(&self,
3494 expr: &'gcx hir::Expr,
3495 expected: Expectation<'tcx>,
3496 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3500 hir::ExprBox(ref subexpr) => {
3501 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3503 ty::TyAdt(def, _) if def.is_box()
3504 => Expectation::rvalue_hint(self, ty.boxed_ty()),
3508 let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3509 tcx.mk_box(referent_ty)
3512 hir::ExprLit(ref lit) => {
3513 self.check_lit(&lit, expected)
3515 hir::ExprBinary(op, ref lhs, ref rhs) => {
3516 self.check_binop(expr, op, lhs, rhs)
3518 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3519 self.check_binop_assign(expr, op, lhs, rhs)
3521 hir::ExprUnary(unop, ref oprnd) => {
3522 let expected_inner = match unop {
3523 hir::UnNot | hir::UnNeg => {
3530 let lvalue_pref = match unop {
3531 hir::UnDeref => lvalue_pref,
3534 let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3538 if !oprnd_t.references_error() {
3539 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3542 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3544 } else if let Some(ok) = self.try_overloaded_deref(
3545 expr.span, oprnd_t, lvalue_pref) {
3546 let method = self.register_infer_ok_obligations(ok);
3547 if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
3548 self.apply_adjustments(oprnd, vec![Adjustment {
3549 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
3550 target: method.sig.inputs()[0]
3553 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3554 self.write_method_call(expr.hir_id, method);
3556 type_error_struct!(tcx.sess, expr.span, oprnd_t, E0614,
3557 "type `{}` cannot be dereferenced",
3559 oprnd_t = tcx.types.err;
3563 let result = self.check_user_unop(expr, oprnd_t, unop);
3564 // If it's builtin, we can reuse the type, this helps inference.
3565 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3570 let result = self.check_user_unop(expr, oprnd_t, unop);
3571 // If it's builtin, we can reuse the type, this helps inference.
3572 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3580 hir::ExprAddrOf(mutbl, ref oprnd) => {
3581 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3583 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3584 if self.tcx.expr_is_lval(&oprnd) {
3585 // Lvalues may legitimately have unsized types.
3586 // For example, dereferences of a fat pointer and
3587 // the last field of a struct can be unsized.
3588 ExpectHasType(mt.ty)
3590 Expectation::rvalue_hint(self, mt.ty)
3596 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3597 let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3599 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3600 if tm.ty.references_error() {
3603 // Note: at this point, we cannot say what the best lifetime
3604 // is to use for resulting pointer. We want to use the
3605 // shortest lifetime possible so as to avoid spurious borrowck
3606 // errors. Moreover, the longest lifetime will depend on the
3607 // precise details of the value whose address is being taken
3608 // (and how long it is valid), which we don't know yet until type
3609 // inference is complete.
3611 // Therefore, here we simply generate a region variable. The
3612 // region inferencer will then select the ultimate value.
3613 // Finally, borrowck is charged with guaranteeing that the
3614 // value whose address was taken can actually be made to live
3615 // as long as it needs to live.
3616 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3617 tcx.mk_ref(region, tm)
3620 hir::ExprPath(ref qpath) => {
3621 let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3622 expr.id, expr.span);
3623 let ty = if def != Def::Err {
3624 self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3626 self.set_tainted_by_errors();
3630 // We always require that the type provided as the value for
3631 // a type parameter outlives the moment of instantiation.
3632 let substs = self.tables.borrow().node_substs(expr.hir_id);
3633 self.add_wf_bounds(substs, expr);
3637 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3638 for output in outputs {
3639 self.check_expr(output);
3641 for input in inputs {
3642 self.check_expr(input);
3646 hir::ExprBreak(destination, ref expr_opt) => {
3647 if let Some(target_id) = destination.target_id.opt_id() {
3648 let (e_ty, e_diverges, cause);
3649 if let Some(ref e) = *expr_opt {
3650 // If this is a break with a value, we need to type-check
3651 // the expression. Get an expected type from the loop context.
3652 let opt_coerce_to = {
3653 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3654 enclosing_breakables.find_breakable(target_id)
3657 .map(|coerce| coerce.expected_ty())
3660 // If the loop context is not a `loop { }`, then break with
3661 // a value is illegal, and `opt_coerce_to` will be `None`.
3662 // Just set expectation to error in that case.
3663 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3665 // Recurse without `enclosing_breakables` borrowed.
3666 e_ty = self.check_expr_with_hint(e, coerce_to);
3667 e_diverges = self.diverges.get();
3668 cause = self.misc(e.span);
3670 // Otherwise, this is a break *without* a value. That's
3671 // always legal, and is equivalent to `break ()`.
3672 e_ty = tcx.mk_nil();
3673 e_diverges = Diverges::Maybe;
3674 cause = self.misc(expr.span);
3677 // Now that we have type-checked `expr_opt`, borrow
3678 // the `enclosing_loops` field and let's coerce the
3679 // type of `expr_opt` into what is expected.
3680 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3681 let ctxt = enclosing_breakables.find_breakable(target_id);
3682 if let Some(ref mut coerce) = ctxt.coerce {
3683 if let Some(ref e) = *expr_opt {
3684 coerce.coerce(self, &cause, e, e_ty, e_diverges);
3686 assert!(e_ty.is_nil());
3687 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
3690 // If `ctxt.coerce` is `None`, we can just ignore
3691 // the type of the expresison. This is because
3692 // either this was a break *without* a value, in
3693 // which case it is always a legal type (`()`), or
3694 // else an error would have been flagged by the
3695 // `loops` pass for using break with an expression
3696 // where you are not supposed to.
3697 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3700 ctxt.may_break = true;
3702 // Otherwise, we failed to find the enclosing loop;
3703 // this can only happen if the `break` was not
3704 // inside a loop at all, which is caught by the
3705 // loop-checking pass.
3706 assert!(self.tcx.sess.err_count() > 0);
3708 // We still need to assign a type to the inner expression to
3709 // prevent the ICE in #43162.
3710 if let Some(ref e) = *expr_opt {
3711 self.check_expr_with_hint(e, tcx.types.err);
3713 // ... except when we try to 'break rust;'.
3714 // ICE this expression in particular (see #43162).
3715 if let hir::ExprPath(hir::QPath::Resolved(_, ref path)) = e.node {
3716 if path.segments.len() == 1 && path.segments[0].name == "rust" {
3717 fatally_break_rust(self.tcx.sess);
3723 // the type of a `break` is always `!`, since it diverges
3726 hir::ExprAgain(_) => { tcx.types.never }
3727 hir::ExprRet(ref expr_opt) => {
3728 if self.ret_coercion.is_none() {
3729 struct_span_err!(self.tcx.sess, expr.span, E0572,
3730 "return statement outside of function body").emit();
3731 } else if let Some(ref e) = *expr_opt {
3732 self.check_return_expr(e);
3734 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3735 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3736 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
3740 hir::ExprAssign(ref lhs, ref rhs) => {
3741 let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3743 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3746 ExpectIfCondition => {
3747 self.tcx.sess.delay_span_bug(lhs.span, "invalid lhs expression in if;\
3748 expected error elsehwere");
3751 // Only check this if not in an `if` condition, as the
3752 // mistyped comparison help is more appropriate.
3753 if !self.tcx.expr_is_lval(&lhs) {
3754 struct_span_err!(self.tcx.sess, expr.span, E0070,
3755 "invalid left-hand side expression")
3756 .span_label(expr.span, "left-hand of expression not valid")
3762 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3764 if lhs_ty.references_error() || rhs_ty.references_error() {
3770 hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3771 self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3772 expr.span, expected)
3774 hir::ExprWhile(ref cond, ref body, _) => {
3775 let ctxt = BreakableCtxt {
3776 // cannot use break with a value from a while loop
3781 self.with_breakable_ctxt(expr.id, ctxt, || {
3782 self.check_expr_has_type_or_error(&cond, tcx.types.bool);
3783 let cond_diverging = self.diverges.get();
3784 self.check_block_no_value(&body);
3786 // We may never reach the body so it diverging means nothing.
3787 self.diverges.set(cond_diverging);
3792 hir::ExprLoop(ref body, _, source) => {
3793 let coerce = match source {
3794 // you can only use break with a value from a normal `loop { }`
3795 hir::LoopSource::Loop => {
3796 let coerce_to = expected.coercion_target_type(self, body.span);
3797 Some(CoerceMany::new(coerce_to))
3800 hir::LoopSource::WhileLet |
3801 hir::LoopSource::ForLoop => {
3806 let ctxt = BreakableCtxt {
3808 may_break: false, // will get updated if/when we find a `break`
3811 let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3812 self.check_block_no_value(&body);
3816 // No way to know whether it's diverging because
3817 // of a `break` or an outer `break` or `return.
3818 self.diverges.set(Diverges::Maybe);
3821 // If we permit break with a value, then result type is
3822 // the LUB of the breaks (possibly ! if none); else, it
3823 // is nil. This makes sense because infinite loops
3824 // (which would have type !) are only possible iff we
3825 // permit break with a value [1].
3826 assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3827 ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3829 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3830 self.check_match(expr, &discrim, arms, expected, match_src)
3832 hir::ExprClosure(capture, ref decl, body_id, _, _) => {
3833 self.check_expr_closure(expr, capture, &decl, body_id, expected)
3835 hir::ExprBlock(ref body) => {
3836 self.check_block_with_expected(&body, expected)
3838 hir::ExprCall(ref callee, ref args) => {
3839 self.check_call(expr, &callee, args, expected)
3841 hir::ExprMethodCall(ref segment, span, ref args) => {
3842 self.check_method_call(expr, segment, span, args, expected, lvalue_pref)
3844 hir::ExprCast(ref e, ref t) => {
3845 // Find the type of `e`. Supply hints based on the type we are casting to,
3847 let t_cast = self.to_ty(t);
3848 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3849 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3850 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3851 let diverges = self.diverges.get();
3853 // Eagerly check for some obvious errors.
3854 if t_expr.references_error() || t_cast.references_error() {
3857 // Defer other checks until we're done type checking.
3858 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3859 match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
3861 deferred_cast_checks.push(cast_check);
3864 Err(ErrorReported) => {
3870 hir::ExprType(ref e, ref t) => {
3871 let typ = self.to_ty(&t);
3872 self.check_expr_eq_type(&e, typ);
3875 hir::ExprArray(ref args) => {
3876 let uty = expected.to_option(self).and_then(|uty| {
3878 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3883 let element_ty = if !args.is_empty() {
3884 let coerce_to = uty.unwrap_or_else(
3885 || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3886 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
3887 assert_eq!(self.diverges.get(), Diverges::Maybe);
3889 let e_ty = self.check_expr_with_hint(e, coerce_to);
3890 let cause = self.misc(e.span);
3891 coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
3893 coerce.complete(self)
3895 self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3897 tcx.mk_array(element_ty, args.len() as u64)
3899 hir::ExprRepeat(ref element, count) => {
3900 let count_def_id = tcx.hir.body_owner_def_id(count);
3901 let param_env = ty::ParamEnv::empty(traits::Reveal::UserFacing);
3902 let substs = Substs::identity_for_item(tcx.global_tcx(), count_def_id);
3903 let count = tcx.const_eval(param_env.and((count_def_id, substs)));
3905 if let Err(ref err) = count {
3906 err.report(tcx, tcx.def_span(count_def_id), "constant expression");
3909 let uty = match expected {
3910 ExpectHasType(uty) => {
3912 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3919 let (element_ty, t) = match uty {
3921 self.check_expr_coercable_to_type(&element, uty);
3925 let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3926 let element_ty = self.check_expr_has_type_or_error(&element, t);
3931 if let Ok(count) = count {
3932 let zero_or_one = count.val.to_const_int().and_then(|count| {
3933 count.to_u64().map(|count| count <= 1)
3934 }).unwrap_or(false);
3936 // For [foo, ..n] where n > 1, `foo` must have
3938 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3939 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3943 if element_ty.references_error() {
3945 } else if let Ok(count) = count {
3946 tcx.mk_ty(ty::TyArray(t, count))
3951 hir::ExprTup(ref elts) => {
3952 let flds = expected.only_has_type(self).and_then(|ty| {
3953 let ty = self.resolve_type_vars_with_obligations(ty);
3955 ty::TyTuple(ref flds, _) => Some(&flds[..]),
3960 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3961 let t = match flds {
3962 Some(ref fs) if i < fs.len() => {
3964 self.check_expr_coercable_to_type(&e, ety);
3968 self.check_expr_with_expectation(&e, NoExpectation)
3973 let tuple = tcx.mk_tup(elt_ts_iter, false);
3974 if tuple.references_error() {
3977 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
3981 hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3982 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3984 hir::ExprField(ref base, ref field) => {
3985 self.check_field(expr, lvalue_pref, &base, field)
3987 hir::ExprTupField(ref base, idx) => {
3988 self.check_tup_field(expr, lvalue_pref, &base, idx)
3990 hir::ExprIndex(ref base, ref idx) => {
3991 let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3992 let idx_t = self.check_expr(&idx);
3994 if base_t.references_error() {
3996 } else if idx_t.references_error() {
3999 let base_t = self.structurally_resolved_type(expr.span, base_t);
4000 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
4001 Some((index_ty, element_ty)) => {
4002 self.demand_coerce(idx, idx_t, index_ty);
4006 let mut err = type_error_struct!(tcx.sess, expr.span, base_t, E0608,
4007 "cannot index into a value of type `{}`",
4009 // Try to give some advice about indexing tuples.
4010 if let ty::TyTuple(..) = base_t.sty {
4011 let mut needs_note = true;
4012 // If the index is an integer, we can show the actual
4013 // fixed expression:
4014 if let hir::ExprLit(ref lit) = idx.node {
4015 if let ast::LitKind::Int(i,
4016 ast::LitIntType::Unsuffixed) = lit.node {
4017 let snip = tcx.sess.codemap().span_to_snippet(base.span);
4018 if let Ok(snip) = snip {
4019 err.span_suggestion(expr.span,
4020 "to access tuple elements, use",
4021 format!("{}.{}", snip, i));
4027 err.help("to access tuple elements, use tuple indexing \
4028 syntax (e.g. `tuple.0`)");
4037 hir::ExprYield(ref value) => {
4038 match self.yield_ty {
4040 self.check_expr_coercable_to_type(&value, ty);
4043 struct_span_err!(self.tcx.sess, expr.span, E0627,
4044 "yield statement outside of generator literal").emit();
4052 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
4053 // The newly resolved definition is written into `type_dependent_defs`.
4054 fn finish_resolving_struct_path(&self,
4057 node_id: ast::NodeId)
4061 hir::QPath::Resolved(ref maybe_qself, ref path) => {
4062 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
4063 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
4066 hir::QPath::TypeRelative(ref qself, ref segment) => {
4067 let ty = self.to_ty(qself);
4069 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
4074 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
4077 // Write back the new resolution.
4078 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
4079 self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, def);
4086 // Resolve associated value path into a base type and associated constant or method definition.
4087 // The newly resolved definition is written into `type_dependent_defs`.
4088 pub fn resolve_ty_and_def_ufcs<'b>(&self,
4089 qpath: &'b hir::QPath,
4090 node_id: ast::NodeId,
4092 -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
4094 let (ty, item_segment) = match *qpath {
4095 hir::QPath::Resolved(ref opt_qself, ref path) => {
4097 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
4098 &path.segments[..]);
4100 hir::QPath::TypeRelative(ref qself, ref segment) => {
4101 (self.to_ty(qself), segment)
4104 let item_name = item_segment.name;
4105 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
4108 let def = match error {
4109 method::MethodError::PrivateMatch(def, _) => def,
4112 if item_name != keywords::Invalid.name() {
4113 self.report_method_error(span, ty, item_name, None, error, None);
4119 // Write back the new resolution.
4120 let hir_id = self.tcx.hir.node_to_hir_id(node_id);
4121 self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, def);
4122 (def, Some(ty), slice::ref_slice(&**item_segment))
4125 pub fn check_decl_initializer(&self,
4126 local: &'gcx hir::Local,
4127 init: &'gcx hir::Expr) -> Ty<'tcx>
4129 // FIXME(tschottdorf): contains_explicit_ref_binding() must be removed
4131 let ref_bindings = local.pat.contains_explicit_ref_binding();
4133 let local_ty = self.local_ty(init.span, local.id);
4134 if let Some(m) = ref_bindings {
4135 // Somewhat subtle: if we have a `ref` binding in the pattern,
4136 // we want to avoid introducing coercions for the RHS. This is
4137 // both because it helps preserve sanity and, in the case of
4138 // ref mut, for soundness (issue #23116). In particular, in
4139 // the latter case, we need to be clear that the type of the
4140 // referent for the reference that results is *equal to* the
4141 // type of the lvalue it is referencing, and not some
4142 // supertype thereof.
4143 let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
4144 self.demand_eqtype(init.span, init_ty, local_ty);
4147 self.check_expr_coercable_to_type(init, local_ty)
4151 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
4152 let t = self.local_ty(local.span, local.id);
4153 self.write_ty(local.hir_id, t);
4155 if let Some(ref init) = local.init {
4156 let init_ty = self.check_decl_initializer(local, &init);
4157 if init_ty.references_error() {
4158 self.write_ty(local.hir_id, init_ty);
4162 self.check_pat(&local.pat, t);
4163 let pat_ty = self.node_ty(local.pat.hir_id);
4164 if pat_ty.references_error() {
4165 self.write_ty(local.hir_id, pat_ty);
4169 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4170 // Don't do all the complex logic below for DeclItem.
4172 hir::StmtDecl(ref decl, _) => {
4174 hir::DeclLocal(_) => {}
4175 hir::DeclItem(_) => {
4180 hir::StmtExpr(..) | hir::StmtSemi(..) => {}
4183 self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
4185 // Hide the outer diverging and has_errors flags.
4186 let old_diverges = self.diverges.get();
4187 let old_has_errors = self.has_errors.get();
4188 self.diverges.set(Diverges::Maybe);
4189 self.has_errors.set(false);
4192 hir::StmtDecl(ref decl, _) => {
4194 hir::DeclLocal(ref l) => {
4195 self.check_decl_local(&l);
4197 hir::DeclItem(_) => {/* ignore for now */}
4200 hir::StmtExpr(ref expr, _) => {
4201 // Check with expected type of ()
4202 self.check_expr_has_type_or_error(&expr, self.tcx.mk_nil());
4204 hir::StmtSemi(ref expr, _) => {
4205 self.check_expr(&expr);
4209 // Combine the diverging and has_error flags.
4210 self.diverges.set(self.diverges.get() | old_diverges);
4211 self.has_errors.set(self.has_errors.get() | old_has_errors);
4214 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
4215 let unit = self.tcx.mk_nil();
4216 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4218 // if the block produces a `!` value, that can always be
4219 // (effectively) coerced to unit.
4221 self.demand_suptype(blk.span, unit, ty);
4225 fn check_block_with_expected(&self,
4226 blk: &'gcx hir::Block,
4227 expected: Expectation<'tcx>) -> Ty<'tcx> {
4229 let mut fcx_ps = self.ps.borrow_mut();
4230 let unsafety_state = fcx_ps.recurse(blk);
4231 replace(&mut *fcx_ps, unsafety_state)
4234 // In some cases, blocks have just one exit, but other blocks
4235 // can be targeted by multiple breaks. This cannot happen in
4236 // normal Rust syntax today, but it can happen when we desugar
4237 // a `do catch { ... }` expression.
4241 // 'a: { if true { break 'a Err(()); } Ok(()) }
4243 // Here we would wind up with two coercions, one from
4244 // `Err(())` and the other from the tail expression
4245 // `Ok(())`. If the tail expression is omitted, that's a
4246 // "forced unit" -- unless the block diverges, in which
4247 // case we can ignore the tail expression (e.g., `'a: {
4248 // break 'a 22; }` would not force the type of the block
4250 let tail_expr = blk.expr.as_ref();
4251 let coerce_to_ty = expected.coercion_target_type(self, blk.span);
4252 let coerce = if blk.targeted_by_break {
4253 CoerceMany::new(coerce_to_ty)
4255 let tail_expr: &[P<hir::Expr>] = match tail_expr {
4256 Some(e) => ref_slice(e),
4259 CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
4262 let ctxt = BreakableCtxt {
4263 coerce: Some(coerce),
4267 let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
4268 for s in &blk.stmts {
4272 // check the tail expression **without** holding the
4273 // `enclosing_breakables` lock below.
4274 let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
4276 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4277 let ctxt = enclosing_breakables.find_breakable(blk.id);
4278 let coerce = ctxt.coerce.as_mut().unwrap();
4279 if let Some(tail_expr_ty) = tail_expr_ty {
4280 let tail_expr = tail_expr.unwrap();
4281 let cause = self.cause(tail_expr.span,
4282 ObligationCauseCode::BlockTailExpression(blk.id));
4287 self.diverges.get());
4289 // Subtle: if there is no explicit tail expression,
4290 // that is typically equivalent to a tail expression
4291 // of `()` -- except if the block diverges. In that
4292 // case, there is no value supplied from the tail
4293 // expression (assuming there are no other breaks,
4294 // this implies that the type of the block will be
4297 // #41425 -- label the implicit `()` as being the
4298 // "found type" here, rather than the "expected type".
4299 if !self.diverges.get().always() {
4300 coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
4301 if let Some(expected_ty) = expected.only_has_type(self) {
4302 self.consider_hint_about_removing_semicolon(blk,
4311 let mut ty = ctxt.coerce.unwrap().complete(self);
4313 if self.has_errors.get() || ty.references_error() {
4314 ty = self.tcx.types.err
4317 self.write_ty(blk.hir_id, ty);
4319 *self.ps.borrow_mut() = prev;
4323 /// Given a `NodeId`, return the `FnDecl` of the method it is enclosed by and whether a
4324 /// suggestion can be made, `None` otherwise.
4325 pub fn get_fn_decl(&self, blk_id: ast::NodeId) -> Option<(hir::FnDecl, bool)> {
4326 // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
4327 // `while` before reaching it, as block tail returns are not available in them.
4328 if let Some(fn_id) = self.tcx.hir.get_return_block(blk_id) {
4329 let parent = self.tcx.hir.get(fn_id);
4331 if let Node::NodeItem(&hir::Item {
4332 name, node: hir::ItemFn(ref decl, ..), ..
4334 decl.clone().and_then(|decl| {
4335 // This is less than ideal, it will not suggest a return type span on any
4336 // method called `main`, regardless of whether it is actually the entry point,
4337 // but it will still present it as the reason for the expected type.
4338 Some((decl, name != Symbol::intern("main")))
4340 } else if let Node::NodeTraitItem(&hir::TraitItem {
4341 node: hir::TraitItemKind::Method(hir::MethodSig {
4345 decl.clone().and_then(|decl| {
4348 } else if let Node::NodeImplItem(&hir::ImplItem {
4349 node: hir::ImplItemKind::Method(hir::MethodSig {
4353 decl.clone().and_then(|decl| {
4364 /// On implicit return expressions with mismatched types, provide the following suggestions:
4366 /// - Point out the method's return type as the reason for the expected type
4367 /// - Possible missing semicolon
4368 /// - Possible missing return type if the return type is the default, and not `fn main()`
4369 pub fn suggest_mismatched_types_on_tail(&self,
4370 err: &mut DiagnosticBuilder<'tcx>,
4371 expression: &'gcx hir::Expr,
4375 blk_id: ast::NodeId) {
4376 self.suggest_missing_semicolon(err, expression, expected, cause_span);
4378 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
4379 self.suggest_missing_return_type(err, &fn_decl, expected, found, can_suggest);
4383 /// A common error is to forget to add a semicolon at the end of a block:
4387 /// bar_that_returns_u32()
4391 /// This routine checks if the return expression in a block would make sense on its own as a
4392 /// statement and the return type has been left as default or has been specified as `()`. If so,
4393 /// it suggests adding a semicolon.
4394 fn suggest_missing_semicolon(&self,
4395 err: &mut DiagnosticBuilder<'tcx>,
4396 expression: &'gcx hir::Expr,
4399 if expected.is_nil() {
4400 // `BlockTailExpression` only relevant if the tail expr would be
4401 // useful on its own.
4402 match expression.node {
4404 hir::ExprMethodCall(..) |
4406 hir::ExprWhile(..) |
4408 hir::ExprMatch(..) |
4409 hir::ExprBlock(..) => {
4410 let sp = cause_span.next_point();
4411 err.span_suggestion(sp,
4412 "try adding a semicolon",
4421 /// A possible error is to forget to add a return type that is needed:
4425 /// bar_that_returns_u32()
4429 /// This routine checks if the return type is left as default, the method is not part of an
4430 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
4432 fn suggest_missing_return_type(&self,
4433 err: &mut DiagnosticBuilder<'tcx>,
4434 fn_decl: &hir::FnDecl,
4437 can_suggest: bool) {
4438 // Only suggest changing the return type for methods that
4439 // haven't set a return type at all (and aren't `fn main()` or an impl).
4440 match (&fn_decl.output, found.is_suggestable(), can_suggest) {
4441 (&hir::FunctionRetTy::DefaultReturn(span), true, true) => {
4442 err.span_suggestion(span,
4443 "try adding a return type",
4444 format!("-> {} ", found));
4446 (&hir::FunctionRetTy::DefaultReturn(span), false, true) => {
4447 err.span_label(span, "possibly return type missing here?");
4449 (&hir::FunctionRetTy::DefaultReturn(span), _, _) => {
4450 // `fn main()` must return `()`, do not suggest changing return type
4451 err.span_label(span, "expected `()` because of default return type");
4453 (&hir::FunctionRetTy::Return(ref ty), _, _) => {
4454 // Only point to return type if the expected type is the return type, as if they
4455 // are not, the expectation must have been caused by something else.
4456 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.node);
4458 let ty = AstConv::ast_ty_to_ty(self, ty);
4459 debug!("suggest_missing_return_type: return type sty {:?}", ty.sty);
4460 debug!("suggest_missing_return_type: expected type sty {:?}", ty.sty);
4461 if ty.sty == expected.sty {
4462 err.span_label(sp, format!("expected `{}` because of return type",
4470 /// A common error is to add an extra semicolon:
4473 /// fn foo() -> usize {
4478 /// This routine checks if the final statement in a block is an
4479 /// expression with an explicit semicolon whose type is compatible
4480 /// with `expected_ty`. If so, it suggests removing the semicolon.
4481 fn consider_hint_about_removing_semicolon(&self,
4482 blk: &'gcx hir::Block,
4483 expected_ty: Ty<'tcx>,
4484 err: &mut DiagnosticBuilder) {
4485 // Be helpful when the user wrote `{... expr;}` and
4486 // taking the `;` off is enough to fix the error.
4487 let last_stmt = match blk.stmts.last() {
4491 let last_expr = match last_stmt.node {
4492 hir::StmtSemi(ref e, _) => e,
4495 let last_expr_ty = self.node_ty(last_expr.hir_id);
4496 if self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err() {
4499 let original_span = original_sp(last_stmt.span, blk.span);
4500 let span_semi = original_span.with_lo(original_span.hi() - BytePos(1));
4501 err.span_suggestion(span_semi, "consider removing this semicolon", "".to_string());
4504 // Instantiates the given path, which must refer to an item with the given
4505 // number of type parameters and type.
4506 pub fn instantiate_value_path(&self,
4507 segments: &[hir::PathSegment],
4508 opt_self_ty: Option<Ty<'tcx>>,
4511 node_id: ast::NodeId)
4513 debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4518 // We need to extract the type parameters supplied by the user in
4519 // the path `path`. Due to the current setup, this is a bit of a
4520 // tricky-process; the problem is that resolve only tells us the
4521 // end-point of the path resolution, and not the intermediate steps.
4522 // Luckily, we can (at least for now) deduce the intermediate steps
4523 // just from the end-point.
4525 // There are basically four cases to consider:
4527 // 1. Reference to a constructor of enum variant or struct:
4529 // struct Foo<T>(...)
4530 // enum E<T> { Foo(...) }
4532 // In these cases, the parameters are declared in the type
4535 // 2. Reference to a fn item or a free constant:
4539 // In this case, the path will again always have the form
4540 // `a::b::foo::<T>` where only the final segment should have
4541 // type parameters. However, in this case, those parameters are
4542 // declared on a value, and hence are in the `FnSpace`.
4544 // 3. Reference to a method or an associated constant:
4546 // impl<A> SomeStruct<A> {
4550 // Here we can have a path like
4551 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4552 // may appear in two places. The penultimate segment,
4553 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4554 // final segment, `foo::<B>` contains parameters in fn space.
4556 // 4. Reference to a local variable
4558 // Local variables can't have any type parameters.
4560 // The first step then is to categorize the segments appropriately.
4562 assert!(!segments.is_empty());
4564 let mut ufcs_associated = None;
4565 let mut type_segment = None;
4566 let mut fn_segment = None;
4568 // Case 1. Reference to a struct/variant constructor.
4569 Def::StructCtor(def_id, ..) |
4570 Def::VariantCtor(def_id, ..) => {
4571 // Everything but the final segment should have no
4572 // parameters at all.
4573 let mut generics = self.tcx.generics_of(def_id);
4574 if let Some(def_id) = generics.parent {
4575 // Variant and struct constructors use the
4576 // generics of their parent type definition.
4577 generics = self.tcx.generics_of(def_id);
4579 type_segment = Some((segments.last().unwrap(), generics));
4582 // Case 2. Reference to a top-level value.
4584 Def::Const(def_id) |
4585 Def::Static(def_id, _) => {
4586 fn_segment = Some((segments.last().unwrap(),
4587 self.tcx.generics_of(def_id)));
4590 // Case 3. Reference to a method or associated const.
4591 Def::Method(def_id) |
4592 Def::AssociatedConst(def_id) => {
4593 let container = self.tcx.associated_item(def_id).container;
4595 ty::TraitContainer(trait_did) => {
4596 callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4598 ty::ImplContainer(_) => {}
4601 let generics = self.tcx.generics_of(def_id);
4602 if segments.len() >= 2 {
4603 let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
4604 type_segment = Some((&segments[segments.len() - 2], parent_generics));
4606 // `<T>::assoc` will end up here, and so can `T::assoc`.
4607 let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4608 ufcs_associated = Some((container, self_ty));
4610 fn_segment = Some((segments.last().unwrap(), generics));
4613 // Case 4. Local variable, no generics.
4614 Def::Local(..) | Def::Upvar(..) => {}
4616 _ => bug!("unexpected definition: {:?}", def),
4619 debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4621 // Now that we have categorized what space the parameters for each
4622 // segment belong to, let's sort out the parameters that the user
4623 // provided (if any) into their appropriate spaces. We'll also report
4624 // errors if type parameters are provided in an inappropriate place.
4625 let poly_segments = type_segment.is_some() as usize +
4626 fn_segment.is_some() as usize;
4627 AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4630 Def::Local(nid) | Def::Upvar(nid, ..) => {
4631 let ty = self.local_ty(span, nid);
4632 let ty = self.normalize_associated_types_in(span, &ty);
4633 self.write_ty(self.tcx.hir.node_to_hir_id(node_id), ty);
4639 // Now we have to compare the types that the user *actually*
4640 // provided against the types that were *expected*. If the user
4641 // did not provide any types, then we want to substitute inference
4642 // variables. If the user provided some types, we may still need
4643 // to add defaults. If the user provided *too many* types, that's
4645 self.check_path_parameter_count(span, &mut type_segment, false);
4646 self.check_path_parameter_count(span, &mut fn_segment, false);
4648 let (fn_start, has_self) = match (type_segment, fn_segment) {
4649 (_, Some((_, generics))) => {
4650 (generics.parent_count(), generics.has_self)
4652 (Some((_, generics)), None) => {
4653 (generics.own_count(), generics.has_self)
4655 (None, None) => (0, false)
4657 let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4658 let mut i = def.index as usize;
4660 let segment = if i < fn_start {
4661 i -= has_self as usize;
4667 let lifetimes = segment.map_or(&[][..], |(s, _)| &s.parameters.lifetimes[..]);
4669 if let Some(lifetime) = lifetimes.get(i) {
4670 AstConv::ast_region_to_region(self, lifetime, Some(def))
4672 self.re_infer(span, Some(def)).unwrap()
4675 let mut i = def.index as usize;
4677 let segment = if i < fn_start {
4678 // Handle Self first, so we can adjust the index to match the AST.
4679 if has_self && i == 0 {
4680 return opt_self_ty.unwrap_or_else(|| {
4681 self.type_var_for_def(span, def, substs)
4684 i -= has_self as usize;
4690 let (types, infer_types) = segment.map_or((&[][..], true), |(s, _)| {
4691 (&s.parameters.types[..], s.parameters.infer_types)
4694 // Skip over the lifetimes in the same segment.
4695 if let Some((_, generics)) = segment {
4696 i -= generics.regions.len();
4699 if let Some(ast_ty) = types.get(i) {
4700 // A provided type parameter.
4702 } else if !infer_types && def.has_default {
4703 // No type parameter provided, but a default exists.
4704 let default = self.tcx.type_of(def.def_id);
4707 default.subst_spanned(self.tcx, substs, Some(span))
4710 // No type parameters were provided, we can infer all.
4711 // This can also be reached in some error cases:
4712 // We prefer to use inference variables instead of
4713 // TyError to let type inference recover somewhat.
4714 self.type_var_for_def(span, def, substs)
4718 // The things we are substituting into the type should not contain
4719 // escaping late-bound regions, and nor should the base type scheme.
4720 let ty = self.tcx.type_of(def.def_id());
4721 assert!(!substs.has_escaping_regions());
4722 assert!(!ty.has_escaping_regions());
4724 // Add all the obligations that are required, substituting and
4725 // normalized appropriately.
4726 let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4727 self.add_obligations_for_parameters(
4728 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4731 // Substitute the values for the type parameters into the type of
4732 // the referenced item.
4733 let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4735 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4736 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4737 // is inherent, there is no `Self` parameter, instead, the impl needs
4738 // type parameters, which we can infer by unifying the provided `Self`
4739 // with the substituted impl type.
4740 let ty = self.tcx.type_of(impl_def_id);
4742 let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4743 match self.at(&self.misc(span), self.param_env).sup(impl_ty, self_ty) {
4744 Ok(ok) => self.register_infer_ok_obligations(ok),
4747 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4754 debug!("instantiate_value_path: type of {:?} is {:?}",
4757 self.write_substs(self.tcx.hir.node_to_hir_id(node_id), substs);
4761 /// Report errors if the provided parameters are too few or too many.
4762 fn check_path_parameter_count(&self,
4764 segment: &mut Option<(&hir::PathSegment, &ty::Generics)>,
4765 is_method_call: bool) {
4766 let (lifetimes, types, infer_types, bindings) = segment.map_or(
4767 (&[][..], &[][..], true, &[][..]),
4768 |(s, _)| (&s.parameters.lifetimes[..], &s.parameters.types[..],
4769 s.parameters.infer_types, &s.parameters.bindings[..]));
4770 let infer_lifetimes = lifetimes.len() == 0;
4772 let count_lifetime_params = |n| {
4773 format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4775 let count_type_params = |n| {
4776 format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4779 // Check provided type parameters.
4780 let type_defs = segment.map_or(&[][..], |(_, generics)| {
4781 if generics.parent.is_none() {
4782 &generics.types[generics.has_self as usize..]
4787 let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4788 if types.len() > type_defs.len() {
4789 let span = types[type_defs.len()].span;
4790 let expected_text = count_type_params(type_defs.len());
4791 let actual_text = count_type_params(types.len());
4792 struct_span_err!(self.tcx.sess, span, E0087,
4793 "too many type parameters provided: \
4794 expected at most {}, found {}",
4795 expected_text, actual_text)
4796 .span_label(span, format!("expected {}", expected_text))
4799 // To prevent derived errors to accumulate due to extra
4800 // type parameters, we force instantiate_value_path to
4801 // use inference variables instead of the provided types.
4803 } else if types.len() < required_len && !infer_types {
4804 let expected_text = count_type_params(required_len);
4805 let actual_text = count_type_params(types.len());
4806 struct_span_err!(self.tcx.sess, span, E0089,
4807 "too few type parameters provided: \
4808 expected {}, found {}",
4809 expected_text, actual_text)
4810 .span_label(span, format!("expected {}", expected_text))
4814 if !bindings.is_empty() {
4815 AstConv::prohibit_projection(self, bindings[0].span);
4818 // Check provided lifetime parameters.
4819 let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4820 let required_len = lifetime_defs.len();
4822 // Prohibit explicit lifetime arguments if late bound lifetime parameters are present.
4823 let has_late_bound_lifetime_defs =
4824 segment.map_or(None, |(_, generics)| generics.has_late_bound_regions);
4825 if let (Some(span_late), false) = (has_late_bound_lifetime_defs, lifetimes.is_empty()) {
4826 // Report this as a lint only if no error was reported previously.
4827 let primary_msg = "cannot specify lifetime arguments explicitly \
4828 if late bound lifetime parameters are present";
4829 let note_msg = "the late bound lifetime parameter is introduced here";
4830 if !is_method_call && (lifetimes.len() > lifetime_defs.len() ||
4831 lifetimes.len() < required_len && !infer_lifetimes) {
4832 let mut err = self.tcx.sess.struct_span_err(lifetimes[0].span, primary_msg);
4833 err.span_note(span_late, note_msg);
4837 let mut multispan = MultiSpan::from_span(lifetimes[0].span);
4838 multispan.push_span_label(span_late, note_msg.to_string());
4839 self.tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
4840 lifetimes[0].id, multispan, primary_msg);
4845 if lifetimes.len() > lifetime_defs.len() {
4846 let span = lifetimes[lifetime_defs.len()].span;
4847 let expected_text = count_lifetime_params(lifetime_defs.len());
4848 let actual_text = count_lifetime_params(lifetimes.len());
4849 struct_span_err!(self.tcx.sess, span, E0088,
4850 "too many lifetime parameters provided: \
4851 expected at most {}, found {}",
4852 expected_text, actual_text)
4853 .span_label(span, format!("expected {}", expected_text))
4855 } else if lifetimes.len() < required_len && !infer_lifetimes {
4856 let expected_text = count_lifetime_params(lifetime_defs.len());
4857 let actual_text = count_lifetime_params(lifetimes.len());
4858 struct_span_err!(self.tcx.sess, span, E0090,
4859 "too few lifetime parameters provided: \
4860 expected {}, found {}",
4861 expected_text, actual_text)
4862 .span_label(span, format!("expected {}", expected_text))
4867 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4869 where F: Fn() -> Ty<'tcx>
4871 let mut ty = self.resolve_type_vars_with_obligations(ty);
4874 let alternative = f();
4877 if alternative.is_ty_var() || alternative.references_error() {
4878 if !self.is_tainted_by_errors() {
4879 type_error_struct!(self.tcx.sess, sp, ty, E0619,
4880 "the type of this value must be known in this context")
4883 self.demand_suptype(sp, self.tcx.types.err, ty);
4884 ty = self.tcx.types.err;
4886 self.demand_suptype(sp, alternative, ty);
4894 // Resolves `typ` by a single level if `typ` is a type variable. If no
4895 // resolution is possible, then an error is reported.
4896 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4897 self.structurally_resolve_type_or_else(sp, ty, || {
4902 fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4903 ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4904 -> (BreakableCtxt<'gcx, 'tcx>, R) {
4907 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4908 index = enclosing_breakables.stack.len();
4909 enclosing_breakables.by_id.insert(id, index);
4910 enclosing_breakables.stack.push(ctxt);
4914 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4915 debug_assert!(enclosing_breakables.stack.len() == index + 1);
4916 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4917 enclosing_breakables.stack.pop().expect("missing breakable context")
4923 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4924 generics: &hir::Generics,
4926 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4927 generics.ty_params.len(), ty);
4929 // make a vector of booleans initially false, set to true when used
4930 if generics.ty_params.is_empty() { return; }
4931 let mut tps_used = vec![false; generics.ty_params.len()];
4933 for leaf_ty in ty.walk() {
4934 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4935 debug!("Found use of ty param num {}", idx);
4936 tps_used[idx as usize - generics.lifetimes.len()] = true;
4940 for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4942 struct_span_err!(tcx.sess, param.span, E0091,
4943 "type parameter `{}` is unused",
4945 .span_label(param.span, "unused type parameter")
4951 fn fatally_break_rust(sess: &Session) {
4952 let handler = sess.diagnostic();
4953 handler.span_bug_no_panic(
4955 "It looks like you're trying to break rust; would you like some ICE?",
4957 handler.note_without_error("the compiler expectedly panicked. this is a feature.");
4958 handler.note_without_error(
4959 "we would appreciate a joke overview: \
4960 https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675"
4962 handler.note_without_error(&format!("rustc {} running on {}",
4963 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
4964 ::session::config::host_triple(),