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 fmt_macros::{Parser, Piece, Position};
89 use hir::def::{Def, CtorKind};
90 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
91 use rustc_back::slice::ref_slice;
92 use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
93 use rustc::infer::type_variable::{TypeVariableOrigin};
94 use rustc::middle::region::CodeExtent;
95 use rustc::ty::subst::{Kind, Subst, Substs};
96 use rustc::traits::{self, FulfillmentContext, ObligationCause, ObligationCauseCode};
97 use rustc::ty::{ParamTy, LvaluePreference, NoPreference, PreferMutLvalue};
98 use rustc::ty::{self, Ty, TyCtxt, Visibility};
99 use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
100 use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
101 use rustc::ty::maps::Providers;
102 use rustc::ty::util::{Representability, IntTypeExt};
103 use errors::DiagnosticBuilder;
104 use require_c_abi_if_variadic;
105 use session::{Session, CompileResult};
108 use util::common::{ErrorReported, indenter};
109 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
111 use std::cell::{Cell, RefCell, Ref, RefMut};
112 use std::collections::hash_map::Entry;
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};
125 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
126 use rustc::hir::itemlikevisit::ItemLikeVisitor;
127 use rustc::hir::{self, PatKind};
128 use rustc::middle::lang_items;
129 use rustc_back::slice;
130 use rustc::middle::const_val::eval_length;
131 use rustc_const_math::ConstInt;
150 /// A wrapper for InferCtxt's `in_progress_tables` field.
151 #[derive(Copy, Clone)]
152 struct MaybeInProgressTables<'a, 'tcx: 'a> {
153 maybe_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
156 impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> {
157 fn borrow(self) -> Ref<'a, ty::TypeckTables<'tcx>> {
158 match self.maybe_tables {
159 Some(tables) => tables.borrow(),
161 bug!("MaybeInProgressTables: inh/fcx.tables.borrow() with no tables")
166 fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
167 match self.maybe_tables {
168 Some(tables) => tables.borrow_mut(),
170 bug!("MaybeInProgressTables: inh/fcx.tables.borrow_mut() with no tables")
177 /// closures defined within the function. For example:
180 /// bar(move|| { ... })
183 /// Here, the function `foo()` and the closure passed to
184 /// `bar()` will each have their own `FnCtxt`, but they will
185 /// share the inherited fields.
186 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
187 infcx: InferCtxt<'a, 'gcx, 'tcx>,
189 tables: MaybeInProgressTables<'a, 'tcx>,
191 locals: RefCell<NodeMap<Ty<'tcx>>>,
193 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
195 // When we process a call like `c()` where `c` is a closure type,
196 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
197 // `FnOnce` closure. In that case, we defer full resolution of the
198 // call until upvar inference can kick in and make the
199 // decision. We keep these deferred resolutions grouped by the
200 // def-id of the closure, so that once we decide, we can easily go
201 // back and process them.
202 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'gcx, 'tcx>>>>,
204 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
206 // Anonymized types found in explicit return types and their
207 // associated fresh inference variable. Writeback resolves these
208 // variables to get the concrete type, which can be used to
209 // deanonymize TyAnon, after typeck is done with all functions.
210 anon_types: RefCell<NodeMap<Ty<'tcx>>>,
212 /// Each type parameter has an implicit region bound that
213 /// indicates it must outlive at least the function body (the user
214 /// may specify stronger requirements). This field indicates the
215 /// region of the callee. If it is `None`, then the parameter
216 /// environment is for an item or something where the "callee" is
218 implicit_region_bound: Option<ty::Region<'tcx>>,
221 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
222 type Target = InferCtxt<'a, 'gcx, 'tcx>;
223 fn deref(&self) -> &Self::Target {
228 /// When type-checking an expression, we propagate downward
229 /// whatever type hint we are able in the form of an `Expectation`.
230 #[derive(Copy, Clone, Debug)]
231 pub enum Expectation<'tcx> {
232 /// We know nothing about what type this expression should have.
235 /// This expression should have the type given (or some subtype)
236 ExpectHasType(Ty<'tcx>),
238 /// This expression will be cast to the `Ty`
239 ExpectCastableToType(Ty<'tcx>),
241 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
242 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
243 ExpectRvalueLikeUnsized(Ty<'tcx>),
246 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
247 // Disregard "castable to" expectations because they
248 // can lead us astray. Consider for example `if cond
249 // {22} else {c} as u8` -- if we propagate the
250 // "castable to u8" constraint to 22, it will pick the
251 // type 22u8, which is overly constrained (c might not
252 // be a u8). In effect, the problem is that the
253 // "castable to" expectation is not the tightest thing
254 // we can say, so we want to drop it in this case.
255 // The tightest thing we can say is "must unify with
256 // else branch". Note that in the case of a "has type"
257 // constraint, this limitation does not hold.
259 // If the expected type is just a type variable, then don't use
260 // an expected type. Otherwise, we might write parts of the type
261 // when checking the 'then' block which are incompatible with the
263 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
265 ExpectHasType(ety) => {
266 let ety = fcx.shallow_resolve(ety);
267 if !ety.is_ty_var() {
273 ExpectRvalueLikeUnsized(ety) => {
274 ExpectRvalueLikeUnsized(ety)
280 /// Provide an expectation for an rvalue expression given an *optional*
281 /// hint, which is not required for type safety (the resulting type might
282 /// be checked higher up, as is the case with `&expr` and `box expr`), but
283 /// is useful in determining the concrete type.
285 /// The primary use case is where the expected type is a fat pointer,
286 /// like `&[isize]`. For example, consider the following statement:
288 /// let x: &[isize] = &[1, 2, 3];
290 /// In this case, the expected type for the `&[1, 2, 3]` expression is
291 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
292 /// expectation `ExpectHasType([isize])`, that would be too strong --
293 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
294 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
295 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
296 /// which still is useful, because it informs integer literals and the like.
297 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
298 /// for examples of where this comes up,.
299 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
300 match fcx.tcx.struct_tail(ty).sty {
301 ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
302 ExpectRvalueLikeUnsized(ty)
304 _ => ExpectHasType(ty)
308 // Resolves `expected` by a single level if it is a variable. If
309 // there is no expected type or resolution is not possible (e.g.,
310 // no constraints yet present), just returns `None`.
311 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
316 ExpectCastableToType(t) => {
317 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
319 ExpectHasType(t) => {
320 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
322 ExpectRvalueLikeUnsized(t) => {
323 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
328 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
329 match self.resolve(fcx) {
330 NoExpectation => None,
331 ExpectCastableToType(ty) |
333 ExpectRvalueLikeUnsized(ty) => Some(ty),
337 /// It sometimes happens that we want to turn an expectation into
338 /// a **hard constraint** (i.e., something that must be satisfied
339 /// for the program to type-check). `only_has_type` will return
340 /// such a constraint, if it exists.
341 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
342 match self.resolve(fcx) {
343 ExpectHasType(ty) => Some(ty),
348 /// Like `only_has_type`, but instead of returning `None` if no
349 /// hard constraint exists, creates a fresh type variable.
350 fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
351 self.only_has_type(fcx)
352 .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
356 #[derive(Copy, Clone)]
357 pub struct UnsafetyState {
358 pub def: ast::NodeId,
359 pub unsafety: hir::Unsafety,
360 pub unsafe_push_count: u32,
365 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
366 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
369 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
370 match self.unsafety {
371 // If this unsafe, then if the outer function was already marked as
372 // unsafe we shouldn't attribute the unsafe'ness to the block. This
373 // way the block can be warned about instead of ignoring this
374 // extraneous block (functions are never warned about).
375 hir::Unsafety::Unsafe if self.from_fn => *self,
378 let (unsafety, def, count) = match blk.rules {
379 hir::PushUnsafeBlock(..) =>
380 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
381 hir::PopUnsafeBlock(..) =>
382 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
383 hir::UnsafeBlock(..) =>
384 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
386 (unsafety, self.def, self.unsafe_push_count),
388 UnsafetyState{ def: def,
390 unsafe_push_count: count,
397 #[derive(Debug, Copy, Clone)]
403 /// Tracks whether executing a node may exit normally (versus
404 /// return/break/panic, which "diverge", leaving dead code in their
405 /// wake). Tracked semi-automatically (through type variables marked
406 /// as diverging), with some manual adjustments for control-flow
407 /// primitives (approximating a CFG).
408 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
410 /// Potentially unknown, some cases converge,
411 /// others require a CFG to determine them.
414 /// Definitely known to diverge and therefore
415 /// not reach the next sibling or its parent.
418 /// Same as `Always` but with a reachability
419 /// warning already emitted
423 // Convenience impls for combinig `Diverges`.
425 impl ops::BitAnd for Diverges {
427 fn bitand(self, other: Self) -> Self {
428 cmp::min(self, other)
432 impl ops::BitOr for Diverges {
434 fn bitor(self, other: Self) -> Self {
435 cmp::max(self, other)
439 impl ops::BitAndAssign for Diverges {
440 fn bitand_assign(&mut self, other: Self) {
441 *self = *self & other;
445 impl ops::BitOrAssign for Diverges {
446 fn bitor_assign(&mut self, other: Self) {
447 *self = *self | other;
452 fn always(self) -> bool {
453 self >= Diverges::Always
457 pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
460 // this is `null` for loops where break with a value is illegal,
461 // such as `while`, `for`, and `while let`
462 coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>,
465 pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
466 stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
467 by_id: NodeMap<usize>,
470 impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
471 fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
472 let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
473 bug!("could not find enclosing breakable with id {}", target_id);
479 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
480 body_id: ast::NodeId,
482 /// The parameter environment used for proving trait obligations
483 /// in this function. This can change when we descend into
484 /// closures (as they bring new things into scope), hence it is
485 /// not part of `Inherited` (as of the time of this writing,
486 /// closures do not yet change the environment, but they will
488 param_env: ty::ParamEnv<'tcx>,
490 // Number of errors that had been reported when we started
491 // checking this function. On exit, if we find that *more* errors
492 // have been reported, we will skip regionck and other work that
493 // expects the types within the function to be consistent.
494 err_count_on_creation: usize,
496 ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>,
498 ps: RefCell<UnsafetyState>,
500 /// Whether the last checked node generates a divergence (e.g.,
501 /// `return` will set this to Always). In general, when entering
502 /// an expression or other node in the tree, the initial value
503 /// indicates whether prior parts of the containing expression may
504 /// have diverged. It is then typically set to `Maybe` (and the
505 /// old value remembered) for processing the subparts of the
506 /// current expression. As each subpart is processed, they may set
507 /// the flag to `Always` etc. Finally, at the end, we take the
508 /// result and "union" it with the original value, so that when we
509 /// return the flag indicates if any subpart of the the parent
510 /// expression (up to and including this part) has diverged. So,
511 /// if you read it after evaluating a subexpression `X`, the value
512 /// you get indicates whether any subexpression that was
513 /// evaluating up to and including `X` diverged.
515 /// We use this flag for two purposes:
517 /// - To warn about unreachable code: if, after processing a
518 /// sub-expression but before we have applied the effects of the
519 /// current node, we see that the flag is set to `Always`, we
520 /// can issue a warning. This corresponds to something like
521 /// `foo(return)`; we warn on the `foo()` expression. (We then
522 /// update the flag to `WarnedAlways` to suppress duplicate
523 /// reports.) Similarly, if we traverse to a fresh statement (or
524 /// tail expression) from a `Always` setting, we will isssue a
525 /// warning. This corresponds to something like `{return;
526 /// foo();}` or `{return; 22}`, where we would warn on the
529 /// - To permit assignment into a local variable or other lvalue
530 /// (including the "return slot") of type `!`. This is allowed
531 /// if **either** the type of value being assigned is `!`, which
532 /// means the current code is dead, **or** the expression's
533 /// divering flag is true, which means that a divering value was
534 /// wrapped (e.g., `let x: ! = foo(return)`).
536 /// To repeat the last point: an expression represents dead-code
537 /// if, after checking it, **either** its type is `!` OR the
538 /// diverges flag is set to something other than `Maybe`.
539 diverges: Cell<Diverges>,
541 /// Whether any child nodes have any type errors.
542 has_errors: Cell<bool>,
544 enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
546 inh: &'a Inherited<'a, 'gcx, 'tcx>,
549 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
550 type Target = Inherited<'a, 'gcx, 'tcx>;
551 fn deref(&self) -> &Self::Target {
556 /// Helper type of a temporary returned by Inherited::build(...).
557 /// Necessary because we can't write the following bound:
558 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
559 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
560 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>,
564 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
565 pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId)
566 -> InheritedBuilder<'a, 'gcx, 'tcx> {
568 infcx: tcx.infer_ctxt().with_fresh_in_progress_tables(),
574 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
575 fn enter<F, R>(&'tcx mut self, f: F) -> R
576 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
578 let def_id = self.def_id;
579 self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
583 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
584 fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> Self {
586 let item_id = tcx.hir.as_local_node_id(def_id);
587 let body_id = item_id.and_then(|id| tcx.hir.maybe_body_owned_by(id));
588 let implicit_region_bound = body_id.map(|body| {
589 tcx.mk_region(ty::ReScope(CodeExtent::CallSiteScope(body)))
593 tables: MaybeInProgressTables {
594 maybe_tables: infcx.in_progress_tables,
597 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
598 locals: RefCell::new(NodeMap()),
599 deferred_call_resolutions: RefCell::new(DefIdMap()),
600 deferred_cast_checks: RefCell::new(Vec::new()),
601 anon_types: RefCell::new(NodeMap()),
602 implicit_region_bound,
606 fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
607 debug!("register_predicate({:?})", obligation);
608 if obligation.has_escaping_regions() {
609 span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
614 .register_predicate_obligation(self, obligation);
617 fn register_predicates(&self, obligations: Vec<traits::PredicateObligation<'tcx>>) {
618 for obligation in obligations {
619 self.register_predicate(obligation);
623 fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
624 self.register_predicates(infer_ok.obligations);
628 fn normalize_associated_types_in<T>(&self,
630 body_id: ast::NodeId,
631 param_env: ty::ParamEnv<'tcx>,
633 where T : TypeFoldable<'tcx>
635 let ok = self.normalize_associated_types_in_as_infer_ok(span, body_id, param_env, value);
636 self.register_infer_ok_obligations(ok)
639 fn normalize_associated_types_in_as_infer_ok<T>(&self,
641 body_id: ast::NodeId,
642 param_env: ty::ParamEnv<'tcx>,
645 where T : TypeFoldable<'tcx>
647 debug!("normalize_associated_types_in(value={:?})", value);
648 let mut selcx = traits::SelectionContext::new(self);
649 let cause = ObligationCause::misc(span, body_id);
650 let traits::Normalized { value, obligations } =
651 traits::normalize(&mut selcx, param_env, cause, value);
652 debug!("normalize_associated_types_in: result={:?} predicates={:?}",
655 InferOk { value, obligations }
658 /// Replace any late-bound regions bound in `value` with
659 /// free variants attached to `all_outlive_scope`.
660 fn liberate_late_bound_regions<T>(&self,
661 all_outlive_scope: DefId,
662 value: &ty::Binder<T>)
664 where T: TypeFoldable<'tcx>
666 self.tcx.replace_late_bound_regions(value, |br| {
667 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
668 scope: all_outlive_scope,
675 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
677 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
678 fn visit_item(&mut self, i: &'tcx hir::Item) {
679 check_item_type(self.tcx, i);
681 fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
682 fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
685 pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
686 tcx.sess.track_errors(|| {
687 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
688 tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor());
692 pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
693 tcx.sess.track_errors(|| {
694 tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx });
698 pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
699 tcx.typeck_item_bodies(LOCAL_CRATE)
702 fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> CompileResult {
703 debug_assert!(crate_num == LOCAL_CRATE);
704 tcx.sess.track_errors(|| {
705 for body_owner_def_id in tcx.body_owners() {
706 tcx.typeck_tables_of(body_owner_def_id);
711 pub fn provide(providers: &mut Providers) {
712 *providers = Providers {
723 fn closure_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
725 -> ty::PolyFnSig<'tcx> {
726 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
727 tcx.typeck_tables_of(def_id).closure_tys[&node_id]
730 fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
733 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
734 tcx.typeck_tables_of(def_id).closure_kinds[&node_id].0
737 fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
739 -> Option<ty::Destructor> {
740 tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
743 /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))`
744 /// with information about it's body-id and fn-decl (if any). Otherwise,
747 /// If this function returns "some", then `typeck_tables(def_id)` will
748 /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or
749 /// may not succeed. In some cases where this function returns `None`
750 /// (notably closures), `typeck_tables(def_id)` would wind up
751 /// redirecting to the owning function.
752 fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
754 -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)>
756 match tcx.hir.get(id) {
757 hir::map::NodeItem(item) => {
759 hir::ItemConst(_, body) |
760 hir::ItemStatic(_, _, body) =>
762 hir::ItemFn(ref decl, .., body) =>
763 Some((body, Some(decl))),
768 hir::map::NodeTraitItem(item) => {
770 hir::TraitItemKind::Const(_, Some(body)) =>
772 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) =>
773 Some((body, Some(&sig.decl))),
778 hir::map::NodeImplItem(item) => {
780 hir::ImplItemKind::Const(_, body) =>
782 hir::ImplItemKind::Method(ref sig, body) =>
783 Some((body, Some(&sig.decl))),
788 hir::map::NodeExpr(expr) => {
789 // FIXME(eddyb) Closures should have separate
790 // function definition IDs and expression IDs.
791 // Type-checking should not let closures get
792 // this far in a constant position.
793 // Assume that everything other than closures
794 // is a constant "initializer" expression.
796 hir::ExprClosure(..) =>
799 Some((hir::BodyId { node_id: expr.id }, None)),
806 fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
809 // Closures' tables come from their outermost function,
810 // as they are part of the same "inference environment".
811 let outer_def_id = tcx.closure_base_def_id(def_id);
812 if outer_def_id != def_id {
813 return tcx.has_typeck_tables(outer_def_id);
816 let id = tcx.hir.as_local_node_id(def_id).unwrap();
817 primary_body_of(tcx, id).is_some()
820 fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
822 -> &'tcx ty::TypeckTables<'tcx> {
823 // Closures' tables come from their outermost function,
824 // as they are part of the same "inference environment".
825 let outer_def_id = tcx.closure_base_def_id(def_id);
826 if outer_def_id != def_id {
827 return tcx.typeck_tables_of(outer_def_id);
830 let id = tcx.hir.as_local_node_id(def_id).unwrap();
831 let span = tcx.hir.span(id);
833 // Figure out what primary body this item has.
834 let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| {
835 span_bug!(span, "can't type-check body of {:?}", def_id);
837 let body = tcx.hir.body(body_id);
839 Inherited::build(tcx, def_id).enter(|inh| {
840 let param_env = tcx.param_env(def_id);
841 let fcx = if let Some(decl) = fn_decl {
842 let fn_sig = tcx.type_of(def_id).fn_sig();
844 check_abi(tcx, span, fn_sig.abi());
846 // Compute the fty from point of view of inside fn.
848 inh.liberate_late_bound_regions(def_id, &fn_sig);
850 inh.normalize_associated_types_in(body.value.span,
855 check_fn(&inh, param_env, fn_sig, decl, id, body)
857 let fcx = FnCtxt::new(&inh, param_env, body.value.id);
858 let expected_type = tcx.type_of(def_id);
859 let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
860 fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
862 // Gather locals in statics (because of block expressions).
863 // This is technically unnecessary because locals in static items are forbidden,
864 // but prevents type checking from blowing up before const checking can properly
866 GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
868 fcx.check_expr_coercable_to_type(&body.value, expected_type);
873 fcx.select_all_obligations_and_apply_defaults();
874 fcx.closure_analyze(body);
875 fcx.select_obligations_where_possible();
877 fcx.select_all_obligations_or_error();
879 if fn_decl.is_some() {
880 fcx.regionck_fn(id, body);
882 fcx.regionck_expr(body);
885 fcx.resolve_type_vars_in_body(body)
889 fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
890 if !tcx.sess.target.target.is_abi_supported(abi) {
891 struct_span_err!(tcx.sess, span, E0570,
892 "The ABI `{}` is not supported for the current target", abi).emit()
896 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
897 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
900 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
901 fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
904 // infer the variable's type
905 let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
906 self.fcx.locals.borrow_mut().insert(nid, var_ty);
910 // take type that the user specified
911 self.fcx.locals.borrow_mut().insert(nid, typ);
918 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
919 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
920 NestedVisitorMap::None
923 // Add explicitly-declared locals.
924 fn visit_local(&mut self, local: &'gcx hir::Local) {
925 let o_ty = match local.ty {
926 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
929 self.assign(local.span, local.id, o_ty);
930 debug!("Local variable {:?} is assigned type {}",
932 self.fcx.ty_to_string(
933 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
934 intravisit::walk_local(self, local);
937 // Add pattern bindings.
938 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
939 if let PatKind::Binding(_, _, ref path1, _) = p.node {
940 let var_ty = self.assign(p.span, p.id, None);
942 self.fcx.require_type_is_sized(var_ty, p.span,
943 traits::VariableType(p.id));
945 debug!("Pattern binding {} is assigned to {} with type {:?}",
947 self.fcx.ty_to_string(
948 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
951 intravisit::walk_pat(self, p);
954 // Don't descend into the bodies of nested closures
955 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
956 _: hir::BodyId, _: Span, _: ast::NodeId) { }
959 /// Helper used for fns and closures. Does the grungy work of checking a function
960 /// body and returns the function context used for that purpose, since in the case of a fn item
961 /// there is still a bit more to do.
964 /// * inherited: other fields inherited from the enclosing fn (if any)
965 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
966 param_env: ty::ParamEnv<'tcx>,
967 fn_sig: ty::FnSig<'tcx>,
968 decl: &'gcx hir::FnDecl,
970 body: &'gcx hir::Body)
971 -> FnCtxt<'a, 'gcx, 'tcx>
973 let mut fn_sig = fn_sig.clone();
975 debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env);
977 // Create the function context. This is either derived from scratch or,
978 // in the case of function expressions, based on the outer context.
979 let mut fcx = FnCtxt::new(inherited, param_env, body.value.id);
980 *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
982 let ret_ty = fn_sig.output();
983 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
984 let ret_ty = fcx.instantiate_anon_types(&ret_ty);
985 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
986 fn_sig = fcx.tcx.mk_fn_sig(
987 fn_sig.inputs().iter().cloned(),
994 GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
996 // Add formal parameters.
997 for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
998 // The type of the argument must be well-formed.
1000 // NB -- this is now checked in wfcheck, but that
1001 // currently only results in warnings, so we issue an
1002 // old-style WF obligation here so that we still get the
1003 // errors that we used to get.
1004 fcx.register_old_wf_obligation(arg_ty, arg.pat.span, traits::MiscObligation);
1006 // Check the pattern.
1007 fcx.check_pat_arg(&arg.pat, arg_ty, true);
1008 fcx.write_ty(arg.id, arg_ty);
1011 inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig);
1013 fcx.check_return_expr(&body.value);
1015 // Finalize the return check by taking the LUB of the return types
1016 // we saw and assigning it to the expected return type. This isn't
1017 // really expected to fail, since the coercions would have failed
1018 // earlier when trying to find a LUB.
1020 // However, the behavior around `!` is sort of complex. In the
1021 // event that the `actual_return_ty` comes back as `!`, that
1022 // indicates that the fn either does not return or "returns" only
1023 // values of type `!`. In this case, if there is an expected
1024 // return type that is *not* `!`, that should be ok. But if the
1025 // return type is being inferred, we want to "fallback" to `!`:
1027 // let x = move || panic!();
1029 // To allow for that, I am creating a type variable with diverging
1030 // fallback. This was deemed ever so slightly better than unifying
1031 // the return value with `!` because it allows for the caller to
1032 // make more assumptions about the return type (e.g., they could do
1034 // let y: Option<u32> = Some(x());
1036 // which would then cause this return type to become `u32`, not
1038 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
1039 let mut actual_return_ty = coercion.complete(&fcx);
1040 if actual_return_ty.is_never() {
1041 actual_return_ty = fcx.next_diverging_ty_var(
1042 TypeVariableOrigin::DivergingFn(body.value.span));
1044 fcx.demand_suptype(body.value.span, ret_ty, actual_return_ty);
1049 fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1052 let def_id = tcx.hir.local_def_id(id);
1053 let def = tcx.adt_def(def_id);
1054 def.destructor(tcx); // force the destructor to be evaluated
1055 check_representable(tcx, span, def_id);
1057 if def.repr.simd() {
1058 check_simd(tcx, span, def_id);
1061 // if struct is packed and not aligned, check fields for alignment.
1062 // Checks for combining packed and align attrs on single struct are done elsewhere.
1063 if tcx.adt_def(def_id).repr.packed() && tcx.adt_def(def_id).repr.align == 0 {
1064 check_packed(tcx, span, def_id);
1068 fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1071 let def_id = tcx.hir.local_def_id(id);
1072 let def = tcx.adt_def(def_id);
1073 def.destructor(tcx); // force the destructor to be evaluated
1074 check_representable(tcx, span, def_id);
1077 pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
1078 debug!("check_item_type(it.id={}, it.name={})",
1080 tcx.item_path_str(tcx.hir.local_def_id(it.id)));
1081 let _indenter = indenter();
1083 // Consts can play a role in type-checking, so they are included here.
1084 hir::ItemStatic(..) |
1085 hir::ItemConst(..) => {
1086 tcx.typeck_tables_of(tcx.hir.local_def_id(it.id));
1088 hir::ItemEnum(ref enum_definition, _) => {
1091 &enum_definition.variants,
1094 hir::ItemFn(..) => {} // entirely within check_item_body
1095 hir::ItemImpl(.., ref impl_item_refs) => {
1096 debug!("ItemImpl {} with id {}", it.name, it.id);
1097 let impl_def_id = tcx.hir.local_def_id(it.id);
1098 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1099 check_impl_items_against_trait(tcx,
1104 let trait_def_id = impl_trait_ref.def_id;
1105 check_on_unimplemented(tcx, trait_def_id, it);
1108 hir::ItemTrait(..) => {
1109 let def_id = tcx.hir.local_def_id(it.id);
1110 check_on_unimplemented(tcx, def_id, it);
1112 hir::ItemStruct(..) => {
1113 check_struct(tcx, it.id, it.span);
1115 hir::ItemUnion(..) => {
1116 check_union(tcx, it.id, it.span);
1118 hir::ItemTy(_, ref generics) => {
1119 let def_id = tcx.hir.local_def_id(it.id);
1120 let pty_ty = tcx.type_of(def_id);
1121 check_bounds_are_used(tcx, generics, pty_ty);
1123 hir::ItemForeignMod(ref m) => {
1124 check_abi(tcx, it.span, m.abi);
1126 if m.abi == Abi::RustIntrinsic {
1127 for item in &m.items {
1128 intrinsic::check_intrinsic_type(tcx, item);
1130 } else if m.abi == Abi::PlatformIntrinsic {
1131 for item in &m.items {
1132 intrinsic::check_platform_intrinsic_type(tcx, item);
1135 for item in &m.items {
1136 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
1137 if !generics.types.is_empty() {
1138 let mut err = struct_span_err!(tcx.sess, item.span, E0044,
1139 "foreign items may not have type parameters");
1140 span_help!(&mut err, item.span,
1141 "consider using specialization instead of \
1146 if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
1147 require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
1152 _ => {/* nothing to do */ }
1156 fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1159 let generics = tcx.generics_of(def_id);
1160 if let Some(ref attr) = item.attrs.iter().find(|a| {
1161 a.check_name("rustc_on_unimplemented")
1163 if let Some(istring) = attr.value_str() {
1164 let istring = istring.as_str();
1165 let parser = Parser::new(&istring);
1166 let types = &generics.types;
1167 for token in parser {
1169 Piece::String(_) => (), // Normal string, no need to check it
1170 Piece::NextArgument(a) => match a.position {
1171 // `{Self}` is allowed
1172 Position::ArgumentNamed(s) if s == "Self" => (),
1173 // So is `{A}` if A is a type parameter
1174 Position::ArgumentNamed(s) => match types.iter().find(|t| {
1179 let name = tcx.item_name(def_id);
1180 span_err!(tcx.sess, attr.span, E0230,
1181 "there is no type parameter \
1186 // `{:1}` and `{}` are not to be used
1187 Position::ArgumentIs(_) => {
1188 span_err!(tcx.sess, attr.span, E0231,
1189 "only named substitution \
1190 parameters are allowed");
1197 tcx.sess, attr.span, E0232,
1198 "this attribute must have a value")
1199 .span_label(attr.span, "attribute requires a value")
1200 .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
1206 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1207 impl_item: &hir::ImplItem,
1210 let mut err = struct_span_err!(
1211 tcx.sess, impl_item.span, E0520,
1212 "`{}` specializes an item from a parent `impl`, but \
1213 that item is not marked `default`",
1215 err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
1218 match tcx.span_of_impl(parent_impl) {
1220 err.span_label(span, "parent `impl` is here");
1221 err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
1225 err.note(&format!("parent implementation is in crate `{}`", cname));
1232 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1233 trait_def: &ty::TraitDef,
1235 impl_item: &hir::ImplItem)
1237 let ancestors = trait_def.ancestors(tcx, impl_id);
1239 let kind = match impl_item.node {
1240 hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
1241 hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
1242 hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
1244 let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
1245 .map(|node_item| node_item.map(|parent| parent.defaultness));
1247 if let Some(parent) = parent {
1248 if tcx.impl_item_is_final(&parent) {
1249 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1255 fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1258 impl_trait_ref: ty::TraitRef<'tcx>,
1259 impl_item_refs: &[hir::ImplItemRef]) {
1260 // If the trait reference itself is erroneous (so the compilation is going
1261 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1262 // isn't populated for such impls.
1263 if impl_trait_ref.references_error() { return; }
1265 // Locate trait definition and items
1266 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1267 let mut overridden_associated_type = None;
1269 let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
1271 // Check existing impl methods to see if they are both present in trait
1272 // and compatible with trait signature
1273 for impl_item in impl_items() {
1274 let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
1275 let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
1276 .find(|ac| ac.name == ty_impl_item.name);
1278 // Check that impl definition matches trait definition
1279 if let Some(ty_trait_item) = ty_trait_item {
1280 match impl_item.node {
1281 hir::ImplItemKind::Const(..) => {
1282 // Find associated const definition.
1283 if ty_trait_item.kind == ty::AssociatedKind::Const {
1284 compare_const_impl(tcx,
1290 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1291 "item `{}` is an associated const, \
1292 which doesn't match its trait `{}`",
1295 err.span_label(impl_item.span, "does not match trait");
1296 // We can only get the spans from local trait definition
1297 // Same for E0324 and E0325
1298 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1299 err.span_label(trait_span, "item in trait");
1304 hir::ImplItemKind::Method(..) => {
1305 let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
1306 if ty_trait_item.kind == ty::AssociatedKind::Method {
1307 let err_count = tcx.sess.err_count();
1308 compare_impl_method(tcx,
1314 true); // start with old-broken-mode
1315 if err_count == tcx.sess.err_count() {
1316 // old broken mode did not report an error. Try with the new mode.
1317 compare_impl_method(tcx,
1323 false); // use the new mode
1326 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1327 "item `{}` is an associated method, \
1328 which doesn't match its trait `{}`",
1331 err.span_label(impl_item.span, "does not match trait");
1332 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1333 err.span_label(trait_span, "item in trait");
1338 hir::ImplItemKind::Type(_) => {
1339 if ty_trait_item.kind == ty::AssociatedKind::Type {
1340 if ty_trait_item.defaultness.has_value() {
1341 overridden_associated_type = Some(impl_item);
1344 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1345 "item `{}` is an associated type, \
1346 which doesn't match its trait `{}`",
1349 err.span_label(impl_item.span, "does not match trait");
1350 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1351 err.span_label(trait_span, "item in trait");
1359 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1362 // Check for missing items from trait
1363 let mut missing_items = Vec::new();
1364 let mut invalidated_items = Vec::new();
1365 let associated_type_overridden = overridden_associated_type.is_some();
1366 for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
1367 let is_implemented = trait_def.ancestors(tcx, impl_id)
1368 .defs(tcx, trait_item.name, trait_item.kind)
1370 .map(|node_item| !node_item.node.is_from_trait())
1373 if !is_implemented {
1374 if !trait_item.defaultness.has_value() {
1375 missing_items.push(trait_item);
1376 } else if associated_type_overridden {
1377 invalidated_items.push(trait_item.name);
1382 if !missing_items.is_empty() {
1383 let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
1384 "not all trait items implemented, missing: `{}`",
1385 missing_items.iter()
1386 .map(|trait_item| trait_item.name.to_string())
1387 .collect::<Vec<_>>().join("`, `"));
1388 err.span_label(impl_span, format!("missing `{}` in implementation",
1389 missing_items.iter()
1390 .map(|trait_item| trait_item.name.to_string())
1391 .collect::<Vec<_>>().join("`, `")));
1392 for trait_item in missing_items {
1393 if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
1394 err.span_label(span, format!("`{}` from trait", trait_item.name));
1396 err.note_trait_signature(trait_item.name.to_string(),
1397 trait_item.signature(&tcx));
1403 if !invalidated_items.is_empty() {
1404 let invalidator = overridden_associated_type.unwrap();
1405 span_err!(tcx.sess, invalidator.span, E0399,
1406 "the following trait items need to be reimplemented \
1407 as `{}` was overridden: `{}`",
1409 invalidated_items.iter()
1410 .map(|name| name.to_string())
1411 .collect::<Vec<_>>().join("`, `"))
1415 /// Checks whether a type can be represented in memory. In particular, it
1416 /// identifies types that contain themselves without indirection through a
1417 /// pointer, which would mean their size is unbounded.
1418 fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1422 let rty = tcx.type_of(item_def_id);
1424 // Check that it is possible to represent this type. This call identifies
1425 // (1) types that contain themselves and (2) types that contain a different
1426 // recursive type. It is only necessary to throw an error on those that
1427 // contain themselves. For case 2, there must be an inner type that will be
1428 // caught by case 1.
1429 match rty.is_representable(tcx, sp) {
1430 Representability::SelfRecursive(spans) => {
1431 let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
1433 err.span_label(span, "recursive without indirection");
1438 Representability::Representable | Representability::ContainsRecursive => (),
1443 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1444 let t = tcx.type_of(def_id);
1446 ty::TyAdt(def, substs) if def.is_struct() => {
1447 let fields = &def.struct_variant().fields;
1448 if fields.is_empty() {
1449 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1452 let e = fields[0].ty(tcx, substs);
1453 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1454 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1455 .span_label(sp, "SIMD elements must have the same type")
1460 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1461 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1463 span_err!(tcx.sess, sp, E0077,
1464 "SIMD vector element type should be machine type");
1473 fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1474 if check_packed_inner(tcx, def_id, &mut Vec::new()) {
1475 struct_span_err!(tcx.sess, sp, E0588,
1476 "packed struct cannot transitively contain a `[repr(align)]` struct").emit();
1480 fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1482 stack: &mut Vec<DefId>) -> bool {
1483 let t = tcx.type_of(def_id);
1484 if stack.contains(&def_id) {
1485 debug!("check_packed_inner: {:?} is recursive", t);
1489 ty::TyAdt(def, substs) if def.is_struct() => {
1490 if tcx.adt_def(def.did).repr.align > 0 {
1493 // push struct def_id before checking fields
1495 for field in &def.struct_variant().fields {
1496 let f = field.ty(tcx, substs);
1498 ty::TyAdt(def, _) => {
1499 if check_packed_inner(tcx, def.did, stack) {
1506 // only need to pop if not early out
1514 #[allow(trivial_numeric_casts)]
1515 pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1517 vs: &'tcx [hir::Variant],
1519 let def_id = tcx.hir.local_def_id(id);
1520 let def = tcx.adt_def(def_id);
1521 def.destructor(tcx); // force the destructor to be evaluated
1523 if vs.is_empty() && tcx.has_attr(def_id, "repr") {
1525 tcx.sess, sp, E0084,
1526 "unsupported representation for zero-variant enum")
1527 .span_label(sp, "unsupported enum representation")
1531 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1532 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1533 if !tcx.sess.features.borrow().i128_type {
1534 emit_feature_err(&tcx.sess.parse_sess,
1535 "i128_type", sp, GateIssue::Language, "128-bit type is unstable");
1540 if let Some(e) = v.node.disr_expr {
1541 tcx.typeck_tables_of(tcx.hir.local_def_id(e.node_id));
1545 let mut disr_vals: Vec<ConstInt> = Vec::new();
1546 for (discr, v) in def.discriminants(tcx).zip(vs) {
1547 // Check for duplicate discriminant values
1548 if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
1549 let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
1550 let variant_i = tcx.hir.expect_variant(variant_i_node_id);
1551 let i_span = match variant_i.node.disr_expr {
1552 Some(expr) => tcx.hir.span(expr.node_id),
1553 None => tcx.hir.span(variant_i_node_id)
1555 let span = match v.node.disr_expr {
1556 Some(expr) => tcx.hir.span(expr.node_id),
1559 struct_span_err!(tcx.sess, span, E0081,
1560 "discriminant value `{}` already exists", disr_vals[i])
1561 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1562 .span_label(span , format!("enum already has `{}`", disr_vals[i]))
1565 disr_vals.push(discr);
1568 check_representable(tcx, sp, def_id);
1571 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1572 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1574 fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
1575 -> ty::GenericPredicates<'tcx>
1578 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1579 let item_id = tcx.hir.ty_param_owner(node_id);
1580 let item_def_id = tcx.hir.local_def_id(item_id);
1581 let generics = tcx.generics_of(item_def_id);
1582 let index = generics.type_param_to_index[&def_id.index];
1583 ty::GenericPredicates {
1585 predicates: self.param_env.caller_bounds.iter().filter(|predicate| {
1587 ty::Predicate::Trait(ref data) => {
1588 data.0.self_ty().is_param(index)
1592 }).cloned().collect()
1596 fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
1597 -> Option<ty::Region<'tcx>> {
1599 Some(def) => infer::EarlyBoundRegion(span, def.name, def.issue_32330),
1600 None => infer::MiscVariable(span)
1602 Some(self.next_region_var(v))
1605 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
1606 self.next_ty_var(TypeVariableOrigin::TypeInference(span))
1609 fn ty_infer_for_def(&self,
1610 ty_param_def: &ty::TypeParameterDef,
1611 substs: &[Kind<'tcx>],
1612 span: Span) -> Ty<'tcx> {
1613 self.type_var_for_def(span, ty_param_def, substs)
1616 fn projected_ty_from_poly_trait_ref(&self,
1618 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1619 item_name: ast::Name)
1622 let (trait_ref, _) =
1623 self.replace_late_bound_regions_with_fresh_var(
1625 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1628 self.tcx().mk_projection(trait_ref, item_name)
1631 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1632 if ty.has_escaping_regions() {
1633 ty // FIXME: normalization and escaping regions
1635 self.normalize_associated_types_in(span, &ty)
1639 fn set_tainted_by_errors(&self) {
1640 self.infcx.set_tainted_by_errors()
1644 /// Controls whether the arguments are tupled. This is used for the call
1647 /// Tupling means that all call-side arguments are packed into a tuple and
1648 /// passed as a single parameter. For example, if tupling is enabled, this
1651 /// fn f(x: (isize, isize))
1653 /// Can be called as:
1660 #[derive(Clone, Eq, PartialEq)]
1661 enum TupleArgumentsFlag {
1666 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1667 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1668 param_env: ty::ParamEnv<'tcx>,
1669 body_id: ast::NodeId)
1670 -> FnCtxt<'a, 'gcx, 'tcx> {
1674 err_count_on_creation: inh.tcx.sess.err_count(),
1676 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
1677 ast::CRATE_NODE_ID)),
1678 diverges: Cell::new(Diverges::Maybe),
1679 has_errors: Cell::new(false),
1680 enclosing_breakables: RefCell::new(EnclosingBreakables {
1688 pub fn sess(&self) -> &Session {
1692 pub fn err_count_since_creation(&self) -> usize {
1693 self.tcx.sess.err_count() - self.err_count_on_creation
1696 /// Produce warning on the given node, if the current point in the
1697 /// function is unreachable, and there hasn't been another warning.
1698 fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
1699 if self.diverges.get() == Diverges::Always {
1700 self.diverges.set(Diverges::WarnedAlways);
1702 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
1704 self.tables.borrow_mut().lints.add_lint(
1705 lint::builtin::UNREACHABLE_CODE,
1707 format!("unreachable {}", kind));
1713 code: ObligationCauseCode<'tcx>)
1714 -> ObligationCause<'tcx> {
1715 ObligationCause::new(span, self.body_id, code)
1718 pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
1719 self.cause(span, ObligationCauseCode::MiscObligation)
1722 /// Resolves type variables in `ty` if possible. Unlike the infcx
1723 /// version (resolve_type_vars_if_possible), this version will
1724 /// also select obligations if it seems useful, in an effort
1725 /// to get more type information.
1726 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1727 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1729 // No TyInfer()? Nothing needs doing.
1730 if !ty.has_infer_types() {
1731 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1735 // If `ty` is a type variable, see whether we already know what it is.
1736 ty = self.resolve_type_vars_if_possible(&ty);
1737 if !ty.has_infer_types() {
1738 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1742 // If not, try resolving pending obligations as much as
1743 // possible. This can help substantially when there are
1744 // indirect dependencies that don't seem worth tracking
1746 self.select_obligations_where_possible();
1747 ty = self.resolve_type_vars_if_possible(&ty);
1749 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1753 fn record_deferred_call_resolution(&self,
1754 closure_def_id: DefId,
1755 r: DeferredCallResolution<'gcx, 'tcx>) {
1756 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1757 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1760 fn remove_deferred_call_resolutions(&self,
1761 closure_def_id: DefId)
1762 -> Vec<DeferredCallResolution<'gcx, 'tcx>>
1764 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1765 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![])
1768 pub fn tag(&self) -> String {
1769 let self_ptr: *const FnCtxt = self;
1770 format!("{:?}", self_ptr)
1773 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1774 match self.locals.borrow().get(&nid) {
1777 span_bug!(span, "no type for local variable {}",
1778 self.tcx.hir.node_to_string(nid));
1784 pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
1785 debug!("write_ty({}, {:?}) in fcx {}",
1786 node_id, self.resolve_type_vars_if_possible(&ty), self.tag());
1787 self.tables.borrow_mut().node_types.insert(node_id, ty);
1789 if ty.references_error() {
1790 self.has_errors.set(true);
1791 self.set_tainted_by_errors();
1795 pub fn write_method_call(&self, node_id: ast::NodeId, method: MethodCallee<'tcx>) {
1796 self.tables.borrow_mut().type_dependent_defs.insert(node_id, Def::Method(method.def_id));
1797 self.write_substs(node_id, method.substs);
1800 pub fn write_substs(&self, node_id: ast::NodeId, substs: &'tcx Substs<'tcx>) {
1801 if !substs.is_noop() {
1802 debug!("write_substs({}, {:?}) in fcx {}",
1807 self.tables.borrow_mut().node_substs.insert(node_id, substs);
1811 pub fn apply_adjustments(&self, expr: &hir::Expr, adj: Vec<Adjustment<'tcx>>) {
1812 debug!("apply_adjustments(expr={:?}, adj={:?})", expr, adj);
1818 match self.tables.borrow_mut().adjustments.entry(expr.id) {
1819 Entry::Vacant(entry) => { entry.insert(adj); },
1820 Entry::Occupied(mut entry) => {
1821 debug!(" - composing on top of {:?}", entry.get());
1822 match (&entry.get()[..], &adj[..]) {
1823 // Applying any adjustment on top of a NeverToAny
1824 // is a valid NeverToAny adjustment, because it can't
1826 (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return,
1828 Adjustment { kind: Adjust::Deref(_), .. },
1829 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
1831 Adjustment { kind: Adjust::Deref(_), .. },
1832 .. // Any following adjustments are allowed.
1834 // A reborrow has no effect before a dereference.
1836 // FIXME: currently we never try to compose autoderefs
1837 // and ReifyFnPointer/UnsafeFnPointer, but we could.
1839 bug!("while adjusting {:?}, can't compose {:?} and {:?}",
1840 expr, entry.get(), adj)
1842 *entry.get_mut() = adj;
1847 /// Basically whenever we are converting from a type scheme into
1848 /// the fn body space, we always want to normalize associated
1849 /// types as well. This function combines the two.
1850 fn instantiate_type_scheme<T>(&self,
1852 substs: &Substs<'tcx>,
1855 where T : TypeFoldable<'tcx>
1857 let value = value.subst(self.tcx, substs);
1858 let result = self.normalize_associated_types_in(span, &value);
1859 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1866 /// As `instantiate_type_scheme`, but for the bounds found in a
1867 /// generic type scheme.
1868 fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
1869 -> ty::InstantiatedPredicates<'tcx> {
1870 let bounds = self.tcx.predicates_of(def_id);
1871 let result = bounds.instantiate(self.tcx, substs);
1872 let result = self.normalize_associated_types_in(span, &result);
1873 debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
1880 /// Replace all anonymized types with fresh inference variables
1881 /// and record them for writeback.
1882 fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
1883 value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
1884 if let ty::TyAnon(def_id, substs) = ty.sty {
1885 // Use the same type variable if the exact same TyAnon appears more
1886 // than once in the return type (e.g. if it's pased to a type alias).
1887 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1888 if let Some(ty_var) = self.anon_types.borrow().get(&id) {
1891 let span = self.tcx.def_span(def_id);
1892 let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
1893 self.anon_types.borrow_mut().insert(id, ty_var);
1895 let predicates_of = self.tcx.predicates_of(def_id);
1896 let bounds = predicates_of.instantiate(self.tcx, substs);
1898 for predicate in bounds.predicates {
1899 // Change the predicate to refer to the type variable,
1900 // which will be the concrete type, instead of the TyAnon.
1901 // This also instantiates nested `impl Trait`.
1902 let predicate = self.instantiate_anon_types(&predicate);
1904 // Require that the predicate holds for the concrete type.
1905 let cause = traits::ObligationCause::new(span, self.body_id,
1906 traits::ReturnType);
1907 self.register_predicate(traits::Obligation::new(cause,
1919 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1920 where T : TypeFoldable<'tcx>
1922 self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value)
1925 fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T)
1927 where T : TypeFoldable<'tcx>
1929 self.inh.normalize_associated_types_in_as_infer_ok(span,
1935 pub fn require_type_meets(&self,
1938 code: traits::ObligationCauseCode<'tcx>,
1941 self.register_bound(
1944 traits::ObligationCause::new(span, self.body_id, code));
1947 pub fn require_type_is_sized(&self,
1950 code: traits::ObligationCauseCode<'tcx>)
1952 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1953 self.require_type_meets(ty, span, code, lang_item);
1956 pub fn register_bound(&self,
1959 cause: traits::ObligationCause<'tcx>)
1961 self.fulfillment_cx.borrow_mut()
1962 .register_bound(self, self.param_env, ty, def_id, cause);
1965 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
1966 let t = AstConv::ast_ty_to_ty(self, ast_t);
1967 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1971 pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
1972 match self.tables.borrow().node_types.get(&id) {
1974 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1976 bug!("no type for node {}: {} in fcx {}",
1977 id, self.tcx.hir.node_to_string(id),
1983 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1984 /// outlive the region `r`.
1985 pub fn register_region_obligation(&self,
1987 region: ty::Region<'tcx>,
1988 cause: traits::ObligationCause<'tcx>)
1990 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
1991 fulfillment_cx.register_region_obligation(ty, region, cause);
1994 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1995 /// outlive the region `r`.
1996 pub fn register_wf_obligation(&self,
1999 code: traits::ObligationCauseCode<'tcx>)
2001 // WF obligations never themselves fail, so no real need to give a detailed cause:
2002 let cause = traits::ObligationCause::new(span, self.body_id, code);
2003 self.register_predicate(traits::Obligation::new(cause,
2005 ty::Predicate::WellFormed(ty)));
2008 pub fn register_old_wf_obligation(&self,
2011 code: traits::ObligationCauseCode<'tcx>)
2013 // Registers an "old-style" WF obligation that uses the
2014 // implicator code. This is basically a buggy version of
2015 // `register_wf_obligation` that is being kept around
2016 // temporarily just to help with phasing in the newer rules.
2018 // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
2019 let cause = traits::ObligationCause::new(span, self.body_id, code);
2020 self.register_region_obligation(ty, self.tcx.types.re_empty, cause);
2023 /// Registers obligations that all types appearing in `substs` are well-formed.
2024 pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
2026 for ty in substs.types() {
2027 self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
2031 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
2032 /// type/region parameter was instantiated (`substs`), creates and registers suitable
2033 /// trait/region obligations.
2035 /// For example, if there is a function:
2038 /// fn foo<'a,T:'a>(...)
2041 /// and a reference:
2047 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
2048 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
2049 pub fn add_obligations_for_parameters(&self,
2050 cause: traits::ObligationCause<'tcx>,
2051 predicates: &ty::InstantiatedPredicates<'tcx>)
2053 assert!(!predicates.has_escaping_regions());
2055 debug!("add_obligations_for_parameters(predicates={:?})",
2058 for obligation in traits::predicates_for_generics(cause, self.param_env, predicates) {
2059 self.register_predicate(obligation);
2063 // FIXME(arielb1): use this instead of field.ty everywhere
2064 // Only for fields! Returns <none> for methods>
2065 // Indifferent to privacy flags
2066 pub fn field_ty(&self,
2068 field: &'tcx ty::FieldDef,
2069 substs: &Substs<'tcx>)
2072 self.normalize_associated_types_in(span,
2073 &field.ty(self.tcx, substs))
2076 fn check_casts(&self) {
2077 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
2078 for cast in deferred_cast_checks.drain(..) {
2083 /// Apply "fallbacks" to some types
2084 /// unconstrained types get replaced with ! or () (depending on whether
2085 /// feature(never_type) is enabled), unconstrained ints with i32, and
2086 /// unconstrained floats with f64.
2087 fn default_type_parameters(&self) {
2088 use rustc::ty::error::UnconstrainedNumeric::Neither;
2089 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
2091 // Defaulting inference variables becomes very dubious if we have
2092 // encountered type-checking errors. Therefore, if we think we saw
2093 // some errors in this function, just resolve all uninstanted type
2094 // varibles to TyError.
2095 if self.is_tainted_by_errors() {
2096 for ty in &self.unsolved_variables() {
2097 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
2098 debug!("default_type_parameters: defaulting `{:?}` to error", ty);
2099 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
2105 for ty in &self.unsolved_variables() {
2106 let resolved = self.resolve_type_vars_if_possible(ty);
2107 if self.type_var_diverges(resolved) {
2108 debug!("default_type_parameters: defaulting `{:?}` to `!` because it diverges",
2110 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
2111 self.tcx.mk_diverging_default());
2113 match self.type_is_unconstrained_numeric(resolved) {
2114 UnconstrainedInt => {
2115 debug!("default_type_parameters: defaulting `{:?}` to `i32`",
2117 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
2119 UnconstrainedFloat => {
2120 debug!("default_type_parameters: defaulting `{:?}` to `f32`",
2122 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
2130 // Implements type inference fallback algorithm
2131 fn select_all_obligations_and_apply_defaults(&self) {
2132 self.select_obligations_where_possible();
2133 self.default_type_parameters();
2134 self.select_obligations_where_possible();
2137 fn select_all_obligations_or_error(&self) {
2138 debug!("select_all_obligations_or_error");
2140 // upvar inference should have ensured that all deferred call
2141 // resolutions are handled by now.
2142 assert!(self.deferred_call_resolutions.borrow().is_empty());
2144 self.select_all_obligations_and_apply_defaults();
2146 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2148 match fulfillment_cx.select_all_or_error(self) {
2150 Err(errors) => { self.report_fulfillment_errors(&errors); }
2154 /// Select as many obligations as we can at present.
2155 fn select_obligations_where_possible(&self) {
2156 match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
2158 Err(errors) => { self.report_fulfillment_errors(&errors); }
2162 /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2163 /// returns a type of `&T`, but the actual type we assign to the
2164 /// *expression* is `T`. So this function just peels off the return
2165 /// type by one layer to yield `T`.
2166 fn make_overloaded_lvalue_return_type(&self,
2167 method: MethodCallee<'tcx>)
2168 -> ty::TypeAndMut<'tcx>
2170 // extract method return type, which will be &T;
2171 // all LB regions should have been instantiated during method lookup
2172 let ret_ty = method.sig.output();
2174 // method returns &T, but the type as visible to user is T, so deref
2175 ret_ty.builtin_deref(true, NoPreference).unwrap()
2178 fn lookup_indexing(&self,
2180 base_expr: &'gcx hir::Expr,
2183 lvalue_pref: LvaluePreference)
2184 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2186 // FIXME(#18741) -- this is almost but not quite the same as the
2187 // autoderef that normal method probing does. They could likely be
2190 let mut autoderef = self.autoderef(base_expr.span, base_ty);
2191 let mut result = None;
2192 while result.is_none() && autoderef.next().is_some() {
2193 result = self.try_index_step(expr, base_expr, &autoderef, lvalue_pref, idx_ty);
2195 autoderef.finalize();
2199 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2200 /// (and otherwise adjust) `base_expr`, looking for a type which either
2201 /// supports builtin indexing or overloaded indexing.
2202 /// This loop implements one step in that search; the autoderef loop
2203 /// is implemented by `lookup_indexing`.
2204 fn try_index_step(&self,
2206 base_expr: &hir::Expr,
2207 autoderef: &Autoderef<'a, 'gcx, 'tcx>,
2208 lvalue_pref: LvaluePreference,
2210 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2212 let adjusted_ty = autoderef.unambiguous_final_ty();
2213 debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
2221 // First, try built-in indexing.
2222 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2223 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2224 debug!("try_index_step: success, using built-in indexing");
2225 let adjustments = autoderef.adjust_steps(lvalue_pref);
2226 self.apply_adjustments(base_expr, adjustments);
2227 return Some((self.tcx.types.usize, ty));
2232 for &unsize in &[false, true] {
2233 let mut self_ty = adjusted_ty;
2235 // We only unsize arrays here.
2236 if let ty::TyArray(element_ty, _) = adjusted_ty.sty {
2237 self_ty = self.tcx.mk_slice(element_ty);
2243 // If some lookup succeeds, write callee into table and extract index/element
2244 // type from the method signature.
2245 // If some lookup succeeded, install method in table
2246 let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_expr.span));
2247 let method = self.try_overloaded_lvalue_op(
2248 expr.span, self_ty, &[input_ty], lvalue_pref, LvalueOp::Index);
2250 let result = method.map(|ok| {
2251 debug!("try_index_step: success, using overloaded indexing");
2252 let method = self.register_infer_ok_obligations(ok);
2254 let mut adjustments = autoderef.adjust_steps(lvalue_pref);
2255 if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
2256 adjustments.push(Adjustment {
2257 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
2258 target: self.tcx.mk_ref(region, ty::TypeAndMut {
2265 adjustments.push(Adjustment {
2266 kind: Adjust::Unsize,
2267 target: method.sig.inputs()[0]
2270 self.apply_adjustments(base_expr, adjustments);
2272 self.write_method_call(expr.id, method);
2273 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2275 if result.is_some() {
2283 fn resolve_lvalue_op(&self, op: LvalueOp, is_mut: bool) -> (Option<DefId>, Symbol) {
2284 let (tr, name) = match (op, is_mut) {
2285 (LvalueOp::Deref, false) =>
2286 (self.tcx.lang_items.deref_trait(), "deref"),
2287 (LvalueOp::Deref, true) =>
2288 (self.tcx.lang_items.deref_mut_trait(), "deref_mut"),
2289 (LvalueOp::Index, false) =>
2290 (self.tcx.lang_items.index_trait(), "index"),
2291 (LvalueOp::Index, true) =>
2292 (self.tcx.lang_items.index_mut_trait(), "index_mut"),
2294 (tr, Symbol::intern(name))
2297 fn try_overloaded_lvalue_op(&self,
2300 arg_tys: &[Ty<'tcx>],
2301 lvalue_pref: LvaluePreference,
2303 -> Option<InferOk<'tcx, MethodCallee<'tcx>>>
2305 debug!("try_overloaded_lvalue_op({:?},{:?},{:?},{:?})",
2311 // Try Mut first, if preferred.
2312 let (mut_tr, mut_op) = self.resolve_lvalue_op(op, true);
2313 let method = match (lvalue_pref, mut_tr) {
2314 (PreferMutLvalue, Some(trait_did)) => {
2315 self.lookup_method_in_trait(span, mut_op, trait_did, base_ty, Some(arg_tys))
2320 // Otherwise, fall back to the immutable version.
2321 let (imm_tr, imm_op) = self.resolve_lvalue_op(op, false);
2322 let method = match (method, imm_tr) {
2323 (None, Some(trait_did)) => {
2324 self.lookup_method_in_trait(span, imm_op, trait_did, base_ty, Some(arg_tys))
2326 (method, _) => method,
2332 fn check_method_argument_types(&self,
2334 method: Result<MethodCallee<'tcx>, ()>,
2335 args_no_rcvr: &'gcx [hir::Expr],
2336 tuple_arguments: TupleArgumentsFlag,
2337 expected: Expectation<'tcx>)
2339 let has_error = match method {
2341 method.substs.references_error() || method.sig.references_error()
2346 let err_inputs = self.err_args(args_no_rcvr.len());
2348 let err_inputs = match tuple_arguments {
2349 DontTupleArguments => err_inputs,
2350 TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
2353 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2354 false, tuple_arguments, None);
2355 return self.tcx.types.err;
2358 let method = method.unwrap();
2359 // HACK(eddyb) ignore self in the definition (see above).
2360 let expected_arg_tys = self.expected_inputs_for_expected_output(
2363 method.sig.output(),
2364 &method.sig.inputs()[1..]
2366 self.check_argument_types(sp, &method.sig.inputs()[1..], &expected_arg_tys[..],
2367 args_no_rcvr, method.sig.variadic, tuple_arguments,
2368 self.tcx.hir.span_if_local(method.def_id));
2372 /// Generic function that factors out common logic from function calls,
2373 /// method calls and overloaded operators.
2374 fn check_argument_types(&self,
2376 fn_inputs: &[Ty<'tcx>],
2377 expected_arg_tys: &[Ty<'tcx>],
2378 args: &'gcx [hir::Expr],
2380 tuple_arguments: TupleArgumentsFlag,
2381 def_span: Option<Span>) {
2384 // Grab the argument types, supplying fresh type variables
2385 // if the wrong number of arguments were supplied
2386 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2392 // All the input types from the fn signature must outlive the call
2393 // so as to validate implied bounds.
2394 for &fn_input_ty in fn_inputs {
2395 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2398 let mut expected_arg_tys = expected_arg_tys;
2399 let expected_arg_count = fn_inputs.len();
2401 let sp_args = if args.len() > 0 {
2402 let (first, args) = args.split_at(1);
2403 let mut sp_tmp = first[0].span;
2405 let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
2406 if ! sp_opt.is_some() {
2409 sp_tmp = sp_opt.unwrap();
2416 fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
2417 arg_count: usize, error_code: &str, variadic: bool,
2418 def_span: Option<Span>) {
2419 let mut err = sess.struct_span_err_with_code(sp,
2420 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2421 if variadic {"at least "} else {""},
2423 if expected_count == 1 {""} else {"s"},
2425 if arg_count == 1 {" was"} else {"s were"}),
2428 err.span_label(sp, format!("expected {}{} parameter{}",
2429 if variadic {"at least "} else {""},
2431 if expected_count == 1 {""} else {"s"}));
2432 if let Some(def_s) = def_span {
2433 err.span_label(def_s, "defined here");
2438 let formal_tys = if tuple_arguments == TupleArguments {
2439 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2440 match tuple_type.sty {
2441 ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
2442 parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
2443 "E0057", false, def_span);
2444 expected_arg_tys = &[];
2445 self.err_args(args.len())
2447 ty::TyTuple(arg_types, _) => {
2448 expected_arg_tys = match expected_arg_tys.get(0) {
2449 Some(&ty) => match ty.sty {
2450 ty::TyTuple(ref tys, _) => &tys,
2458 span_err!(tcx.sess, sp, E0059,
2459 "cannot use call notation; the first type parameter \
2460 for the function trait is neither a tuple nor unit");
2461 expected_arg_tys = &[];
2462 self.err_args(args.len())
2465 } else if expected_arg_count == supplied_arg_count {
2467 } else if variadic {
2468 if supplied_arg_count >= expected_arg_count {
2471 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2472 supplied_arg_count, "E0060", true, def_span);
2473 expected_arg_tys = &[];
2474 self.err_args(supplied_arg_count)
2477 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2478 supplied_arg_count, "E0061", false, def_span);
2479 expected_arg_tys = &[];
2480 self.err_args(supplied_arg_count)
2483 debug!("check_argument_types: formal_tys={:?}",
2484 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2486 // Check the arguments.
2487 // We do this in a pretty awful way: first we typecheck any arguments
2488 // that are not closures, then we typecheck the closures. This is so
2489 // that we have more information about the types of arguments when we
2490 // typecheck the functions. This isn't really the right way to do this.
2491 for &check_closures in &[false, true] {
2492 debug!("check_closures={}", check_closures);
2494 // More awful hacks: before we check argument types, try to do
2495 // an "opportunistic" vtable resolution of any trait bounds on
2496 // the call. This helps coercions.
2498 self.select_obligations_where_possible();
2501 // For variadic functions, we don't have a declared type for all of
2502 // the arguments hence we only do our usual type checking with
2503 // the arguments who's types we do know.
2504 let t = if variadic {
2506 } else if tuple_arguments == TupleArguments {
2511 for (i, arg) in args.iter().take(t).enumerate() {
2512 // Warn only for the first loop (the "no closures" one).
2513 // Closure arguments themselves can't be diverging, but
2514 // a previous argument can, e.g. `foo(panic!(), || {})`.
2515 if !check_closures {
2516 self.warn_if_unreachable(arg.id, arg.span, "expression");
2519 let is_closure = match arg.node {
2520 hir::ExprClosure(..) => true,
2524 if is_closure != check_closures {
2528 debug!("checking the argument");
2529 let formal_ty = formal_tys[i];
2531 // The special-cased logic below has three functions:
2532 // 1. Provide as good of an expected type as possible.
2533 let expected = expected_arg_tys.get(i).map(|&ty| {
2534 Expectation::rvalue_hint(self, ty)
2537 let checked_ty = self.check_expr_with_expectation(
2539 expected.unwrap_or(ExpectHasType(formal_ty)));
2541 // 2. Coerce to the most detailed type that could be coerced
2542 // to, which is `expected_ty` if `rvalue_hint` returns an
2543 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2544 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2545 self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
2547 // 3. Relate the expected type and the formal one,
2548 // if the expected type was used for the coercion.
2549 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2553 // We also need to make sure we at least write the ty of the other
2554 // arguments which we skipped above.
2556 for arg in args.iter().skip(expected_arg_count) {
2557 let arg_ty = self.check_expr(&arg);
2559 // There are a few types which get autopromoted when passed via varargs
2560 // in C but we just error out instead and require explicit casts.
2561 let arg_ty = self.structurally_resolved_type(arg.span,
2564 ty::TyFloat(ast::FloatTy::F32) => {
2565 self.type_error_message(arg.span, |t| {
2566 format!("can't pass an `{}` to variadic \
2567 function, cast to `c_double`", t)
2570 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2571 self.type_error_message(arg.span, |t| {
2572 format!("can't pass `{}` to variadic \
2573 function, cast to `c_int`",
2577 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2578 self.type_error_message(arg.span, |t| {
2579 format!("can't pass `{}` to variadic \
2580 function, cast to `c_uint`",
2584 ty::TyFnDef(.., f) => {
2585 let ptr_ty = self.tcx.mk_fn_ptr(f);
2586 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2587 self.type_error_message(arg.span,
2589 format!("can't pass `{}` to variadic \
2590 function, cast to `{}`", t, ptr_ty)
2599 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2600 (0..len).map(|_| self.tcx.types.err).collect()
2603 // AST fragment checking
2606 expected: Expectation<'tcx>)
2612 ast::LitKind::Str(..) => tcx.mk_static_str(),
2613 ast::LitKind::ByteStr(ref v) => {
2614 tcx.mk_imm_ref(tcx.types.re_static,
2615 tcx.mk_array(tcx.types.u8, v.len()))
2617 ast::LitKind::Byte(_) => tcx.types.u8,
2618 ast::LitKind::Char(_) => tcx.types.char,
2619 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2620 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2621 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2622 let opt_ty = expected.to_option(self).and_then(|ty| {
2624 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2625 ty::TyChar => Some(tcx.types.u8),
2626 ty::TyRawPtr(..) => Some(tcx.types.usize),
2627 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2631 opt_ty.unwrap_or_else(
2632 || tcx.mk_int_var(self.next_int_var_id()))
2634 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2635 ast::LitKind::FloatUnsuffixed(_) => {
2636 let opt_ty = expected.to_option(self).and_then(|ty| {
2638 ty::TyFloat(_) => Some(ty),
2642 opt_ty.unwrap_or_else(
2643 || tcx.mk_float_var(self.next_float_var_id()))
2645 ast::LitKind::Bool(_) => tcx.types.bool
2649 fn check_expr_eq_type(&self,
2650 expr: &'gcx hir::Expr,
2651 expected: Ty<'tcx>) {
2652 let ty = self.check_expr_with_hint(expr, expected);
2653 self.demand_eqtype(expr.span, expected, ty);
2656 pub fn check_expr_has_type(&self,
2657 expr: &'gcx hir::Expr,
2658 expected: Ty<'tcx>) -> Ty<'tcx> {
2659 let mut ty = self.check_expr_with_hint(expr, expected);
2661 // While we don't allow *arbitrary* coercions here, we *do* allow
2662 // coercions from ! to `expected`.
2664 assert!(!self.tables.borrow().adjustments.contains_key(&expr.id),
2665 "expression with never type wound up being adjusted");
2666 let adj_ty = self.next_diverging_ty_var(
2667 TypeVariableOrigin::AdjustmentType(expr.span));
2668 self.apply_adjustments(expr, vec![Adjustment {
2669 kind: Adjust::NeverToAny,
2675 self.demand_suptype(expr.span, expected, ty);
2679 fn check_expr_coercable_to_type(&self,
2680 expr: &'gcx hir::Expr,
2681 expected: Ty<'tcx>) -> Ty<'tcx> {
2682 let ty = self.check_expr_with_hint(expr, expected);
2683 self.demand_coerce(expr, ty, expected);
2687 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2688 expected: Ty<'tcx>) -> Ty<'tcx> {
2689 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2692 fn check_expr_with_expectation(&self,
2693 expr: &'gcx hir::Expr,
2694 expected: Expectation<'tcx>) -> Ty<'tcx> {
2695 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2698 fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
2699 self.check_expr_with_expectation(expr, NoExpectation)
2702 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2703 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2704 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2707 // determine the `self` type, using fresh variables for all variables
2708 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2709 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2711 pub fn impl_self_ty(&self,
2712 span: Span, // (potential) receiver for this impl
2714 -> TypeAndSubsts<'tcx> {
2715 let ity = self.tcx.type_of(did);
2716 debug!("impl_self_ty: ity={:?}", ity);
2718 let substs = self.fresh_substs_for_item(span, did);
2719 let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
2721 TypeAndSubsts { substs: substs, ty: substd_ty }
2724 /// Unifies the output type with the expected type early, for more coercions
2725 /// and forward type information on the input expressions.
2726 fn expected_inputs_for_expected_output(&self,
2728 expected_ret: Expectation<'tcx>,
2729 formal_ret: Ty<'tcx>,
2730 formal_args: &[Ty<'tcx>])
2732 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2733 self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
2734 // Attempt to apply a subtyping relationship between the formal
2735 // return type (likely containing type variables if the function
2736 // is polymorphic) and the expected return type.
2737 // No argument expectations are produced if unification fails.
2738 let origin = self.misc(call_span);
2739 let ures = self.at(&origin, self.param_env).sup(ret_ty, formal_ret);
2741 // FIXME(#15760) can't use try! here, FromError doesn't default
2742 // to identity so the resulting type is not constrained.
2745 // Process any obligations locally as much as
2746 // we can. We don't care if some things turn
2747 // out unconstrained or ambiguous, as we're
2748 // just trying to get hints here.
2749 let result = self.save_and_restore_in_snapshot_flag(|_| {
2750 let mut fulfill = FulfillmentContext::new();
2751 let ok = ok; // FIXME(#30046)
2752 for obligation in ok.obligations {
2753 fulfill.register_predicate_obligation(self, obligation);
2755 fulfill.select_where_possible(self)
2760 Err(_) => return Err(()),
2763 Err(_) => return Err(()),
2766 // Record all the argument types, with the substitutions
2767 // produced from the above subtyping unification.
2768 Ok(formal_args.iter().map(|ty| {
2769 self.resolve_type_vars_if_possible(ty)
2772 }).unwrap_or(vec![]);
2773 debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
2774 formal_args, formal_ret,
2775 expected_args, expected_ret);
2779 // Checks a method call.
2780 fn check_method_call(&self,
2781 expr: &'gcx hir::Expr,
2782 method_name: Spanned<ast::Name>,
2783 args: &'gcx [hir::Expr],
2785 expected: Expectation<'tcx>,
2786 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2787 let rcvr = &args[0];
2788 let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2790 // no need to check for bot/err -- callee does that
2791 let expr_t = self.structurally_resolved_type(expr.span, rcvr_t);
2793 let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2794 let method = match self.lookup_method(method_name.span,
2801 self.write_method_call(expr.id, method);
2805 if method_name.node != keywords::Invalid.name() {
2806 self.report_method_error(method_name.span,
2817 // Call the generic checker.
2818 self.check_method_argument_types(method_name.span, method,
2824 fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
2828 .unwrap_or_else(|| span_bug!(return_expr.span,
2829 "check_return_expr called outside fn body"));
2831 let ret_ty = ret_coercion.borrow().expected_ty();
2832 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
2833 ret_coercion.borrow_mut()
2835 &self.misc(return_expr.span),
2838 self.diverges.get());
2842 // A generic function for checking the then and else in an if
2844 fn check_then_else(&self,
2845 cond_expr: &'gcx hir::Expr,
2846 then_expr: &'gcx hir::Expr,
2847 opt_else_expr: Option<&'gcx hir::Expr>,
2849 expected: Expectation<'tcx>) -> Ty<'tcx> {
2850 let cond_ty = self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2851 let cond_diverges = self.diverges.get();
2852 self.diverges.set(Diverges::Maybe);
2854 let expected = expected.adjust_for_branches(self);
2855 let then_ty = self.check_expr_with_expectation(then_expr, expected);
2856 let then_diverges = self.diverges.get();
2857 self.diverges.set(Diverges::Maybe);
2859 // We've already taken the expected type's preferences
2860 // into account when typing the `then` branch. To figure
2861 // out the initial shot at a LUB, we thus only consider
2862 // `expected` if it represents a *hard* constraint
2863 // (`only_has_type`); otherwise, we just go with a
2864 // fresh type variable.
2865 let coerce_to_ty = expected.coercion_target_type(self, sp);
2866 let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty);
2868 let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
2869 coerce.coerce(self, &if_cause, then_expr, then_ty, then_diverges);
2871 if let Some(else_expr) = opt_else_expr {
2872 let else_ty = self.check_expr_with_expectation(else_expr, expected);
2873 let else_diverges = self.diverges.get();
2875 coerce.coerce(self, &if_cause, else_expr, else_ty, else_diverges);
2877 // We won't diverge unless both branches do (or the condition does).
2878 self.diverges.set(cond_diverges | then_diverges & else_diverges);
2880 let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
2881 coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true);
2883 // If the condition is false we can't diverge.
2884 self.diverges.set(cond_diverges);
2887 let result_ty = coerce.complete(self);
2888 if cond_ty.references_error() {
2895 // Check field access expressions
2896 fn check_field(&self,
2897 expr: &'gcx hir::Expr,
2898 lvalue_pref: LvaluePreference,
2899 base: &'gcx hir::Expr,
2900 field: &Spanned<ast::Name>) -> Ty<'tcx> {
2901 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2902 let expr_t = self.structurally_resolved_type(expr.span,
2904 let mut private_candidate = None;
2905 let mut autoderef = self.autoderef(expr.span, expr_t);
2906 while let Some((base_t, _)) = autoderef.next() {
2908 ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
2909 debug!("struct named {:?}", base_t);
2910 let (ident, def_scope) =
2911 self.tcx.adjust(field.node, base_def.did, self.body_id);
2912 let fields = &base_def.struct_variant().fields;
2913 if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
2914 let field_ty = self.field_ty(expr.span, field, substs);
2915 if field.vis.is_accessible_from(def_scope, self.tcx) {
2916 let adjustments = autoderef.adjust_steps(lvalue_pref);
2917 self.apply_adjustments(base, adjustments);
2918 autoderef.finalize();
2920 self.tcx.check_stability(field.did, expr.id, expr.span);
2924 private_candidate = Some((base_def.did, field_ty));
2930 autoderef.unambiguous_final_ty();
2932 if let Some((did, field_ty)) = private_candidate {
2933 let struct_path = self.tcx().item_path_str(did);
2934 let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
2935 let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
2936 // Also check if an accessible method exists, which is often what is meant.
2937 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2938 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2943 } else if field.node == keywords::Invalid.name() {
2944 self.tcx().types.err
2945 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2946 self.type_error_struct(field.span, |actual| {
2947 format!("attempted to take value of method `{}` on type \
2948 `{}`", field.node, actual)
2950 .help("maybe a `()` to call it is missing? \
2951 If not, try an anonymous function")
2953 self.tcx().types.err
2955 if !expr_t.is_primitive_ty() {
2956 let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0609,
2957 "no field `{}` on type `{}`",
2958 field.node, expr_t);
2960 ty::TyAdt(def, _) if !def.is_enum() => {
2961 if let Some(suggested_field_name) =
2962 Self::suggest_field_name(def.struct_variant(), field, vec![]) {
2963 err.span_label(field.span,
2964 format!("did you mean `{}`?", suggested_field_name));
2966 err.span_label(field.span, "unknown field");
2969 ty::TyRawPtr(..) => {
2970 err.note(&format!("`{0}` is a native pointer; perhaps you need to deref \
2972 self.tcx.hir.node_to_pretty_string(base.id),
2979 type_error_struct!(self.tcx().sess, field.span, expr_t, E0610,
2980 "`{}` is a primitive type and therefore doesn't have fields",
2983 self.tcx().types.err
2987 // Return an hint about the closest match in field names
2988 fn suggest_field_name(variant: &'tcx ty::VariantDef,
2989 field: &Spanned<ast::Name>,
2990 skip : Vec<InternedString>)
2992 let name = field.node.as_str();
2993 let names = variant.fields.iter().filter_map(|field| {
2994 // ignore already set fields and private fields from non-local crates
2995 if skip.iter().any(|x| *x == field.name.as_str()) ||
2996 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
3003 // only find fits with at least one matching letter
3004 find_best_match_for_name(names, &name, Some(name.len()))
3007 // Check tuple index expressions
3008 fn check_tup_field(&self,
3009 expr: &'gcx hir::Expr,
3010 lvalue_pref: LvaluePreference,
3011 base: &'gcx hir::Expr,
3012 idx: codemap::Spanned<usize>) -> Ty<'tcx> {
3013 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
3014 let expr_t = self.structurally_resolved_type(expr.span,
3016 let mut private_candidate = None;
3017 let mut tuple_like = false;
3018 let mut autoderef = self.autoderef(expr.span, expr_t);
3019 while let Some((base_t, _)) = autoderef.next() {
3020 let field = match base_t.sty {
3021 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
3022 tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
3023 if !tuple_like { continue }
3025 debug!("tuple struct named {:?}", base_t);
3026 let ident = ast::Ident {
3027 name: Symbol::intern(&idx.node.to_string()),
3028 ctxt: idx.span.ctxt.modern(),
3030 let (ident, def_scope) =
3031 self.tcx.adjust_ident(ident, base_def.did, self.body_id);
3032 let fields = &base_def.struct_variant().fields;
3033 if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
3034 let field_ty = self.field_ty(expr.span, field, substs);
3035 if field.vis.is_accessible_from(def_scope, self.tcx) {
3036 self.tcx.check_stability(field.did, expr.id, expr.span);
3039 private_candidate = Some((base_def.did, field_ty));
3046 ty::TyTuple(ref v, _) => {
3048 v.get(idx.node).cloned()
3053 if let Some(field_ty) = field {
3054 let adjustments = autoderef.adjust_steps(lvalue_pref);
3055 self.apply_adjustments(base, adjustments);
3056 autoderef.finalize();
3060 autoderef.unambiguous_final_ty();
3062 if let Some((did, field_ty)) = private_candidate {
3063 let struct_path = self.tcx().item_path_str(did);
3064 let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3065 self.tcx().sess.span_err(expr.span, &msg);
3069 self.type_error_message(
3073 format!("attempted out-of-bounds tuple index `{}` on \
3078 format!("attempted tuple index `{}` on type `{}`, but the \
3079 type was not a tuple or tuple struct",
3086 self.tcx().types.err
3089 fn report_unknown_field(&self,
3091 variant: &'tcx ty::VariantDef,
3093 skip_fields: &[hir::Field],
3095 let mut err = self.type_error_struct_with_diag(
3097 |actual| match ty.sty {
3098 ty::TyAdt(adt, ..) if adt.is_enum() => {
3099 struct_span_err!(self.tcx.sess, field.name.span, E0559,
3100 "{} `{}::{}` has no field named `{}`",
3101 kind_name, actual, variant.name, field.name.node)
3104 struct_span_err!(self.tcx.sess, field.name.span, E0560,
3105 "{} `{}` has no field named `{}`",
3106 kind_name, actual, field.name.node)
3110 // prevent all specified fields from being suggested
3111 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3112 if let Some(field_name) = Self::suggest_field_name(variant,
3114 skip_fields.collect()) {
3115 err.span_label(field.name.span,
3116 format!("field does not exist - did you mean `{}`?", field_name));
3119 ty::TyAdt(adt, ..) if adt.is_enum() => {
3120 err.span_label(field.name.span, format!("`{}::{}` does not have this field",
3124 err.span_label(field.name.span, format!("`{}` does not have this field", ty));
3131 fn check_expr_struct_fields(&self,
3133 expected: Expectation<'tcx>,
3134 expr_id: ast::NodeId,
3136 variant: &'tcx ty::VariantDef,
3137 ast_fields: &'gcx [hir::Field],
3138 check_completeness: bool) {
3142 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3143 .get(0).cloned().unwrap_or(adt_ty);
3145 let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
3146 (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
3147 (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
3149 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3152 let mut remaining_fields = FxHashMap();
3153 for field in &variant.fields {
3154 remaining_fields.insert(field.name.to_ident(), field);
3157 let mut seen_fields = FxHashMap();
3159 let mut error_happened = false;
3161 // Typecheck each field.
3162 for field in ast_fields {
3163 let final_field_type;
3164 let field_type_hint;
3166 let ident = tcx.adjust(field.name.node, variant.did, self.body_id).0;
3167 if let Some(v_field) = remaining_fields.remove(&ident) {
3168 final_field_type = self.field_ty(field.span, v_field, substs);
3169 field_type_hint = self.field_ty(field.span, v_field, hint_substs);
3171 seen_fields.insert(field.name.node, field.span);
3173 // we don't look at stability attributes on
3174 // struct-like enums (yet...), but it's definitely not
3175 // a bug to have construct one.
3176 if adt_kind != ty::AdtKind::Enum {
3177 tcx.check_stability(v_field.did, expr_id, field.span);
3180 error_happened = true;
3181 final_field_type = tcx.types.err;
3182 field_type_hint = tcx.types.err;
3183 if let Some(_) = variant.find_field_named(field.name.node) {
3184 let mut err = struct_span_err!(self.tcx.sess,
3187 "field `{}` specified more than once",
3190 err.span_label(field.name.span, "used more than once");
3192 if let Some(prev_span) = seen_fields.get(&field.name.node) {
3193 err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
3198 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3202 // Make sure to give a type to the field even if there's
3203 // an error, so we can continue typechecking
3204 let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
3205 self.demand_coerce(&field.expr, ty, final_field_type);
3208 // Make sure the programmer specified correct number of fields.
3209 if kind_name == "union" {
3210 if ast_fields.len() != 1 {
3211 tcx.sess.span_err(span, "union expressions should have exactly one field");
3213 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3214 let len = remaining_fields.len();
3216 let mut displayable_field_names = remaining_fields
3218 .map(|ident| ident.name.as_str())
3219 .collect::<Vec<_>>();
3221 displayable_field_names.sort();
3223 let truncated_fields_error = if len <= 3 {
3226 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3229 let remaining_fields_names = displayable_field_names.iter().take(3)
3230 .map(|n| format!("`{}`", n))
3231 .collect::<Vec<_>>()
3234 struct_span_err!(tcx.sess, span, E0063,
3235 "missing field{} {}{} in initializer of `{}`",
3236 if remaining_fields.len() == 1 {""} else {"s"},
3237 remaining_fields_names,
3238 truncated_fields_error,
3240 .span_label(span, format!("missing {}{}",
3241 remaining_fields_names,
3242 truncated_fields_error))
3247 fn check_struct_fields_on_error(&self,
3248 fields: &'gcx [hir::Field],
3249 base_expr: &'gcx Option<P<hir::Expr>>) {
3250 for field in fields {
3251 self.check_expr(&field.expr);
3255 self.check_expr(&base);
3261 pub fn check_struct_path(&self,
3263 node_id: ast::NodeId)
3264 -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
3265 let path_span = match *qpath {
3266 hir::QPath::Resolved(_, ref path) => path.span,
3267 hir::QPath::TypeRelative(ref qself, _) => qself.span
3269 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3270 let variant = match def {
3272 self.set_tainted_by_errors();
3275 Def::Variant(..) => {
3277 ty::TyAdt(adt, substs) => {
3278 Some((adt.variant_of_def(def), adt.did, substs))
3280 _ => bug!("unexpected type: {:?}", ty.sty)
3283 Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3284 Def::AssociatedTy(..) | Def::SelfTy(..) => {
3286 ty::TyAdt(adt, substs) if !adt.is_enum() => {
3287 Some((adt.struct_variant(), adt.did, substs))
3292 _ => bug!("unexpected definition: {:?}", def)
3295 if let Some((variant, did, substs)) = variant {
3296 // Check bounds on type arguments used in the path.
3297 let bounds = self.instantiate_bounds(path_span, did, substs);
3298 let cause = traits::ObligationCause::new(path_span, self.body_id,
3299 traits::ItemObligation(did));
3300 self.add_obligations_for_parameters(cause, &bounds);
3304 struct_span_err!(self.tcx.sess, path_span, E0071,
3305 "expected struct, variant or union type, found {}",
3306 ty.sort_string(self.tcx))
3307 .span_label(path_span, "not a struct")
3313 fn check_expr_struct(&self,
3315 expected: Expectation<'tcx>,
3317 fields: &'gcx [hir::Field],
3318 base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3320 // Find the relevant variant
3321 let (variant, struct_ty) =
3322 if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3325 self.check_struct_fields_on_error(fields, base_expr);
3326 return self.tcx.types.err;
3329 let path_span = match *qpath {
3330 hir::QPath::Resolved(_, ref path) => path.span,
3331 hir::QPath::TypeRelative(ref qself, _) => qself.span
3334 self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3335 base_expr.is_none());
3336 if let &Some(ref base_expr) = base_expr {
3337 self.check_expr_has_type(base_expr, struct_ty);
3338 match struct_ty.sty {
3339 ty::TyAdt(adt, substs) if adt.is_struct() => {
3340 let fru_field_types = adt.struct_variant().fields.iter().map(|f| {
3341 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
3343 self.tables.borrow_mut().fru_field_types.insert(expr.id, fru_field_types);
3346 span_err!(self.tcx.sess, base_expr.span, E0436,
3347 "functional record update syntax requires a struct");
3351 self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3357 /// If an expression has any sub-expressions that result in a type error,
3358 /// inspecting that expression's type with `ty.references_error()` will return
3359 /// true. Likewise, if an expression is known to diverge, inspecting its
3360 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3361 /// strict, _|_ can appear in the type of an expression that does not,
3362 /// itself, diverge: for example, fn() -> _|_.)
3363 /// Note that inspecting a type's structure *directly* may expose the fact
3364 /// that there are actually multiple representations for `TyError`, so avoid
3365 /// that when err needs to be handled differently.
3366 fn check_expr_with_expectation_and_lvalue_pref(&self,
3367 expr: &'gcx hir::Expr,
3368 expected: Expectation<'tcx>,
3369 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3370 debug!(">> typechecking: expr={:?} expected={:?}",
3373 // Warn for expressions after diverging siblings.
3374 self.warn_if_unreachable(expr.id, expr.span, "expression");
3376 // Hide the outer diverging and has_errors flags.
3377 let old_diverges = self.diverges.get();
3378 let old_has_errors = self.has_errors.get();
3379 self.diverges.set(Diverges::Maybe);
3380 self.has_errors.set(false);
3382 let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3384 // Warn for non-block expressions with diverging children.
3387 hir::ExprLoop(..) | hir::ExprWhile(..) |
3388 hir::ExprIf(..) | hir::ExprMatch(..) => {}
3390 _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3393 // Any expression that produces a value of type `!` must have diverged
3395 self.diverges.set(self.diverges.get() | Diverges::Always);
3398 // Record the type, which applies it effects.
3399 // We need to do this after the warning above, so that
3400 // we don't warn for the diverging expression itself.
3401 self.write_ty(expr.id, ty);
3403 // Combine the diverging and has_error flags.
3404 self.diverges.set(self.diverges.get() | old_diverges);
3405 self.has_errors.set(self.has_errors.get() | old_has_errors);
3407 debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3408 debug!("... {:?}, expected is {:?}", ty, expected);
3413 fn check_expr_kind(&self,
3414 expr: &'gcx hir::Expr,
3415 expected: Expectation<'tcx>,
3416 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3420 hir::ExprBox(ref subexpr) => {
3421 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3423 ty::TyAdt(def, _) if def.is_box()
3424 => Expectation::rvalue_hint(self, ty.boxed_ty()),
3428 let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3429 tcx.mk_box(referent_ty)
3432 hir::ExprLit(ref lit) => {
3433 self.check_lit(&lit, expected)
3435 hir::ExprBinary(op, ref lhs, ref rhs) => {
3436 self.check_binop(expr, op, lhs, rhs)
3438 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3439 self.check_binop_assign(expr, op, lhs, rhs)
3441 hir::ExprUnary(unop, ref oprnd) => {
3442 let expected_inner = match unop {
3443 hir::UnNot | hir::UnNeg => {
3450 let lvalue_pref = match unop {
3451 hir::UnDeref => lvalue_pref,
3454 let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3458 if !oprnd_t.references_error() {
3459 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3462 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3464 } else if let Some(ok) = self.try_overloaded_deref(
3465 expr.span, oprnd_t, lvalue_pref) {
3466 let method = self.register_infer_ok_obligations(ok);
3467 if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
3468 self.apply_adjustments(oprnd, vec![Adjustment {
3469 kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
3470 target: method.sig.inputs()[0]
3473 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3474 self.write_method_call(expr.id, method);
3476 self.type_error_message(expr.span, |actual| {
3477 format!("type `{}` cannot be \
3478 dereferenced", actual)
3480 oprnd_t = tcx.types.err;
3484 let result = self.check_user_unop(expr, oprnd_t, unop);
3485 // If it's builtin, we can reuse the type, this helps inference.
3486 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3491 let result = self.check_user_unop(expr, oprnd_t, unop);
3492 // If it's builtin, we can reuse the type, this helps inference.
3493 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3501 hir::ExprAddrOf(mutbl, ref oprnd) => {
3502 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3504 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3505 if self.tcx.expr_is_lval(&oprnd) {
3506 // Lvalues may legitimately have unsized types.
3507 // For example, dereferences of a fat pointer and
3508 // the last field of a struct can be unsized.
3509 ExpectHasType(mt.ty)
3511 Expectation::rvalue_hint(self, mt.ty)
3517 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3518 let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3520 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3521 if tm.ty.references_error() {
3524 // Note: at this point, we cannot say what the best lifetime
3525 // is to use for resulting pointer. We want to use the
3526 // shortest lifetime possible so as to avoid spurious borrowck
3527 // errors. Moreover, the longest lifetime will depend on the
3528 // precise details of the value whose address is being taken
3529 // (and how long it is valid), which we don't know yet until type
3530 // inference is complete.
3532 // Therefore, here we simply generate a region variable. The
3533 // region inferencer will then select the ultimate value.
3534 // Finally, borrowck is charged with guaranteeing that the
3535 // value whose address was taken can actually be made to live
3536 // as long as it needs to live.
3537 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3538 tcx.mk_ref(region, tm)
3541 hir::ExprPath(ref qpath) => {
3542 let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3543 expr.id, expr.span);
3544 let ty = if def != Def::Err {
3545 self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3547 self.set_tainted_by_errors();
3551 // We always require that the type provided as the value for
3552 // a type parameter outlives the moment of instantiation.
3553 let substs = self.tables.borrow().node_substs(expr.id);
3554 self.add_wf_bounds(substs, expr);
3558 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3559 for output in outputs {
3560 self.check_expr(output);
3562 for input in inputs {
3563 self.check_expr(input);
3567 hir::ExprBreak(destination, ref expr_opt) => {
3568 if let Some(target_id) = destination.target_id.opt_id() {
3569 let (e_ty, e_diverges, cause);
3570 if let Some(ref e) = *expr_opt {
3571 // If this is a break with a value, we need to type-check
3572 // the expression. Get an expected type from the loop context.
3573 let opt_coerce_to = {
3574 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3575 enclosing_breakables.find_breakable(target_id)
3578 .map(|coerce| coerce.expected_ty())
3581 // If the loop context is not a `loop { }`, then break with
3582 // a value is illegal, and `opt_coerce_to` will be `None`.
3583 // Just set expectation to error in that case.
3584 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3586 // Recurse without `enclosing_breakables` borrowed.
3587 e_ty = self.check_expr_with_hint(e, coerce_to);
3588 e_diverges = self.diverges.get();
3589 cause = self.misc(e.span);
3591 // Otherwise, this is a break *without* a value. That's
3592 // always legal, and is equivalent to `break ()`.
3593 e_ty = tcx.mk_nil();
3594 e_diverges = Diverges::Maybe;
3595 cause = self.misc(expr.span);
3598 // Now that we have type-checked `expr_opt`, borrow
3599 // the `enclosing_loops` field and let's coerce the
3600 // type of `expr_opt` into what is expected.
3601 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3602 let ctxt = enclosing_breakables.find_breakable(target_id);
3603 if let Some(ref mut coerce) = ctxt.coerce {
3604 if let Some(ref e) = *expr_opt {
3605 coerce.coerce(self, &cause, e, e_ty, e_diverges);
3607 assert!(e_ty.is_nil());
3608 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
3611 // If `ctxt.coerce` is `None`, we can just ignore
3612 // the type of the expresison. This is because
3613 // either this was a break *without* a value, in
3614 // which case it is always a legal type (`()`), or
3615 // else an error would have been flagged by the
3616 // `loops` pass for using break with an expression
3617 // where you are not supposed to.
3618 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3621 ctxt.may_break = true;
3623 // Otherwise, we failed to find the enclosing loop;
3624 // this can only happen if the `break` was not
3625 // inside a loop at all, which is caught by the
3626 // loop-checking pass.
3627 assert!(self.tcx.sess.err_count() > 0);
3630 // the type of a `break` is always `!`, since it diverges
3633 hir::ExprAgain(_) => { tcx.types.never }
3634 hir::ExprRet(ref expr_opt) => {
3635 if self.ret_coercion.is_none() {
3636 struct_span_err!(self.tcx.sess, expr.span, E0572,
3637 "return statement outside of function body").emit();
3638 } else if let Some(ref e) = *expr_opt {
3639 self.check_return_expr(e);
3641 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3642 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3643 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
3647 hir::ExprAssign(ref lhs, ref rhs) => {
3648 let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3651 if !tcx.expr_is_lval(&lhs) {
3653 tcx.sess, expr.span, E0070,
3654 "invalid left-hand side expression")
3657 "left-hand of expression not valid")
3661 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3663 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3665 if lhs_ty.references_error() || rhs_ty.references_error() {
3671 hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3672 self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3673 expr.span, expected)
3675 hir::ExprWhile(ref cond, ref body, _) => {
3676 let ctxt = BreakableCtxt {
3677 // cannot use break with a value from a while loop
3682 self.with_breakable_ctxt(expr.id, ctxt, || {
3683 self.check_expr_has_type(&cond, tcx.types.bool);
3684 let cond_diverging = self.diverges.get();
3685 self.check_block_no_value(&body);
3687 // We may never reach the body so it diverging means nothing.
3688 self.diverges.set(cond_diverging);
3693 hir::ExprLoop(ref body, _, source) => {
3694 let coerce = match source {
3695 // you can only use break with a value from a normal `loop { }`
3696 hir::LoopSource::Loop => {
3697 let coerce_to = expected.coercion_target_type(self, body.span);
3698 Some(CoerceMany::new(coerce_to))
3701 hir::LoopSource::WhileLet |
3702 hir::LoopSource::ForLoop => {
3707 let ctxt = BreakableCtxt {
3709 may_break: false, // will get updated if/when we find a `break`
3712 let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3713 self.check_block_no_value(&body);
3717 // No way to know whether it's diverging because
3718 // of a `break` or an outer `break` or `return.
3719 self.diverges.set(Diverges::Maybe);
3722 // If we permit break with a value, then result type is
3723 // the LUB of the breaks (possibly ! if none); else, it
3724 // is nil. This makes sense because infinite loops
3725 // (which would have type !) are only possible iff we
3726 // permit break with a value [1].
3727 assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3728 ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3730 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3731 self.check_match(expr, &discrim, arms, expected, match_src)
3733 hir::ExprClosure(capture, ref decl, body_id, _) => {
3734 self.check_expr_closure(expr, capture, &decl, body_id, expected)
3736 hir::ExprBlock(ref body) => {
3737 self.check_block_with_expected(&body, expected)
3739 hir::ExprCall(ref callee, ref args) => {
3740 self.check_call(expr, &callee, args, expected)
3742 hir::ExprMethodCall(name, ref tps, ref args) => {
3743 self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
3745 hir::ExprCast(ref e, ref t) => {
3746 // Find the type of `e`. Supply hints based on the type we are casting to,
3748 let t_cast = self.to_ty(t);
3749 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3750 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3751 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3752 let diverges = self.diverges.get();
3754 // Eagerly check for some obvious errors.
3755 if t_expr.references_error() || t_cast.references_error() {
3758 // Defer other checks until we're done type checking.
3759 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3760 match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
3762 deferred_cast_checks.push(cast_check);
3765 Err(ErrorReported) => {
3771 hir::ExprType(ref e, ref t) => {
3772 let typ = self.to_ty(&t);
3773 self.check_expr_eq_type(&e, typ);
3776 hir::ExprArray(ref args) => {
3777 let uty = expected.to_option(self).and_then(|uty| {
3779 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3784 let element_ty = if !args.is_empty() {
3785 let coerce_to = uty.unwrap_or_else(
3786 || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3787 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
3788 assert_eq!(self.diverges.get(), Diverges::Maybe);
3790 let e_ty = self.check_expr_with_hint(e, coerce_to);
3791 let cause = self.misc(e.span);
3792 coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
3794 coerce.complete(self)
3796 self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3798 tcx.mk_array(element_ty, args.len())
3800 hir::ExprRepeat(ref element, count) => {
3801 let count = eval_length(self.tcx, count, "repeat count")
3804 let uty = match expected {
3805 ExpectHasType(uty) => {
3807 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3814 let (element_ty, t) = match uty {
3816 self.check_expr_coercable_to_type(&element, uty);
3820 let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3821 let element_ty = self.check_expr_has_type(&element, t);
3827 // For [foo, ..n] where n > 1, `foo` must have
3829 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3830 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3833 if element_ty.references_error() {
3836 tcx.mk_array(t, count)
3839 hir::ExprTup(ref elts) => {
3840 let flds = expected.only_has_type(self).and_then(|ty| {
3842 ty::TyTuple(ref flds, _) => Some(&flds[..]),
3847 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3848 let t = match flds {
3849 Some(ref fs) if i < fs.len() => {
3851 self.check_expr_coercable_to_type(&e, ety);
3855 self.check_expr_with_expectation(&e, NoExpectation)
3860 let tuple = tcx.mk_tup(elt_ts_iter, false);
3861 if tuple.references_error() {
3867 hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3868 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3870 hir::ExprField(ref base, ref field) => {
3871 self.check_field(expr, lvalue_pref, &base, field)
3873 hir::ExprTupField(ref base, idx) => {
3874 self.check_tup_field(expr, lvalue_pref, &base, idx)
3876 hir::ExprIndex(ref base, ref idx) => {
3877 let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3878 let idx_t = self.check_expr(&idx);
3880 if base_t.references_error() {
3882 } else if idx_t.references_error() {
3885 let base_t = self.structurally_resolved_type(expr.span, base_t);
3886 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3887 Some((index_ty, element_ty)) => {
3888 self.demand_coerce(idx, idx_t, index_ty);
3892 let mut err = self.type_error_struct(
3895 format!("cannot index a value of type `{}`",
3899 // Try to give some advice about indexing tuples.
3900 if let ty::TyTuple(..) = base_t.sty {
3901 let mut needs_note = true;
3902 // If the index is an integer, we can show the actual
3903 // fixed expression:
3904 if let hir::ExprLit(ref lit) = idx.node {
3905 if let ast::LitKind::Int(i,
3906 ast::LitIntType::Unsuffixed) = lit.node {
3907 let snip = tcx.sess.codemap().span_to_snippet(base.span);
3908 if let Ok(snip) = snip {
3909 err.span_suggestion(expr.span,
3910 "to access tuple elements, use",
3911 format!("{}.{}", snip, i));
3917 err.help("to access tuple elements, use tuple indexing \
3918 syntax (e.g. `tuple.0`)");
3930 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3931 // The newly resolved definition is written into `type_dependent_defs`.
3932 fn finish_resolving_struct_path(&self,
3935 node_id: ast::NodeId)
3939 hir::QPath::Resolved(ref maybe_qself, ref path) => {
3940 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
3941 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
3944 hir::QPath::TypeRelative(ref qself, ref segment) => {
3945 let ty = self.to_ty(qself);
3947 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
3952 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
3955 // Write back the new resolution.
3956 self.tables.borrow_mut().type_dependent_defs.insert(node_id, def);
3963 // Resolve associated value path into a base type and associated constant or method definition.
3964 // The newly resolved definition is written into `type_dependent_defs`.
3965 pub fn resolve_ty_and_def_ufcs<'b>(&self,
3966 qpath: &'b hir::QPath,
3967 node_id: ast::NodeId,
3969 -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3971 let (ty, item_segment) = match *qpath {
3972 hir::QPath::Resolved(ref opt_qself, ref path) => {
3974 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
3975 &path.segments[..]);
3977 hir::QPath::TypeRelative(ref qself, ref segment) => {
3978 (self.to_ty(qself), segment)
3981 let item_name = item_segment.name;
3982 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3985 let def = match error {
3986 method::MethodError::PrivateMatch(def) => def,
3989 if item_name != keywords::Invalid.name() {
3990 self.report_method_error(span, ty, item_name, None, error, None);
3996 // Write back the new resolution.
3997 self.tables.borrow_mut().type_dependent_defs.insert(node_id, def);
3998 (def, Some(ty), slice::ref_slice(&**item_segment))
4001 pub fn check_decl_initializer(&self,
4002 local: &'gcx hir::Local,
4003 init: &'gcx hir::Expr) -> Ty<'tcx>
4005 let ref_bindings = local.pat.contains_ref_binding();
4007 let local_ty = self.local_ty(init.span, local.id);
4008 if let Some(m) = ref_bindings {
4009 // Somewhat subtle: if we have a `ref` binding in the pattern,
4010 // we want to avoid introducing coercions for the RHS. This is
4011 // both because it helps preserve sanity and, in the case of
4012 // ref mut, for soundness (issue #23116). In particular, in
4013 // the latter case, we need to be clear that the type of the
4014 // referent for the reference that results is *equal to* the
4015 // type of the lvalue it is referencing, and not some
4016 // supertype thereof.
4017 let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
4018 self.demand_eqtype(init.span, init_ty, local_ty);
4021 self.check_expr_coercable_to_type(init, local_ty)
4025 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
4026 let t = self.local_ty(local.span, local.id);
4027 self.write_ty(local.id, t);
4029 if let Some(ref init) = local.init {
4030 let init_ty = self.check_decl_initializer(local, &init);
4031 if init_ty.references_error() {
4032 self.write_ty(local.id, init_ty);
4036 self.check_pat(&local.pat, t);
4037 let pat_ty = self.node_ty(local.pat.id);
4038 if pat_ty.references_error() {
4039 self.write_ty(local.id, pat_ty);
4043 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4044 // Don't do all the complex logic below for DeclItem.
4046 hir::StmtDecl(ref decl, _) => {
4048 hir::DeclLocal(_) => {}
4049 hir::DeclItem(_) => {
4054 hir::StmtExpr(..) | hir::StmtSemi(..) => {}
4057 self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
4059 // Hide the outer diverging and has_errors flags.
4060 let old_diverges = self.diverges.get();
4061 let old_has_errors = self.has_errors.get();
4062 self.diverges.set(Diverges::Maybe);
4063 self.has_errors.set(false);
4066 hir::StmtDecl(ref decl, _) => {
4068 hir::DeclLocal(ref l) => {
4069 self.check_decl_local(&l);
4071 hir::DeclItem(_) => {/* ignore for now */}
4074 hir::StmtExpr(ref expr, _) => {
4075 // Check with expected type of ()
4076 self.check_expr_has_type(&expr, self.tcx.mk_nil());
4078 hir::StmtSemi(ref expr, _) => {
4079 self.check_expr(&expr);
4083 // Combine the diverging and has_error flags.
4084 self.diverges.set(self.diverges.get() | old_diverges);
4085 self.has_errors.set(self.has_errors.get() | old_has_errors);
4088 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
4089 let unit = self.tcx.mk_nil();
4090 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4092 // if the block produces a `!` value, that can always be
4093 // (effectively) coerced to unit.
4095 self.demand_suptype(blk.span, unit, ty);
4099 fn check_block_with_expected(&self,
4100 blk: &'gcx hir::Block,
4101 expected: Expectation<'tcx>) -> Ty<'tcx> {
4103 let mut fcx_ps = self.ps.borrow_mut();
4104 let unsafety_state = fcx_ps.recurse(blk);
4105 replace(&mut *fcx_ps, unsafety_state)
4108 // In some cases, blocks have just one exit, but other blocks
4109 // can be targeted by multiple breaks. This cannot happen in
4110 // normal Rust syntax today, but it can happen when we desugar
4111 // a `do catch { ... }` expression.
4115 // 'a: { if true { break 'a Err(()); } Ok(()) }
4117 // Here we would wind up with two coercions, one from
4118 // `Err(())` and the other from the tail expression
4119 // `Ok(())`. If the tail expression is omitted, that's a
4120 // "forced unit" -- unless the block diverges, in which
4121 // case we can ignore the tail expression (e.g., `'a: {
4122 // break 'a 22; }` would not force the type of the block
4124 let tail_expr = blk.expr.as_ref();
4125 let coerce_to_ty = expected.coercion_target_type(self, blk.span);
4126 let coerce = if blk.targeted_by_break {
4127 CoerceMany::new(coerce_to_ty)
4129 let tail_expr: &[P<hir::Expr>] = match tail_expr {
4130 Some(e) => ref_slice(e),
4133 CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
4136 let ctxt = BreakableCtxt {
4137 coerce: Some(coerce),
4141 let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
4142 for s in &blk.stmts {
4146 // check the tail expression **without** holding the
4147 // `enclosing_breakables` lock below.
4148 let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
4150 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4151 let mut ctxt = enclosing_breakables.find_breakable(blk.id);
4152 let mut coerce = ctxt.coerce.as_mut().unwrap();
4153 if let Some(tail_expr_ty) = tail_expr_ty {
4154 let tail_expr = tail_expr.unwrap();
4156 &self.misc(tail_expr.span),
4159 self.diverges.get());
4161 // Subtle: if there is no explicit tail expression,
4162 // that is typically equivalent to a tail expression
4163 // of `()` -- except if the block diverges. In that
4164 // case, there is no value supplied from the tail
4165 // expression (assuming there are no other breaks,
4166 // this implies that the type of the block will be
4169 // #41425 -- label the implicit `()` as being the
4170 // "found type" here, rather than the "expected type".
4171 if !self.diverges.get().always() {
4172 coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
4173 if let Some(expected_ty) = expected.only_has_type(self) {
4174 self.consider_hint_about_removing_semicolon(blk,
4183 let mut ty = ctxt.coerce.unwrap().complete(self);
4185 if self.has_errors.get() || ty.references_error() {
4186 ty = self.tcx.types.err
4189 self.write_ty(blk.id, ty);
4191 *self.ps.borrow_mut() = prev;
4195 /// A common error is to add an extra semicolon:
4198 /// fn foo() -> usize {
4203 /// This routine checks if the final statement in a block is an
4204 /// expression with an explicit semicolon whose type is compatible
4205 /// with `expected_ty`. If so, it suggests removing the semicolon.
4206 fn consider_hint_about_removing_semicolon(&self,
4207 blk: &'gcx hir::Block,
4208 expected_ty: Ty<'tcx>,
4209 err: &mut DiagnosticBuilder) {
4210 // Be helpful when the user wrote `{... expr;}` and
4211 // taking the `;` off is enough to fix the error.
4212 let last_stmt = match blk.stmts.last() {
4216 let last_expr = match last_stmt.node {
4217 hir::StmtSemi(ref e, _) => e,
4220 let last_expr_ty = self.node_ty(last_expr.id);
4221 if self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err() {
4224 let original_span = original_sp(last_stmt.span, blk.span);
4225 let span_semi = Span {
4226 lo: original_span.hi - BytePos(1),
4227 hi: original_span.hi,
4228 ctxt: original_span.ctxt,
4230 err.span_help(span_semi, "consider removing this semicolon:");
4233 // Instantiates the given path, which must refer to an item with the given
4234 // number of type parameters and type.
4235 pub fn instantiate_value_path(&self,
4236 segments: &[hir::PathSegment],
4237 opt_self_ty: Option<Ty<'tcx>>,
4240 node_id: ast::NodeId)
4242 debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4247 // We need to extract the type parameters supplied by the user in
4248 // the path `path`. Due to the current setup, this is a bit of a
4249 // tricky-process; the problem is that resolve only tells us the
4250 // end-point of the path resolution, and not the intermediate steps.
4251 // Luckily, we can (at least for now) deduce the intermediate steps
4252 // just from the end-point.
4254 // There are basically four cases to consider:
4256 // 1. Reference to a constructor of enum variant or struct:
4258 // struct Foo<T>(...)
4259 // enum E<T> { Foo(...) }
4261 // In these cases, the parameters are declared in the type
4264 // 2. Reference to a fn item or a free constant:
4268 // In this case, the path will again always have the form
4269 // `a::b::foo::<T>` where only the final segment should have
4270 // type parameters. However, in this case, those parameters are
4271 // declared on a value, and hence are in the `FnSpace`.
4273 // 3. Reference to a method or an associated constant:
4275 // impl<A> SomeStruct<A> {
4279 // Here we can have a path like
4280 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4281 // may appear in two places. The penultimate segment,
4282 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4283 // final segment, `foo::<B>` contains parameters in fn space.
4285 // 4. Reference to a local variable
4287 // Local variables can't have any type parameters.
4289 // The first step then is to categorize the segments appropriately.
4291 assert!(!segments.is_empty());
4293 let mut ufcs_associated = None;
4294 let mut type_segment = None;
4295 let mut fn_segment = None;
4297 // Case 1. Reference to a struct/variant constructor.
4298 Def::StructCtor(def_id, ..) |
4299 Def::VariantCtor(def_id, ..) => {
4300 // Everything but the final segment should have no
4301 // parameters at all.
4302 let mut generics = self.tcx.generics_of(def_id);
4303 if let Some(def_id) = generics.parent {
4304 // Variant and struct constructors use the
4305 // generics of their parent type definition.
4306 generics = self.tcx.generics_of(def_id);
4308 type_segment = Some((segments.last().unwrap(), generics));
4311 // Case 2. Reference to a top-level value.
4313 Def::Const(def_id) |
4314 Def::Static(def_id, _) => {
4315 fn_segment = Some((segments.last().unwrap(),
4316 self.tcx.generics_of(def_id)));
4319 // Case 3. Reference to a method or associated const.
4320 Def::Method(def_id) |
4321 Def::AssociatedConst(def_id) => {
4322 let container = self.tcx.associated_item(def_id).container;
4324 ty::TraitContainer(trait_did) => {
4325 callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4327 ty::ImplContainer(_) => {}
4330 let generics = self.tcx.generics_of(def_id);
4331 if segments.len() >= 2 {
4332 let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
4333 type_segment = Some((&segments[segments.len() - 2], parent_generics));
4335 // `<T>::assoc` will end up here, and so can `T::assoc`.
4336 let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4337 ufcs_associated = Some((container, self_ty));
4339 fn_segment = Some((segments.last().unwrap(), generics));
4342 // Case 4. Local variable, no generics.
4343 Def::Local(..) | Def::Upvar(..) => {}
4345 _ => bug!("unexpected definition: {:?}", def),
4348 debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4350 // Now that we have categorized what space the parameters for each
4351 // segment belong to, let's sort out the parameters that the user
4352 // provided (if any) into their appropriate spaces. We'll also report
4353 // errors if type parameters are provided in an inappropriate place.
4354 let poly_segments = type_segment.is_some() as usize +
4355 fn_segment.is_some() as usize;
4356 AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4359 Def::Local(def_id) | Def::Upvar(def_id, ..) => {
4360 let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
4361 let ty = self.local_ty(span, nid);
4362 let ty = self.normalize_associated_types_in(span, &ty);
4363 self.write_ty(node_id, ty);
4369 // Now we have to compare the types that the user *actually*
4370 // provided against the types that were *expected*. If the user
4371 // did not provide any types, then we want to substitute inference
4372 // variables. If the user provided some types, we may still need
4373 // to add defaults. If the user provided *too many* types, that's
4375 self.check_path_parameter_count(span, &mut type_segment);
4376 self.check_path_parameter_count(span, &mut fn_segment);
4378 let (fn_start, has_self) = match (type_segment, fn_segment) {
4379 (_, Some((_, generics))) => {
4380 (generics.parent_count(), generics.has_self)
4382 (Some((_, generics)), None) => {
4383 (generics.own_count(), generics.has_self)
4385 (None, None) => (0, false)
4387 let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4388 let mut i = def.index as usize;
4390 let segment = if i < fn_start {
4391 i -= has_self as usize;
4397 let lifetimes = match segment.map(|(s, _)| &s.parameters) {
4398 Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
4399 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4403 if let Some(lifetime) = lifetimes.get(i) {
4404 AstConv::ast_region_to_region(self, lifetime, Some(def))
4406 self.re_infer(span, Some(def)).unwrap()
4409 let mut i = def.index as usize;
4411 let segment = if i < fn_start {
4412 // Handle Self first, so we can adjust the index to match the AST.
4413 if has_self && i == 0 {
4414 return opt_self_ty.unwrap_or_else(|| {
4415 self.type_var_for_def(span, def, substs)
4418 i -= has_self as usize;
4424 let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
4425 Some(&hir::AngleBracketedParameters(ref data)) => {
4426 (&data.types[..], data.infer_types)
4428 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4429 None => (&[][..], true)
4432 // Skip over the lifetimes in the same segment.
4433 if let Some((_, generics)) = segment {
4434 i -= generics.regions.len();
4437 if let Some(ast_ty) = types.get(i) {
4438 // A provided type parameter.
4440 } else if !infer_types && def.has_default {
4441 // No type parameter provided, but a default exists.
4442 let default = self.tcx.type_of(def.def_id);
4445 default.subst_spanned(self.tcx, substs, Some(span))
4448 // No type parameters were provided, we can infer all.
4449 // This can also be reached in some error cases:
4450 // We prefer to use inference variables instead of
4451 // TyError to let type inference recover somewhat.
4452 self.type_var_for_def(span, def, substs)
4456 // The things we are substituting into the type should not contain
4457 // escaping late-bound regions, and nor should the base type scheme.
4458 let ty = self.tcx.type_of(def.def_id());
4459 assert!(!substs.has_escaping_regions());
4460 assert!(!ty.has_escaping_regions());
4462 // Add all the obligations that are required, substituting and
4463 // normalized appropriately.
4464 let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4465 self.add_obligations_for_parameters(
4466 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4469 // Substitute the values for the type parameters into the type of
4470 // the referenced item.
4471 let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4473 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4474 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4475 // is inherent, there is no `Self` parameter, instead, the impl needs
4476 // type parameters, which we can infer by unifying the provided `Self`
4477 // with the substituted impl type.
4478 let ty = self.tcx.type_of(impl_def_id);
4480 let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4481 match self.at(&self.misc(span), self.param_env).sup(impl_ty, self_ty) {
4482 Ok(ok) => self.register_infer_ok_obligations(ok),
4485 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4492 debug!("instantiate_value_path: type of {:?} is {:?}",
4495 self.write_substs(node_id, substs);
4499 /// Report errors if the provided parameters are too few or too many.
4500 fn check_path_parameter_count(&self,
4502 segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
4503 let (lifetimes, types, infer_types, bindings) = {
4504 match segment.map(|(s, _)| &s.parameters) {
4505 Some(&hir::AngleBracketedParameters(ref data)) => {
4506 (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
4508 Some(&hir::ParenthesizedParameters(_)) => {
4509 AstConv::prohibit_parenthesized_params(self, &segment.as_ref().unwrap().0,
4511 (&[][..], &[][..], true, &[][..])
4513 None => (&[][..], &[][..], true, &[][..])
4517 let count_lifetime_params = |n| {
4518 format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4520 let count_type_params = |n| {
4521 format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4524 // Check provided lifetime parameters.
4525 let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4526 if lifetimes.len() > lifetime_defs.len() {
4527 let expected_text = count_lifetime_params(lifetime_defs.len());
4528 let actual_text = count_lifetime_params(lifetimes.len());
4529 struct_span_err!(self.tcx.sess, span, E0088,
4530 "too many lifetime parameters provided: \
4531 expected at most {}, found {}",
4532 expected_text, actual_text)
4533 .span_label(span, format!("expected {}", expected_text))
4535 } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
4536 let expected_text = count_lifetime_params(lifetime_defs.len());
4537 let actual_text = count_lifetime_params(lifetimes.len());
4538 struct_span_err!(self.tcx.sess, span, E0090,
4539 "too few lifetime parameters provided: \
4540 expected {}, found {}",
4541 expected_text, actual_text)
4542 .span_label(span, format!("expected {}", expected_text))
4546 // The case where there is not enough lifetime parameters is not checked,
4547 // because this is not possible - a function never takes lifetime parameters.
4548 // See discussion for Pull Request 36208.
4550 // Check provided type parameters.
4551 let type_defs = segment.map_or(&[][..], |(_, generics)| {
4552 if generics.parent.is_none() {
4553 &generics.types[generics.has_self as usize..]
4558 let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4559 if types.len() > type_defs.len() {
4560 let span = types[type_defs.len()].span;
4561 let expected_text = count_type_params(type_defs.len());
4562 let actual_text = count_type_params(types.len());
4563 struct_span_err!(self.tcx.sess, span, E0087,
4564 "too many type parameters provided: \
4565 expected at most {}, found {}",
4566 expected_text, actual_text)
4567 .span_label(span, format!("expected {}", expected_text))
4570 // To prevent derived errors to accumulate due to extra
4571 // type parameters, we force instantiate_value_path to
4572 // use inference variables instead of the provided types.
4574 } else if !infer_types && types.len() < required_len {
4575 let expected_text = count_type_params(required_len);
4576 let actual_text = count_type_params(types.len());
4577 struct_span_err!(self.tcx.sess, span, E0089,
4578 "too few type parameters provided: \
4579 expected {}, found {}",
4580 expected_text, actual_text)
4581 .span_label(span, format!("expected {}", expected_text))
4585 if !bindings.is_empty() {
4586 span_err!(self.tcx.sess, bindings[0].span, E0182,
4587 "unexpected binding of associated item in expression path \
4588 (only allowed in type paths)");
4592 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4594 where F: Fn() -> Ty<'tcx>
4596 let mut ty = self.resolve_type_vars_with_obligations(ty);
4599 let alternative = f();
4602 if alternative.is_ty_var() || alternative.references_error() {
4603 if !self.is_tainted_by_errors() {
4604 self.type_error_message(sp, |_actual| {
4605 "the type of this value must be known in this context".to_string()
4608 self.demand_suptype(sp, self.tcx.types.err, ty);
4609 ty = self.tcx.types.err;
4611 self.demand_suptype(sp, alternative, ty);
4619 // Resolves `typ` by a single level if `typ` is a type variable. If no
4620 // resolution is possible, then an error is reported.
4621 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4622 self.structurally_resolve_type_or_else(sp, ty, || {
4627 fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4628 ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4629 -> (BreakableCtxt<'gcx, 'tcx>, R) {
4632 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4633 index = enclosing_breakables.stack.len();
4634 enclosing_breakables.by_id.insert(id, index);
4635 enclosing_breakables.stack.push(ctxt);
4639 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4640 debug_assert!(enclosing_breakables.stack.len() == index + 1);
4641 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4642 enclosing_breakables.stack.pop().expect("missing breakable context")
4648 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4649 generics: &hir::Generics,
4651 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4652 generics.ty_params.len(), ty);
4654 // make a vector of booleans initially false, set to true when used
4655 if generics.ty_params.is_empty() { return; }
4656 let mut tps_used = vec![false; generics.ty_params.len()];
4658 for leaf_ty in ty.walk() {
4659 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4660 debug!("Found use of ty param num {}", idx);
4661 tps_used[idx as usize - generics.lifetimes.len()] = true;
4665 for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4667 struct_span_err!(tcx.sess, param.span, E0091,
4668 "type parameter `{}` is unused",
4670 .span_label(param.span, "unused type parameter")