1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 Within the check phase of type check, we check each item one at a time
16 (bodies of function expressions are checked as part of the containing
17 function). Inference is used to supply types wherever they are
20 By far the most complex case is checking the body of a function. This
21 can be broken down into several distinct phases:
23 - gather: creates type variables to represent the type of each local
24 variable and pattern binding.
26 - main: the main pass does the lion's share of the work: it
27 determines the types of all expressions, resolves
28 methods, checks for most invalid conditions, and so forth. In
29 some cases, where a type is unknown, it may create a type or region
30 variable and use that as the type of an expression.
32 In the process of checking, various constraints will be placed on
33 these type variables through the subtyping relationships requested
34 through the `demand` module. The `infer` module is in charge
35 of resolving those constraints.
37 - regionck: after main is complete, the regionck pass goes over all
38 types looking for regions and making sure that they did not escape
39 into places they are not in scope. This may also influence the
40 final assignments of the various region variables if there is some
43 - vtable: find and records the impls to use for each trait bound that
44 appears on a type parameter.
46 - writeback: writes the final types within a function body, replacing
47 type variables with their final inferred types. These final types
48 are written into the `tcx.node_types` table, which should *never* contain
49 any reference to a type variable.
53 While type checking a function, the intermediate types for the
54 expressions, blocks, and so forth contained within the function are
55 stored in `fcx.node_types` and `fcx.item_substs`. These types
56 may contain unresolved type variables. After type checking is
57 complete, the functions in the writeback module are used to take the
58 types from this table, resolve them, and then write them into their
59 permanent home in the type context `tcx`.
61 This means that during inferencing you should use `fcx.write_ty()`
62 and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
63 nodes within the function.
65 The types of top-level items, which never contain unbound type
66 variables, are stored directly into the `tcx` tables.
68 n.b.: A type variable is not the same thing as a type parameter. A
69 type variable is rather an "instance" of a type parameter: that is,
70 given a generic function `fn foo<T>(t: T)`: while checking the
71 function `foo`, the type `ty_param(0)` refers to the type `T`, which
72 is treated in abstract. When `foo()` is called, however, `T` will be
73 substituted for a fresh type variable `N`. This variable will
74 eventually be resolved to some concrete type (which might itself be
79 pub use self::Expectation::*;
80 use self::coercion::{CoerceMany, DynamicCoerceMany};
81 pub use self::compare_method::{compare_impl_method, compare_const_impl};
82 use self::TupleArgumentsFlag::*;
85 use fmt_macros::{Parser, Piece, Position};
86 use hir::def::{Def, CtorKind};
87 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
88 use rustc_back::slice::ref_slice;
89 use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
90 use rustc::infer::type_variable::{TypeVariableOrigin};
91 use rustc::middle::region::CodeExtent;
92 use rustc::ty::subst::{Kind, Subst, Substs};
93 use rustc::traits::{self, FulfillmentContext, ObligationCause, ObligationCauseCode, Reveal};
94 use rustc::ty::{ParamTy, LvaluePreference, NoPreference, PreferMutLvalue};
95 use rustc::ty::{self, Ty, TyCtxt, Visibility};
96 use rustc::ty::{MethodCall, MethodCallee};
97 use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
98 use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
99 use rustc::ty::maps::Providers;
100 use rustc::ty::util::{Representability, IntTypeExt};
101 use errors::DiagnosticBuilder;
102 use require_c_abi_if_variadic;
103 use session::{Session, CompileResult};
106 use util::common::{ErrorReported, indenter};
107 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
109 use std::cell::{Cell, RefCell};
110 use std::collections::hash_map::Entry;
112 use std::mem::replace;
113 use std::ops::{self, Deref};
114 use syntax::abi::Abi;
116 use syntax::codemap::{self, original_sp, Spanned};
117 use syntax::feature_gate::{GateIssue, emit_feature_err};
119 use syntax::symbol::{Symbol, InternedString, keywords};
120 use syntax::util::lev_distance::find_best_match_for_name;
121 use syntax_pos::{self, BytePos, Span, DUMMY_SP};
123 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
124 use rustc::hir::itemlikevisit::ItemLikeVisitor;
125 use rustc::hir::{self, PatKind};
126 use rustc::middle::lang_items;
127 use rustc_back::slice;
128 use rustc::middle::const_val::eval_length;
129 use rustc_const_math::ConstInt;
148 /// closures defined within the function. For example:
151 /// bar(move|| { ... })
154 /// Here, the function `foo()` and the closure passed to
155 /// `bar()` will each have their own `FnCtxt`, but they will
156 /// share the inherited fields.
157 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
158 infcx: InferCtxt<'a, 'gcx, 'tcx>,
160 locals: RefCell<NodeMap<Ty<'tcx>>>,
162 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
164 // When we process a call like `c()` where `c` is a closure type,
165 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
166 // `FnOnce` closure. In that case, we defer full resolution of the
167 // call until upvar inference can kick in and make the
168 // decision. We keep these deferred resolutions grouped by the
169 // def-id of the closure, so that once we decide, we can easily go
170 // back and process them.
171 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>>>,
173 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
175 // Anonymized types found in explicit return types and their
176 // associated fresh inference variable. Writeback resolves these
177 // variables to get the concrete type, which can be used to
178 // deanonymize TyAnon, after typeck is done with all functions.
179 anon_types: RefCell<NodeMap<Ty<'tcx>>>,
181 /// Each type parameter has an implicit region bound that
182 /// indicates it must outlive at least the function body (the user
183 /// may specify stronger requirements). This field indicates the
184 /// region of the callee. If it is `None`, then the parameter
185 /// environment is for an item or something where the "callee" is
187 implicit_region_bound: Option<ty::Region<'tcx>>,
190 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
191 type Target = InferCtxt<'a, 'gcx, 'tcx>;
192 fn deref(&self) -> &Self::Target {
197 trait DeferredCallResolution<'gcx, 'tcx> {
198 fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>);
201 type DeferredCallResolutionHandler<'gcx, 'tcx> = Box<DeferredCallResolution<'gcx, 'tcx>+'tcx>;
203 /// When type-checking an expression, we propagate downward
204 /// whatever type hint we are able in the form of an `Expectation`.
205 #[derive(Copy, Clone, Debug)]
206 pub enum Expectation<'tcx> {
207 /// We know nothing about what type this expression should have.
210 /// This expression should have the type given (or some subtype)
211 ExpectHasType(Ty<'tcx>),
213 /// This expression will be cast to the `Ty`
214 ExpectCastableToType(Ty<'tcx>),
216 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
217 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
218 ExpectRvalueLikeUnsized(Ty<'tcx>),
221 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
222 // Disregard "castable to" expectations because they
223 // can lead us astray. Consider for example `if cond
224 // {22} else {c} as u8` -- if we propagate the
225 // "castable to u8" constraint to 22, it will pick the
226 // type 22u8, which is overly constrained (c might not
227 // be a u8). In effect, the problem is that the
228 // "castable to" expectation is not the tightest thing
229 // we can say, so we want to drop it in this case.
230 // The tightest thing we can say is "must unify with
231 // else branch". Note that in the case of a "has type"
232 // constraint, this limitation does not hold.
234 // If the expected type is just a type variable, then don't use
235 // an expected type. Otherwise, we might write parts of the type
236 // when checking the 'then' block which are incompatible with the
238 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
240 ExpectHasType(ety) => {
241 let ety = fcx.shallow_resolve(ety);
242 if !ety.is_ty_var() {
248 ExpectRvalueLikeUnsized(ety) => {
249 ExpectRvalueLikeUnsized(ety)
255 /// Provide an expectation for an rvalue expression given an *optional*
256 /// hint, which is not required for type safety (the resulting type might
257 /// be checked higher up, as is the case with `&expr` and `box expr`), but
258 /// is useful in determining the concrete type.
260 /// The primary use case is where the expected type is a fat pointer,
261 /// like `&[isize]`. For example, consider the following statement:
263 /// let x: &[isize] = &[1, 2, 3];
265 /// In this case, the expected type for the `&[1, 2, 3]` expression is
266 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
267 /// expectation `ExpectHasType([isize])`, that would be too strong --
268 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
269 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
270 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
271 /// which still is useful, because it informs integer literals and the like.
272 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
273 /// for examples of where this comes up,.
274 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
275 match fcx.tcx.struct_tail(ty).sty {
276 ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
277 ExpectRvalueLikeUnsized(ty)
279 _ => ExpectHasType(ty)
283 // Resolves `expected` by a single level if it is a variable. If
284 // there is no expected type or resolution is not possible (e.g.,
285 // no constraints yet present), just returns `None`.
286 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
291 ExpectCastableToType(t) => {
292 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
294 ExpectHasType(t) => {
295 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
297 ExpectRvalueLikeUnsized(t) => {
298 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
303 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
304 match self.resolve(fcx) {
305 NoExpectation => None,
306 ExpectCastableToType(ty) |
308 ExpectRvalueLikeUnsized(ty) => Some(ty),
312 /// It sometimes happens that we want to turn an expectation into
313 /// a **hard constraint** (i.e., something that must be satisfied
314 /// for the program to type-check). `only_has_type` will return
315 /// such a constraint, if it exists.
316 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
317 match self.resolve(fcx) {
318 ExpectHasType(ty) => Some(ty),
323 /// Like `only_has_type`, but instead of returning `None` if no
324 /// hard constraint exists, creates a fresh type variable.
325 fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
326 self.only_has_type(fcx)
327 .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
331 #[derive(Copy, Clone)]
332 pub struct UnsafetyState {
333 pub def: ast::NodeId,
334 pub unsafety: hir::Unsafety,
335 pub unsafe_push_count: u32,
340 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
341 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
344 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
345 match self.unsafety {
346 // If this unsafe, then if the outer function was already marked as
347 // unsafe we shouldn't attribute the unsafe'ness to the block. This
348 // way the block can be warned about instead of ignoring this
349 // extraneous block (functions are never warned about).
350 hir::Unsafety::Unsafe if self.from_fn => *self,
353 let (unsafety, def, count) = match blk.rules {
354 hir::PushUnsafeBlock(..) =>
355 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
356 hir::PopUnsafeBlock(..) =>
357 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
358 hir::UnsafeBlock(..) =>
359 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
361 (unsafety, self.def, self.unsafe_push_count),
363 UnsafetyState{ def: def,
365 unsafe_push_count: count,
372 #[derive(Debug, Copy, Clone)]
378 #[derive(Copy, Clone, Debug)]
379 pub struct AdjustedRcvr<'a> {
380 pub rcvr_expr: &'a hir::Expr,
381 pub autoderefs: usize,
385 /// Tracks whether executing a node may exit normally (versus
386 /// return/break/panic, which "diverge", leaving dead code in their
387 /// wake). Tracked semi-automatically (through type variables marked
388 /// as diverging), with some manual adjustments for control-flow
389 /// primitives (approximating a CFG).
390 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
392 /// Potentially unknown, some cases converge,
393 /// others require a CFG to determine them.
396 /// Definitely known to diverge and therefore
397 /// not reach the next sibling or its parent.
400 /// Same as `Always` but with a reachability
401 /// warning already emitted
405 // Convenience impls for combinig `Diverges`.
407 impl ops::BitAnd for Diverges {
409 fn bitand(self, other: Self) -> Self {
410 cmp::min(self, other)
414 impl ops::BitOr for Diverges {
416 fn bitor(self, other: Self) -> Self {
417 cmp::max(self, other)
421 impl ops::BitAndAssign for Diverges {
422 fn bitand_assign(&mut self, other: Self) {
423 *self = *self & other;
427 impl ops::BitOrAssign for Diverges {
428 fn bitor_assign(&mut self, other: Self) {
429 *self = *self | other;
434 fn always(self) -> bool {
435 self >= Diverges::Always
439 pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
442 // this is `null` for loops where break with a value is illegal,
443 // such as `while`, `for`, and `while let`
444 coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>,
447 pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
448 stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
449 by_id: NodeMap<usize>,
452 impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
453 fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
454 let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
455 bug!("could not find enclosing breakable with id {}", target_id);
461 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
462 body_id: ast::NodeId,
464 // Number of errors that had been reported when we started
465 // checking this function. On exit, if we find that *more* errors
466 // have been reported, we will skip regionck and other work that
467 // expects the types within the function to be consistent.
468 err_count_on_creation: usize,
470 ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>,
472 ps: RefCell<UnsafetyState>,
474 /// Whether the last checked node generates a divergence (e.g.,
475 /// `return` will set this to Always). In general, when entering
476 /// an expression or other node in the tree, the initial value
477 /// indicates whether prior parts of the containing expression may
478 /// have diverged. It is then typically set to `Maybe` (and the
479 /// old value remembered) for processing the subparts of the
480 /// current expression. As each subpart is processed, they may set
481 /// the flag to `Always` etc. Finally, at the end, we take the
482 /// result and "union" it with the original value, so that when we
483 /// return the flag indicates if any subpart of the the parent
484 /// expression (up to and including this part) has diverged. So,
485 /// if you read it after evaluating a subexpression `X`, the value
486 /// you get indicates whether any subexpression that was
487 /// evaluating up to and including `X` diverged.
489 /// We use this flag for two purposes:
491 /// - To warn about unreachable code: if, after processing a
492 /// sub-expression but before we have applied the effects of the
493 /// current node, we see that the flag is set to `Always`, we
494 /// can issue a warning. This corresponds to something like
495 /// `foo(return)`; we warn on the `foo()` expression. (We then
496 /// update the flag to `WarnedAlways` to suppress duplicate
497 /// reports.) Similarly, if we traverse to a fresh statement (or
498 /// tail expression) from a `Always` setting, we will isssue a
499 /// warning. This corresponds to something like `{return;
500 /// foo();}` or `{return; 22}`, where we would warn on the
503 /// - To permit assignment into a local variable or other lvalue
504 /// (including the "return slot") of type `!`. This is allowed
505 /// if **either** the type of value being assigned is `!`, which
506 /// means the current code is dead, **or** the expression's
507 /// divering flag is true, which means that a divering value was
508 /// wrapped (e.g., `let x: ! = foo(return)`).
510 /// To repeat the last point: an expression represents dead-code
511 /// if, after checking it, **either** its type is `!` OR the
512 /// diverges flag is set to something other than `Maybe`.
513 diverges: Cell<Diverges>,
515 /// Whether any child nodes have any type errors.
516 has_errors: Cell<bool>,
518 enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
520 inh: &'a Inherited<'a, 'gcx, 'tcx>,
523 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
524 type Target = Inherited<'a, 'gcx, 'tcx>;
525 fn deref(&self) -> &Self::Target {
530 /// Helper type of a temporary returned by Inherited::build(...).
531 /// Necessary because we can't write the following bound:
532 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
533 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
534 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>,
538 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
539 pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId)
540 -> InheritedBuilder<'a, 'gcx, 'tcx> {
541 let tables = ty::TypeckTables::empty();
542 let param_env = tcx.parameter_environment(def_id);
544 infcx: tcx.infer_ctxt((tables, param_env), Reveal::UserFacing),
550 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
551 fn enter<F, R>(&'tcx mut self, f: F) -> R
552 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
554 let def_id = self.def_id;
555 self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
559 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
560 fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> Self {
562 let item_id = tcx.hir.as_local_node_id(def_id);
563 let body_id = item_id.and_then(|id| tcx.hir.maybe_body_owned_by(id));
564 let implicit_region_bound = body_id.map(|body| {
565 tcx.mk_region(ty::ReScope(CodeExtent::CallSiteScope(body)))
570 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
571 locals: RefCell::new(NodeMap()),
572 deferred_call_resolutions: RefCell::new(DefIdMap()),
573 deferred_cast_checks: RefCell::new(Vec::new()),
574 anon_types: RefCell::new(NodeMap()),
575 implicit_region_bound,
579 fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
580 debug!("register_predicate({:?})", obligation);
581 if obligation.has_escaping_regions() {
582 span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
587 .register_predicate_obligation(self, obligation);
590 fn register_predicates(&self, obligations: Vec<traits::PredicateObligation<'tcx>>) {
591 for obligation in obligations {
592 self.register_predicate(obligation);
596 fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
597 self.register_predicates(infer_ok.obligations);
601 fn normalize_associated_types_in<T>(&self,
603 body_id: ast::NodeId,
605 where T : TypeFoldable<'tcx>
607 let ok = self.normalize_associated_types_in_as_infer_ok(span, body_id, value);
608 self.register_infer_ok_obligations(ok)
611 fn normalize_associated_types_in_as_infer_ok<T>(&self,
613 body_id: ast::NodeId,
616 where T : TypeFoldable<'tcx>
618 debug!("normalize_associated_types_in(value={:?})", value);
619 let mut selcx = traits::SelectionContext::new(self);
620 let cause = ObligationCause::misc(span, body_id);
621 let traits::Normalized { value, obligations } =
622 traits::normalize(&mut selcx, cause, value);
623 debug!("normalize_associated_types_in: result={:?} predicates={:?}",
626 InferOk { value, obligations }
629 /// Replace any late-bound regions bound in `value` with
630 /// free variants attached to `all_outlive_scope`.
631 fn liberate_late_bound_regions<T>(&self,
632 all_outlive_scope: DefId,
633 value: &ty::Binder<T>)
635 where T: TypeFoldable<'tcx>
637 self.tcx.replace_late_bound_regions(value, |br| {
638 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
639 scope: all_outlive_scope,
646 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
648 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
649 fn visit_item(&mut self, i: &'tcx hir::Item) {
650 check_item_type(self.tcx, i);
652 fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
653 fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
656 pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
657 tcx.sess.track_errors(|| {
658 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
659 tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor());
663 pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
664 tcx.sess.track_errors(|| {
665 tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx });
669 pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
670 tcx.typeck_item_bodies(LOCAL_CRATE)
673 fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> CompileResult {
674 debug_assert!(crate_num == LOCAL_CRATE);
675 tcx.sess.track_errors(|| {
676 for body_owner_def_id in tcx.body_owners() {
677 tcx.typeck_tables_of(body_owner_def_id);
682 pub fn provide(providers: &mut Providers) {
683 *providers = Providers {
694 fn closure_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
696 -> ty::PolyFnSig<'tcx> {
697 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
698 tcx.typeck_tables_of(def_id).closure_tys[&node_id]
701 fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
704 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
705 tcx.typeck_tables_of(def_id).closure_kinds[&node_id]
708 fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
710 -> Option<ty::Destructor> {
711 tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
714 /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))`
715 /// with information about it's body-id and fn-decl (if any). Otherwise,
718 /// If this function returns "some", then `typeck_tables(def_id)` will
719 /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or
720 /// may not succeed. In some cases where this function returns `None`
721 /// (notably closures), `typeck_tables(def_id)` would wind up
722 /// redirecting to the owning function.
723 fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
725 -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)>
727 match tcx.hir.get(id) {
728 hir::map::NodeItem(item) => {
730 hir::ItemConst(_, body) |
731 hir::ItemStatic(_, _, body) =>
733 hir::ItemFn(ref decl, .., body) =>
734 Some((body, Some(decl))),
739 hir::map::NodeTraitItem(item) => {
741 hir::TraitItemKind::Const(_, Some(body)) =>
743 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) =>
744 Some((body, Some(&sig.decl))),
749 hir::map::NodeImplItem(item) => {
751 hir::ImplItemKind::Const(_, body) =>
753 hir::ImplItemKind::Method(ref sig, body) =>
754 Some((body, Some(&sig.decl))),
759 hir::map::NodeExpr(expr) => {
760 // FIXME(eddyb) Closures should have separate
761 // function definition IDs and expression IDs.
762 // Type-checking should not let closures get
763 // this far in a constant position.
764 // Assume that everything other than closures
765 // is a constant "initializer" expression.
767 hir::ExprClosure(..) =>
770 Some((hir::BodyId { node_id: expr.id }, None)),
777 fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
780 // Closures' tables come from their outermost function,
781 // as they are part of the same "inference environment".
782 let outer_def_id = tcx.closure_base_def_id(def_id);
783 if outer_def_id != def_id {
784 return tcx.has_typeck_tables(outer_def_id);
787 let id = tcx.hir.as_local_node_id(def_id).unwrap();
788 primary_body_of(tcx, id).is_some()
791 fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
793 -> &'tcx ty::TypeckTables<'tcx> {
794 // Closures' tables come from their outermost function,
795 // as they are part of the same "inference environment".
796 let outer_def_id = tcx.closure_base_def_id(def_id);
797 if outer_def_id != def_id {
798 return tcx.typeck_tables_of(outer_def_id);
801 let id = tcx.hir.as_local_node_id(def_id).unwrap();
802 let span = tcx.hir.span(id);
804 // Figure out what primary body this item has.
805 let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| {
806 span_bug!(span, "can't type-check body of {:?}", def_id);
808 let body = tcx.hir.body(body_id);
810 Inherited::build(tcx, def_id).enter(|inh| {
811 let fcx = if let Some(decl) = fn_decl {
812 let fn_sig = tcx.type_of(def_id).fn_sig();
814 check_abi(tcx, span, fn_sig.abi());
816 // Compute the fty from point of view of inside fn.
818 inh.liberate_late_bound_regions(def_id, &fn_sig);
820 inh.normalize_associated_types_in(body.value.span, body_id.node_id, &fn_sig);
822 check_fn(&inh, fn_sig, decl, id, body)
824 let fcx = FnCtxt::new(&inh, body.value.id);
825 let expected_type = tcx.type_of(def_id);
826 let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
827 fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
829 // Gather locals in statics (because of block expressions).
830 // This is technically unnecessary because locals in static items are forbidden,
831 // but prevents type checking from blowing up before const checking can properly
833 GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
835 fcx.check_expr_coercable_to_type(&body.value, expected_type);
840 fcx.select_all_obligations_and_apply_defaults();
841 fcx.closure_analyze(body);
842 fcx.select_obligations_where_possible();
844 fcx.select_all_obligations_or_error();
846 if fn_decl.is_some() {
847 fcx.regionck_fn(id, body);
849 fcx.regionck_expr(body);
852 fcx.resolve_type_vars_in_body(body)
856 fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
857 if !tcx.sess.target.target.is_abi_supported(abi) {
858 struct_span_err!(tcx.sess, span, E0570,
859 "The ABI `{}` is not supported for the current target", abi).emit()
863 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
864 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
867 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
868 fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
871 // infer the variable's type
872 let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
873 self.fcx.locals.borrow_mut().insert(nid, var_ty);
877 // take type that the user specified
878 self.fcx.locals.borrow_mut().insert(nid, typ);
885 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
886 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
887 NestedVisitorMap::None
890 // Add explicitly-declared locals.
891 fn visit_local(&mut self, local: &'gcx hir::Local) {
892 let o_ty = match local.ty {
893 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
896 self.assign(local.span, local.id, o_ty);
897 debug!("Local variable {:?} is assigned type {}",
899 self.fcx.ty_to_string(
900 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
901 intravisit::walk_local(self, local);
904 // Add pattern bindings.
905 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
906 if let PatKind::Binding(_, _, ref path1, _) = p.node {
907 let var_ty = self.assign(p.span, p.id, None);
909 self.fcx.require_type_is_sized(var_ty, p.span,
910 traits::VariableType(p.id));
912 debug!("Pattern binding {} is assigned to {} with type {:?}",
914 self.fcx.ty_to_string(
915 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
918 intravisit::walk_pat(self, p);
921 // Don't descend into the bodies of nested closures
922 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
923 _: hir::BodyId, _: Span, _: ast::NodeId) { }
926 /// Helper used for fns and closures. Does the grungy work of checking a function
927 /// body and returns the function context used for that purpose, since in the case of a fn item
928 /// there is still a bit more to do.
931 /// * inherited: other fields inherited from the enclosing fn (if any)
932 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
933 fn_sig: ty::FnSig<'tcx>,
934 decl: &'gcx hir::FnDecl,
936 body: &'gcx hir::Body)
937 -> FnCtxt<'a, 'gcx, 'tcx>
939 let mut fn_sig = fn_sig.clone();
941 debug!("check_fn(sig={:?}, fn_id={})", fn_sig, fn_id);
943 // Create the function context. This is either derived from scratch or,
944 // in the case of function expressions, based on the outer context.
945 let mut fcx = FnCtxt::new(inherited, body.value.id);
946 *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
948 let ret_ty = fn_sig.output();
949 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
950 let ret_ty = fcx.instantiate_anon_types(&ret_ty);
951 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
952 fn_sig = fcx.tcx.mk_fn_sig(
953 fn_sig.inputs().iter().cloned(),
960 GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
962 // Add formal parameters.
963 for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
964 // The type of the argument must be well-formed.
966 // NB -- this is now checked in wfcheck, but that
967 // currently only results in warnings, so we issue an
968 // old-style WF obligation here so that we still get the
969 // errors that we used to get.
970 fcx.register_old_wf_obligation(arg_ty, arg.pat.span, traits::MiscObligation);
972 // Check the pattern.
973 fcx.check_pat_arg(&arg.pat, arg_ty, true);
974 fcx.write_ty(arg.id, arg_ty);
977 inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig);
979 fcx.check_return_expr(&body.value);
981 // Finalize the return check by taking the LUB of the return types
982 // we saw and assigning it to the expected return type. This isn't
983 // really expected to fail, since the coercions would have failed
984 // earlier when trying to find a LUB.
986 // However, the behavior around `!` is sort of complex. In the
987 // event that the `actual_return_ty` comes back as `!`, that
988 // indicates that the fn either does not return or "returns" only
989 // values of type `!`. In this case, if there is an expected
990 // return type that is *not* `!`, that should be ok. But if the
991 // return type is being inferred, we want to "fallback" to `!`:
993 // let x = move || panic!();
995 // To allow for that, I am creating a type variable with diverging
996 // fallback. This was deemed ever so slightly better than unifying
997 // the return value with `!` because it allows for the caller to
998 // make more assumptions about the return type (e.g., they could do
1000 // let y: Option<u32> = Some(x());
1002 // which would then cause this return type to become `u32`, not
1004 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
1005 let mut actual_return_ty = coercion.complete(&fcx);
1006 if actual_return_ty.is_never() {
1007 actual_return_ty = fcx.next_diverging_ty_var(
1008 TypeVariableOrigin::DivergingFn(body.value.span));
1010 fcx.demand_suptype(body.value.span, ret_ty, actual_return_ty);
1015 fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1018 let def_id = tcx.hir.local_def_id(id);
1019 let def = tcx.adt_def(def_id);
1020 def.destructor(tcx); // force the destructor to be evaluated
1021 check_representable(tcx, span, def_id);
1023 if def.repr.simd() {
1024 check_simd(tcx, span, def_id);
1027 // if struct is packed and not aligned, check fields for alignment.
1028 // Checks for combining packed and align attrs on single struct are done elsewhere.
1029 if tcx.adt_def(def_id).repr.packed() && tcx.adt_def(def_id).repr.align == 0 {
1030 check_packed(tcx, span, def_id);
1034 fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1037 let def_id = tcx.hir.local_def_id(id);
1038 let def = tcx.adt_def(def_id);
1039 def.destructor(tcx); // force the destructor to be evaluated
1040 check_representable(tcx, span, def_id);
1043 pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
1044 debug!("check_item_type(it.id={}, it.name={})",
1046 tcx.item_path_str(tcx.hir.local_def_id(it.id)));
1047 let _indenter = indenter();
1049 // Consts can play a role in type-checking, so they are included here.
1050 hir::ItemStatic(..) |
1051 hir::ItemConst(..) => {
1052 tcx.typeck_tables_of(tcx.hir.local_def_id(it.id));
1054 hir::ItemEnum(ref enum_definition, _) => {
1057 &enum_definition.variants,
1060 hir::ItemFn(..) => {} // entirely within check_item_body
1061 hir::ItemImpl(.., ref impl_item_refs) => {
1062 debug!("ItemImpl {} with id {}", it.name, it.id);
1063 let impl_def_id = tcx.hir.local_def_id(it.id);
1064 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1065 check_impl_items_against_trait(tcx,
1070 let trait_def_id = impl_trait_ref.def_id;
1071 check_on_unimplemented(tcx, trait_def_id, it);
1074 hir::ItemTrait(..) => {
1075 let def_id = tcx.hir.local_def_id(it.id);
1076 check_on_unimplemented(tcx, def_id, it);
1078 hir::ItemStruct(..) => {
1079 check_struct(tcx, it.id, it.span);
1081 hir::ItemUnion(..) => {
1082 check_union(tcx, it.id, it.span);
1084 hir::ItemTy(_, ref generics) => {
1085 let def_id = tcx.hir.local_def_id(it.id);
1086 let pty_ty = tcx.type_of(def_id);
1087 check_bounds_are_used(tcx, generics, pty_ty);
1089 hir::ItemForeignMod(ref m) => {
1090 check_abi(tcx, it.span, m.abi);
1092 if m.abi == Abi::RustIntrinsic {
1093 for item in &m.items {
1094 intrinsic::check_intrinsic_type(tcx, item);
1096 } else if m.abi == Abi::PlatformIntrinsic {
1097 for item in &m.items {
1098 intrinsic::check_platform_intrinsic_type(tcx, item);
1101 for item in &m.items {
1102 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
1103 if !generics.types.is_empty() {
1104 let mut err = struct_span_err!(tcx.sess, item.span, E0044,
1105 "foreign items may not have type parameters");
1106 span_help!(&mut err, item.span,
1107 "consider using specialization instead of \
1112 if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
1113 require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
1118 _ => {/* nothing to do */ }
1122 fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1125 let generics = tcx.generics_of(def_id);
1126 if let Some(ref attr) = item.attrs.iter().find(|a| {
1127 a.check_name("rustc_on_unimplemented")
1129 if let Some(istring) = attr.value_str() {
1130 let istring = istring.as_str();
1131 let parser = Parser::new(&istring);
1132 let types = &generics.types;
1133 for token in parser {
1135 Piece::String(_) => (), // Normal string, no need to check it
1136 Piece::NextArgument(a) => match a.position {
1137 // `{Self}` is allowed
1138 Position::ArgumentNamed(s) if s == "Self" => (),
1139 // So is `{A}` if A is a type parameter
1140 Position::ArgumentNamed(s) => match types.iter().find(|t| {
1145 let name = tcx.item_name(def_id);
1146 span_err!(tcx.sess, attr.span, E0230,
1147 "there is no type parameter \
1152 // `{:1}` and `{}` are not to be used
1153 Position::ArgumentIs(_) => {
1154 span_err!(tcx.sess, attr.span, E0231,
1155 "only named substitution \
1156 parameters are allowed");
1163 tcx.sess, attr.span, E0232,
1164 "this attribute must have a value")
1165 .span_label(attr.span, "attribute requires a value")
1166 .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
1172 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1173 impl_item: &hir::ImplItem,
1176 let mut err = struct_span_err!(
1177 tcx.sess, impl_item.span, E0520,
1178 "`{}` specializes an item from a parent `impl`, but \
1179 that item is not marked `default`",
1181 err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
1184 match tcx.span_of_impl(parent_impl) {
1186 err.span_label(span, "parent `impl` is here");
1187 err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
1191 err.note(&format!("parent implementation is in crate `{}`", cname));
1198 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1199 trait_def: &ty::TraitDef,
1201 impl_item: &hir::ImplItem)
1203 let ancestors = trait_def.ancestors(tcx, impl_id);
1205 let kind = match impl_item.node {
1206 hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
1207 hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
1208 hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
1210 let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
1211 .map(|node_item| node_item.map(|parent| parent.defaultness));
1213 if let Some(parent) = parent {
1214 if tcx.impl_item_is_final(&parent) {
1215 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1221 fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1224 impl_trait_ref: ty::TraitRef<'tcx>,
1225 impl_item_refs: &[hir::ImplItemRef]) {
1226 // If the trait reference itself is erroneous (so the compilation is going
1227 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1228 // isn't populated for such impls.
1229 if impl_trait_ref.references_error() { return; }
1231 // Locate trait definition and items
1232 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1233 let mut overridden_associated_type = None;
1235 let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
1237 // Check existing impl methods to see if they are both present in trait
1238 // and compatible with trait signature
1239 for impl_item in impl_items() {
1240 let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
1241 let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
1242 .find(|ac| ac.name == ty_impl_item.name);
1244 // Check that impl definition matches trait definition
1245 if let Some(ty_trait_item) = ty_trait_item {
1246 match impl_item.node {
1247 hir::ImplItemKind::Const(..) => {
1248 // Find associated const definition.
1249 if ty_trait_item.kind == ty::AssociatedKind::Const {
1250 compare_const_impl(tcx,
1256 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1257 "item `{}` is an associated const, \
1258 which doesn't match its trait `{}`",
1261 err.span_label(impl_item.span, "does not match trait");
1262 // We can only get the spans from local trait definition
1263 // Same for E0324 and E0325
1264 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1265 err.span_label(trait_span, "item in trait");
1270 hir::ImplItemKind::Method(..) => {
1271 let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
1272 if ty_trait_item.kind == ty::AssociatedKind::Method {
1273 let err_count = tcx.sess.err_count();
1274 compare_impl_method(tcx,
1280 true); // start with old-broken-mode
1281 if err_count == tcx.sess.err_count() {
1282 // old broken mode did not report an error. Try with the new mode.
1283 compare_impl_method(tcx,
1289 false); // use the new mode
1292 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1293 "item `{}` is an associated method, \
1294 which doesn't match its trait `{}`",
1297 err.span_label(impl_item.span, "does not match trait");
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::Type(_) => {
1305 if ty_trait_item.kind == ty::AssociatedKind::Type {
1306 if ty_trait_item.defaultness.has_value() {
1307 overridden_associated_type = Some(impl_item);
1310 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1311 "item `{}` is an associated type, \
1312 which doesn't match its trait `{}`",
1315 err.span_label(impl_item.span, "does not match trait");
1316 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1317 err.span_label(trait_span, "item in trait");
1325 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1328 // Check for missing items from trait
1329 let mut missing_items = Vec::new();
1330 let mut invalidated_items = Vec::new();
1331 let associated_type_overridden = overridden_associated_type.is_some();
1332 for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
1333 let is_implemented = trait_def.ancestors(tcx, impl_id)
1334 .defs(tcx, trait_item.name, trait_item.kind)
1336 .map(|node_item| !node_item.node.is_from_trait())
1339 if !is_implemented {
1340 if !trait_item.defaultness.has_value() {
1341 missing_items.push(trait_item);
1342 } else if associated_type_overridden {
1343 invalidated_items.push(trait_item.name);
1348 let signature = |item: &ty::AssociatedItem| {
1350 ty::AssociatedKind::Method => {
1351 format!("{}", tcx.type_of(item.def_id).fn_sig().0)
1353 ty::AssociatedKind::Type => format!("type {};", item.name.to_string()),
1354 ty::AssociatedKind::Const => {
1355 format!("const {}: {:?};", item.name.to_string(), tcx.type_of(item.def_id))
1360 if !missing_items.is_empty() {
1361 let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
1362 "not all trait items implemented, missing: `{}`",
1363 missing_items.iter()
1364 .map(|trait_item| trait_item.name.to_string())
1365 .collect::<Vec<_>>().join("`, `"));
1366 err.span_label(impl_span, format!("missing `{}` in implementation",
1367 missing_items.iter()
1368 .map(|trait_item| trait_item.name.to_string())
1369 .collect::<Vec<_>>().join("`, `")));
1370 for trait_item in missing_items {
1371 if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
1372 err.span_label(span, format!("`{}` from trait", trait_item.name));
1374 err.note(&format!("`{}` from trait: `{}`",
1376 signature(&trait_item)));
1382 if !invalidated_items.is_empty() {
1383 let invalidator = overridden_associated_type.unwrap();
1384 span_err!(tcx.sess, invalidator.span, E0399,
1385 "the following trait items need to be reimplemented \
1386 as `{}` was overridden: `{}`",
1388 invalidated_items.iter()
1389 .map(|name| name.to_string())
1390 .collect::<Vec<_>>().join("`, `"))
1394 /// Checks whether a type can be represented in memory. In particular, it
1395 /// identifies types that contain themselves without indirection through a
1396 /// pointer, which would mean their size is unbounded.
1397 fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1401 let rty = tcx.type_of(item_def_id);
1403 // Check that it is possible to represent this type. This call identifies
1404 // (1) types that contain themselves and (2) types that contain a different
1405 // recursive type. It is only necessary to throw an error on those that
1406 // contain themselves. For case 2, there must be an inner type that will be
1407 // caught by case 1.
1408 match rty.is_representable(tcx, sp) {
1409 Representability::SelfRecursive(spans) => {
1410 let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
1412 err.span_label(span, "recursive without indirection");
1417 Representability::Representable | Representability::ContainsRecursive => (),
1422 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1423 let t = tcx.type_of(def_id);
1425 ty::TyAdt(def, substs) if def.is_struct() => {
1426 let fields = &def.struct_variant().fields;
1427 if fields.is_empty() {
1428 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1431 let e = fields[0].ty(tcx, substs);
1432 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1433 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1434 .span_label(sp, "SIMD elements must have the same type")
1439 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1440 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1442 span_err!(tcx.sess, sp, E0077,
1443 "SIMD vector element type should be machine type");
1452 fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1453 if check_packed_inner(tcx, def_id, &mut Vec::new()) {
1454 struct_span_err!(tcx.sess, sp, E0588,
1455 "packed struct cannot transitively contain a `[repr(align)]` struct").emit();
1459 fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1461 stack: &mut Vec<DefId>) -> bool {
1462 let t = tcx.type_of(def_id);
1463 if stack.contains(&def_id) {
1464 debug!("check_packed_inner: {:?} is recursive", t);
1468 ty::TyAdt(def, substs) if def.is_struct() => {
1469 if tcx.adt_def(def.did).repr.align > 0 {
1472 // push struct def_id before checking fields
1474 for field in &def.struct_variant().fields {
1475 let f = field.ty(tcx, substs);
1477 ty::TyAdt(def, _) => {
1478 if check_packed_inner(tcx, def.did, stack) {
1485 // only need to pop if not early out
1493 #[allow(trivial_numeric_casts)]
1494 pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1496 vs: &'tcx [hir::Variant],
1498 let def_id = tcx.hir.local_def_id(id);
1499 let def = tcx.adt_def(def_id);
1500 def.destructor(tcx); // force the destructor to be evaluated
1502 if vs.is_empty() && tcx.has_attr(def_id, "repr") {
1504 tcx.sess, sp, E0084,
1505 "unsupported representation for zero-variant enum")
1506 .span_label(sp, "unsupported enum representation")
1510 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1511 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1512 if !tcx.sess.features.borrow().i128_type {
1513 emit_feature_err(&tcx.sess.parse_sess,
1514 "i128_type", sp, GateIssue::Language, "128-bit type is unstable");
1519 if let Some(e) = v.node.disr_expr {
1520 tcx.typeck_tables_of(tcx.hir.local_def_id(e.node_id));
1524 let mut disr_vals: Vec<ConstInt> = Vec::new();
1525 for (discr, v) in def.discriminants(tcx).zip(vs) {
1526 // Check for duplicate discriminant values
1527 if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
1528 let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
1529 let variant_i = tcx.hir.expect_variant(variant_i_node_id);
1530 let i_span = match variant_i.node.disr_expr {
1531 Some(expr) => tcx.hir.span(expr.node_id),
1532 None => tcx.hir.span(variant_i_node_id)
1534 let span = match v.node.disr_expr {
1535 Some(expr) => tcx.hir.span(expr.node_id),
1538 struct_span_err!(tcx.sess, span, E0081,
1539 "discriminant value `{}` already exists", disr_vals[i])
1540 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1541 .span_label(span , format!("enum already has `{}`", disr_vals[i]))
1544 disr_vals.push(discr);
1547 check_representable(tcx, sp, def_id);
1550 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1551 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1553 fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
1554 -> ty::GenericPredicates<'tcx>
1557 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1558 let item_id = tcx.hir.ty_param_owner(node_id);
1559 let item_def_id = tcx.hir.local_def_id(item_id);
1560 let generics = tcx.generics_of(item_def_id);
1561 let index = generics.type_param_to_index[&def_id.index];
1562 ty::GenericPredicates {
1564 predicates: self.parameter_environment.caller_bounds.iter().filter(|predicate| {
1566 ty::Predicate::Trait(ref data) => {
1567 data.0.self_ty().is_param(index)
1571 }).cloned().collect()
1575 fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
1576 -> Option<ty::Region<'tcx>> {
1578 Some(def) => infer::EarlyBoundRegion(span, def.name, def.issue_32330),
1579 None => infer::MiscVariable(span)
1581 Some(self.next_region_var(v))
1584 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
1585 self.next_ty_var(TypeVariableOrigin::TypeInference(span))
1588 fn ty_infer_for_def(&self,
1589 ty_param_def: &ty::TypeParameterDef,
1590 substs: &[Kind<'tcx>],
1591 span: Span) -> Ty<'tcx> {
1592 self.type_var_for_def(span, ty_param_def, substs)
1595 fn projected_ty_from_poly_trait_ref(&self,
1597 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1598 item_name: ast::Name)
1601 let (trait_ref, _) =
1602 self.replace_late_bound_regions_with_fresh_var(
1604 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1607 self.tcx().mk_projection(trait_ref, item_name)
1610 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1611 if ty.has_escaping_regions() {
1612 ty // FIXME: normalization and escaping regions
1614 self.normalize_associated_types_in(span, &ty)
1618 fn set_tainted_by_errors(&self) {
1619 self.infcx.set_tainted_by_errors()
1623 /// Controls whether the arguments are tupled. This is used for the call
1626 /// Tupling means that all call-side arguments are packed into a tuple and
1627 /// passed as a single parameter. For example, if tupling is enabled, this
1630 /// fn f(x: (isize, isize))
1632 /// Can be called as:
1639 #[derive(Clone, Eq, PartialEq)]
1640 enum TupleArgumentsFlag {
1645 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1646 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1647 body_id: ast::NodeId)
1648 -> FnCtxt<'a, 'gcx, 'tcx> {
1651 err_count_on_creation: inh.tcx.sess.err_count(),
1653 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
1654 ast::CRATE_NODE_ID)),
1655 diverges: Cell::new(Diverges::Maybe),
1656 has_errors: Cell::new(false),
1657 enclosing_breakables: RefCell::new(EnclosingBreakables {
1665 pub fn sess(&self) -> &Session {
1669 pub fn err_count_since_creation(&self) -> usize {
1670 self.tcx.sess.err_count() - self.err_count_on_creation
1673 /// Produce warning on the given node, if the current point in the
1674 /// function is unreachable, and there hasn't been another warning.
1675 fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
1676 if self.diverges.get() == Diverges::Always {
1677 self.diverges.set(Diverges::WarnedAlways);
1679 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
1681 self.tables.borrow_mut().lints.add_lint(
1682 lint::builtin::UNREACHABLE_CODE,
1684 format!("unreachable {}", kind));
1690 code: ObligationCauseCode<'tcx>)
1691 -> ObligationCause<'tcx> {
1692 ObligationCause::new(span, self.body_id, code)
1695 pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
1696 self.cause(span, ObligationCauseCode::MiscObligation)
1699 /// Resolves type variables in `ty` if possible. Unlike the infcx
1700 /// version (resolve_type_vars_if_possible), this version will
1701 /// also select obligations if it seems useful, in an effort
1702 /// to get more type information.
1703 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1704 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1706 // No TyInfer()? Nothing needs doing.
1707 if !ty.has_infer_types() {
1708 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1712 // If `ty` is a type variable, see whether we already know what it is.
1713 ty = self.resolve_type_vars_if_possible(&ty);
1714 if !ty.has_infer_types() {
1715 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1719 // If not, try resolving pending obligations as much as
1720 // possible. This can help substantially when there are
1721 // indirect dependencies that don't seem worth tracking
1723 self.select_obligations_where_possible();
1724 ty = self.resolve_type_vars_if_possible(&ty);
1726 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1730 fn record_deferred_call_resolution(&self,
1731 closure_def_id: DefId,
1732 r: DeferredCallResolutionHandler<'gcx, 'tcx>) {
1733 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1734 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1737 fn remove_deferred_call_resolutions(&self,
1738 closure_def_id: DefId)
1739 -> Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>
1741 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1742 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(Vec::new())
1745 pub fn tag(&self) -> String {
1746 let self_ptr: *const FnCtxt = self;
1747 format!("{:?}", self_ptr)
1750 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1751 match self.locals.borrow().get(&nid) {
1754 span_bug!(span, "no type for local variable {}",
1755 self.tcx.hir.node_to_string(nid));
1761 pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
1762 debug!("write_ty({}, {:?}) in fcx {}",
1763 node_id, self.resolve_type_vars_if_possible(&ty), self.tag());
1764 self.tables.borrow_mut().node_types.insert(node_id, ty);
1766 if ty.references_error() {
1767 self.has_errors.set(true);
1768 self.set_tainted_by_errors();
1772 pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
1773 if !substs.substs.is_noop() {
1774 debug!("write_substs({}, {:?}) in fcx {}",
1779 self.tables.borrow_mut().item_substs.insert(node_id, substs);
1783 pub fn apply_autoderef_adjustment(&self,
1784 node_id: ast::NodeId,
1786 adjusted_ty: Ty<'tcx>) {
1787 self.apply_adjustment(node_id, Adjustment {
1788 kind: Adjust::DerefRef {
1797 pub fn apply_adjustment(&self, node_id: ast::NodeId, adj: Adjustment<'tcx>) {
1798 debug!("apply_adjustment(node_id={}, adj={:?})", node_id, adj);
1800 if adj.is_identity() {
1804 match self.tables.borrow_mut().adjustments.entry(node_id) {
1805 Entry::Vacant(entry) => { entry.insert(adj); },
1806 Entry::Occupied(mut entry) => {
1807 debug!(" - composing on top of {:?}", entry.get());
1808 let composed_kind = match (entry.get().kind, adj.kind) {
1809 // Applying any adjustment on top of a NeverToAny
1810 // is a valid NeverToAny adjustment, because it can't
1812 (Adjust::NeverToAny, _) => Adjust::NeverToAny,
1815 autoref: Some(AutoBorrow::Ref(..)),
1817 }, Adjust::DerefRef { autoderefs, .. }) if autoderefs > 0 => {
1818 // A reborrow has no effect before a dereference.
1821 // FIXME: currently we never try to compose autoderefs
1822 // and ReifyFnPointer/UnsafeFnPointer, but we could.
1824 bug!("while adjusting {}, can't compose {:?} and {:?}",
1825 node_id, entry.get(), adj)
1827 *entry.get_mut() = Adjustment {
1828 kind: composed_kind,
1835 /// Basically whenever we are converting from a type scheme into
1836 /// the fn body space, we always want to normalize associated
1837 /// types as well. This function combines the two.
1838 fn instantiate_type_scheme<T>(&self,
1840 substs: &Substs<'tcx>,
1843 where T : TypeFoldable<'tcx>
1845 let value = value.subst(self.tcx, substs);
1846 let result = self.normalize_associated_types_in(span, &value);
1847 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1854 /// As `instantiate_type_scheme`, but for the bounds found in a
1855 /// generic type scheme.
1856 fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
1857 -> ty::InstantiatedPredicates<'tcx> {
1858 let bounds = self.tcx.predicates_of(def_id);
1859 let result = bounds.instantiate(self.tcx, substs);
1860 let result = self.normalize_associated_types_in(span, &result);
1861 debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
1868 /// Replace all anonymized types with fresh inference variables
1869 /// and record them for writeback.
1870 fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
1871 value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
1872 if let ty::TyAnon(def_id, substs) = ty.sty {
1873 // Use the same type variable if the exact same TyAnon appears more
1874 // than once in the return type (e.g. if it's pased to a type alias).
1875 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1876 if let Some(ty_var) = self.anon_types.borrow().get(&id) {
1879 let span = self.tcx.def_span(def_id);
1880 let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
1881 self.anon_types.borrow_mut().insert(id, ty_var);
1883 let predicates_of = self.tcx.predicates_of(def_id);
1884 let bounds = predicates_of.instantiate(self.tcx, substs);
1886 for predicate in bounds.predicates {
1887 // Change the predicate to refer to the type variable,
1888 // which will be the concrete type, instead of the TyAnon.
1889 // This also instantiates nested `impl Trait`.
1890 let predicate = self.instantiate_anon_types(&predicate);
1892 // Require that the predicate holds for the concrete type.
1893 let cause = traits::ObligationCause::new(span, self.body_id,
1894 traits::ReturnType);
1895 self.register_predicate(traits::Obligation::new(cause, predicate));
1905 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1906 where T : TypeFoldable<'tcx>
1908 let ok = self.normalize_associated_types_in_as_infer_ok(span, value);
1909 self.register_infer_ok_obligations(ok)
1912 fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T)
1914 where T : TypeFoldable<'tcx>
1916 self.inh.normalize_associated_types_in_as_infer_ok(span, self.body_id, value)
1919 pub fn write_nil(&self, node_id: ast::NodeId) {
1920 self.write_ty(node_id, self.tcx.mk_nil());
1923 pub fn write_error(&self, node_id: ast::NodeId) {
1924 self.write_ty(node_id, self.tcx.types.err);
1927 pub fn require_type_meets(&self,
1930 code: traits::ObligationCauseCode<'tcx>,
1933 self.register_bound(
1936 traits::ObligationCause::new(span, self.body_id, code));
1939 pub fn require_type_is_sized(&self,
1942 code: traits::ObligationCauseCode<'tcx>)
1944 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1945 self.require_type_meets(ty, span, code, lang_item);
1948 pub fn register_bound(&self,
1951 cause: traits::ObligationCause<'tcx>)
1953 self.fulfillment_cx.borrow_mut()
1954 .register_bound(self, ty, def_id, cause);
1957 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
1958 let t = AstConv::ast_ty_to_ty(self, ast_t);
1959 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1963 pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
1964 match self.tables.borrow().node_types.get(&id) {
1966 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1968 bug!("no type for node {}: {} in fcx {}",
1969 id, self.tcx.hir.node_to_string(id),
1975 pub fn opt_node_ty_substs<F>(&self,
1978 F: FnOnce(&ty::ItemSubsts<'tcx>),
1980 if let Some(s) = self.tables.borrow().item_substs.get(&id) {
1985 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1986 /// outlive the region `r`.
1987 pub fn register_region_obligation(&self,
1989 region: ty::Region<'tcx>,
1990 cause: traits::ObligationCause<'tcx>)
1992 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
1993 fulfillment_cx.register_region_obligation(ty, region, cause);
1996 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1997 /// outlive the region `r`.
1998 pub fn register_wf_obligation(&self,
2001 code: traits::ObligationCauseCode<'tcx>)
2003 // WF obligations never themselves fail, so no real need to give a detailed cause:
2004 let cause = traits::ObligationCause::new(span, self.body_id, code);
2005 self.register_predicate(traits::Obligation::new(cause, 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, 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.ty.fn_ret();
2173 let ret_ty = self.tcx.no_late_bound_regions(&ret_ty).unwrap();
2175 // method returns &T, but the type as visible to user is T, so deref
2176 ret_ty.builtin_deref(true, NoPreference).unwrap()
2179 fn lookup_indexing(&self,
2181 base_expr: &'gcx hir::Expr,
2184 lvalue_pref: LvaluePreference)
2185 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2187 // FIXME(#18741) -- this is almost but not quite the same as the
2188 // autoderef that normal method probing does. They could likely be
2191 let mut autoderef = self.autoderef(base_expr.span, base_ty);
2193 while let Some((adj_ty, autoderefs)) = autoderef.next() {
2194 if let Some(final_mt) = self.try_index_step(
2195 MethodCall::expr(expr.id), expr, Some(AdjustedRcvr {
2196 rcvr_expr: base_expr,
2199 }), base_expr.span, adj_ty, lvalue_pref, idx_ty)
2201 autoderef.finalize(lvalue_pref, base_expr);
2202 return Some(final_mt);
2205 if let ty::TyArray(element_ty, _) = adj_ty.sty {
2206 autoderef.finalize(lvalue_pref, base_expr);
2207 let adj_ty = self.tcx.mk_slice(element_ty);
2208 return self.try_index_step(
2209 MethodCall::expr(expr.id), expr, Some(AdjustedRcvr {
2210 rcvr_expr: base_expr,
2213 }), base_expr.span, adj_ty, lvalue_pref, idx_ty)
2216 autoderef.unambiguous_final_ty();
2220 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2221 /// (and otherwise adjust) `base_expr`, looking for a type which either
2222 /// supports builtin indexing or overloaded indexing.
2223 /// This loop implements one step in that search; the autoderef loop
2224 /// is implemented by `lookup_indexing`.
2225 fn try_index_step(&self,
2226 method_call: MethodCall,
2228 base_expr: Option<AdjustedRcvr>,
2230 adjusted_ty: Ty<'tcx>,
2231 lvalue_pref: LvaluePreference,
2233 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2236 debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
2243 let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_span));
2245 // First, try built-in indexing.
2246 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2247 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2248 debug!("try_index_step: success, using built-in indexing");
2249 // If we had `[T; N]`, we should've caught it before unsizing to `[T]`.
2250 if let Some(base_expr) = base_expr {
2251 assert!(!base_expr.unsize);
2252 self.apply_autoderef_adjustment(
2253 base_expr.rcvr_expr.id, base_expr.autoderefs, adjusted_ty);
2255 return Some((tcx.types.usize, ty));
2260 // If some lookup succeeds, write callee into table and extract index/element
2261 // type from the method signature.
2262 // If some lookup succeeded, install method in table
2263 let method = self.try_overloaded_lvalue_op(
2264 expr.span, base_expr, adjusted_ty, &[input_ty], lvalue_pref, LvalueOp::Index);
2267 debug!("try_index_step: success, using overloaded indexing");
2268 let method = self.register_infer_ok_obligations(ok);
2269 self.tables.borrow_mut().method_map.insert(method_call, method);
2270 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2274 fn resolve_lvalue_op(&self, op: LvalueOp, is_mut: bool) -> (Option<DefId>, Symbol) {
2275 let (tr, name) = match (op, is_mut) {
2276 (LvalueOp::Deref, false) =>
2277 (self.tcx.lang_items.deref_trait(), "deref"),
2278 (LvalueOp::Deref, true) =>
2279 (self.tcx.lang_items.deref_mut_trait(), "deref_mut"),
2280 (LvalueOp::Index, false) =>
2281 (self.tcx.lang_items.index_trait(), "index"),
2282 (LvalueOp::Index, true) =>
2283 (self.tcx.lang_items.index_mut_trait(), "index_mut"),
2285 (tr, Symbol::intern(name))
2288 fn try_overloaded_lvalue_op(&self,
2290 base_expr: Option<AdjustedRcvr>,
2292 arg_tys: &[Ty<'tcx>],
2293 lvalue_pref: LvaluePreference,
2295 -> Option<InferOk<'tcx, MethodCallee<'tcx>>>
2297 debug!("try_overloaded_lvalue_op({:?},{:?},{:?},{:?},{:?})",
2304 // Try Mut first, if preferred.
2305 let (mut_tr, mut_op) = self.resolve_lvalue_op(op, true);
2306 let method = match (lvalue_pref, mut_tr) {
2307 (PreferMutLvalue, Some(trait_did)) => {
2308 self.lookup_method_in_trait_adjusted(span,
2313 Some(arg_tys.to_owned()))
2318 // Otherwise, fall back to the immutable version.
2319 let (imm_tr, imm_op) = self.resolve_lvalue_op(op, false);
2320 let method = match (method, imm_tr) {
2321 (None, Some(trait_did)) => {
2322 self.lookup_method_in_trait_adjusted(span,
2327 Some(arg_tys.to_owned()))
2329 (method, _) => method,
2335 fn check_method_argument_types(&self,
2337 method_fn_ty: Ty<'tcx>,
2338 callee_expr: &'gcx hir::Expr,
2339 args_no_rcvr: &'gcx [hir::Expr],
2340 tuple_arguments: TupleArgumentsFlag,
2341 expected: Expectation<'tcx>)
2343 if method_fn_ty.references_error() {
2344 let err_inputs = self.err_args(args_no_rcvr.len());
2346 let err_inputs = match tuple_arguments {
2347 DontTupleArguments => err_inputs,
2348 TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
2351 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2352 false, tuple_arguments, None);
2355 match method_fn_ty.sty {
2356 ty::TyFnDef(def_id, .., ref fty) => {
2357 // HACK(eddyb) ignore self in the definition (see above).
2358 let expected_arg_tys = self.expected_inputs_for_expected_output(
2362 &fty.0.inputs()[1..]
2364 self.check_argument_types(sp, &fty.0.inputs()[1..], &expected_arg_tys[..],
2365 args_no_rcvr, fty.0.variadic, tuple_arguments,
2366 self.tcx.hir.span_if_local(def_id));
2370 span_bug!(callee_expr.span, "method without bare fn type");
2376 /// Generic function that factors out common logic from function calls,
2377 /// method calls and overloaded operators.
2378 fn check_argument_types(&self,
2380 fn_inputs: &[Ty<'tcx>],
2381 expected_arg_tys: &[Ty<'tcx>],
2382 args: &'gcx [hir::Expr],
2384 tuple_arguments: TupleArgumentsFlag,
2385 def_span: Option<Span>) {
2388 // Grab the argument types, supplying fresh type variables
2389 // if the wrong number of arguments were supplied
2390 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2396 // All the input types from the fn signature must outlive the call
2397 // so as to validate implied bounds.
2398 for &fn_input_ty in fn_inputs {
2399 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2402 let mut expected_arg_tys = expected_arg_tys;
2403 let expected_arg_count = fn_inputs.len();
2405 let sp_args = if args.len() > 0 {
2406 let (first, args) = args.split_at(1);
2407 let mut sp_tmp = first[0].span;
2409 let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
2410 if ! sp_opt.is_some() {
2413 sp_tmp = sp_opt.unwrap();
2420 fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
2421 arg_count: usize, error_code: &str, variadic: bool,
2422 def_span: Option<Span>) {
2423 let mut err = sess.struct_span_err_with_code(sp,
2424 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2425 if variadic {"at least "} else {""},
2427 if expected_count == 1 {""} else {"s"},
2429 if arg_count == 1 {" was"} else {"s were"}),
2432 err.span_label(sp, format!("expected {}{} parameter{}",
2433 if variadic {"at least "} else {""},
2435 if expected_count == 1 {""} else {"s"}));
2436 if let Some(def_s) = def_span {
2437 err.span_label(def_s, "defined here");
2442 let formal_tys = if tuple_arguments == TupleArguments {
2443 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2444 match tuple_type.sty {
2445 ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
2446 parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
2447 "E0057", false, def_span);
2448 expected_arg_tys = &[];
2449 self.err_args(args.len())
2451 ty::TyTuple(arg_types, _) => {
2452 expected_arg_tys = match expected_arg_tys.get(0) {
2453 Some(&ty) => match ty.sty {
2454 ty::TyTuple(ref tys, _) => &tys,
2462 span_err!(tcx.sess, sp, E0059,
2463 "cannot use call notation; the first type parameter \
2464 for the function trait is neither a tuple nor unit");
2465 expected_arg_tys = &[];
2466 self.err_args(args.len())
2469 } else if expected_arg_count == supplied_arg_count {
2471 } else if variadic {
2472 if supplied_arg_count >= expected_arg_count {
2475 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2476 supplied_arg_count, "E0060", true, def_span);
2477 expected_arg_tys = &[];
2478 self.err_args(supplied_arg_count)
2481 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2482 supplied_arg_count, "E0061", false, def_span);
2483 expected_arg_tys = &[];
2484 self.err_args(supplied_arg_count)
2487 debug!("check_argument_types: formal_tys={:?}",
2488 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2490 // Check the arguments.
2491 // We do this in a pretty awful way: first we typecheck any arguments
2492 // that are not closures, then we typecheck the closures. This is so
2493 // that we have more information about the types of arguments when we
2494 // typecheck the functions. This isn't really the right way to do this.
2495 for &check_closures in &[false, true] {
2496 debug!("check_closures={}", check_closures);
2498 // More awful hacks: before we check argument types, try to do
2499 // an "opportunistic" vtable resolution of any trait bounds on
2500 // the call. This helps coercions.
2502 self.select_obligations_where_possible();
2505 // For variadic functions, we don't have a declared type for all of
2506 // the arguments hence we only do our usual type checking with
2507 // the arguments who's types we do know.
2508 let t = if variadic {
2510 } else if tuple_arguments == TupleArguments {
2515 for (i, arg) in args.iter().take(t).enumerate() {
2516 // Warn only for the first loop (the "no closures" one).
2517 // Closure arguments themselves can't be diverging, but
2518 // a previous argument can, e.g. `foo(panic!(), || {})`.
2519 if !check_closures {
2520 self.warn_if_unreachable(arg.id, arg.span, "expression");
2523 let is_closure = match arg.node {
2524 hir::ExprClosure(..) => true,
2528 if is_closure != check_closures {
2532 debug!("checking the argument");
2533 let formal_ty = formal_tys[i];
2535 // The special-cased logic below has three functions:
2536 // 1. Provide as good of an expected type as possible.
2537 let expected = expected_arg_tys.get(i).map(|&ty| {
2538 Expectation::rvalue_hint(self, ty)
2541 let checked_ty = self.check_expr_with_expectation(
2543 expected.unwrap_or(ExpectHasType(formal_ty)));
2545 // 2. Coerce to the most detailed type that could be coerced
2546 // to, which is `expected_ty` if `rvalue_hint` returns an
2547 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2548 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2549 self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
2551 // 3. Relate the expected type and the formal one,
2552 // if the expected type was used for the coercion.
2553 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2557 // We also need to make sure we at least write the ty of the other
2558 // arguments which we skipped above.
2560 for arg in args.iter().skip(expected_arg_count) {
2561 let arg_ty = self.check_expr(&arg);
2563 // There are a few types which get autopromoted when passed via varargs
2564 // in C but we just error out instead and require explicit casts.
2565 let arg_ty = self.structurally_resolved_type(arg.span,
2568 ty::TyFloat(ast::FloatTy::F32) => {
2569 self.type_error_message(arg.span, |t| {
2570 format!("can't pass an `{}` to variadic \
2571 function, cast to `c_double`", t)
2574 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2575 self.type_error_message(arg.span, |t| {
2576 format!("can't pass `{}` to variadic \
2577 function, cast to `c_int`",
2581 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2582 self.type_error_message(arg.span, |t| {
2583 format!("can't pass `{}` to variadic \
2584 function, cast to `c_uint`",
2588 ty::TyFnDef(.., f) => {
2589 let ptr_ty = self.tcx.mk_fn_ptr(f);
2590 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2591 self.type_error_message(arg.span,
2593 format!("can't pass `{}` to variadic \
2594 function, cast to `{}`", t, ptr_ty)
2603 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2604 (0..len).map(|_| self.tcx.types.err).collect()
2607 // AST fragment checking
2610 expected: Expectation<'tcx>)
2616 ast::LitKind::Str(..) => tcx.mk_static_str(),
2617 ast::LitKind::ByteStr(ref v) => {
2618 tcx.mk_imm_ref(tcx.types.re_static,
2619 tcx.mk_array(tcx.types.u8, v.len()))
2621 ast::LitKind::Byte(_) => tcx.types.u8,
2622 ast::LitKind::Char(_) => tcx.types.char,
2623 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2624 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2625 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2626 let opt_ty = expected.to_option(self).and_then(|ty| {
2628 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2629 ty::TyChar => Some(tcx.types.u8),
2630 ty::TyRawPtr(..) => Some(tcx.types.usize),
2631 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2635 opt_ty.unwrap_or_else(
2636 || tcx.mk_int_var(self.next_int_var_id()))
2638 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2639 ast::LitKind::FloatUnsuffixed(_) => {
2640 let opt_ty = expected.to_option(self).and_then(|ty| {
2642 ty::TyFloat(_) => Some(ty),
2646 opt_ty.unwrap_or_else(
2647 || tcx.mk_float_var(self.next_float_var_id()))
2649 ast::LitKind::Bool(_) => tcx.types.bool
2653 fn check_expr_eq_type(&self,
2654 expr: &'gcx hir::Expr,
2655 expected: Ty<'tcx>) {
2656 let ty = self.check_expr_with_hint(expr, expected);
2657 self.demand_eqtype(expr.span, expected, ty);
2660 pub fn check_expr_has_type(&self,
2661 expr: &'gcx hir::Expr,
2662 expected: Ty<'tcx>) -> Ty<'tcx> {
2663 let mut ty = self.check_expr_with_hint(expr, expected);
2665 // While we don't allow *arbitrary* coercions here, we *do* allow
2666 // coercions from ! to `expected`.
2668 assert!(!self.tables.borrow().adjustments.contains_key(&expr.id),
2669 "expression with never type wound up being adjusted");
2670 let adj_ty = self.next_diverging_ty_var(
2671 TypeVariableOrigin::AdjustmentType(expr.span));
2672 self.apply_adjustment(expr.id, Adjustment {
2673 kind: Adjust::NeverToAny,
2679 self.demand_suptype(expr.span, expected, ty);
2683 fn check_expr_coercable_to_type(&self,
2684 expr: &'gcx hir::Expr,
2685 expected: Ty<'tcx>) -> Ty<'tcx> {
2686 let ty = self.check_expr_with_hint(expr, expected);
2687 self.demand_coerce(expr, ty, expected);
2691 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2692 expected: Ty<'tcx>) -> Ty<'tcx> {
2693 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2696 fn check_expr_with_expectation(&self,
2697 expr: &'gcx hir::Expr,
2698 expected: Expectation<'tcx>) -> Ty<'tcx> {
2699 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2702 fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
2703 self.check_expr_with_expectation(expr, NoExpectation)
2706 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2707 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2708 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2711 // determine the `self` type, using fresh variables for all variables
2712 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2713 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2715 pub fn impl_self_ty(&self,
2716 span: Span, // (potential) receiver for this impl
2718 -> TypeAndSubsts<'tcx> {
2719 let ity = self.tcx.type_of(did);
2720 debug!("impl_self_ty: ity={:?}", ity);
2722 let substs = self.fresh_substs_for_item(span, did);
2723 let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
2725 TypeAndSubsts { substs: substs, ty: substd_ty }
2728 /// Unifies the output type with the expected type early, for more coercions
2729 /// and forward type information on the input expressions.
2730 fn expected_inputs_for_expected_output(&self,
2732 expected_ret: Expectation<'tcx>,
2733 formal_ret: Ty<'tcx>,
2734 formal_args: &[Ty<'tcx>])
2736 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2737 self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
2738 // Attempt to apply a subtyping relationship between the formal
2739 // return type (likely containing type variables if the function
2740 // is polymorphic) and the expected return type.
2741 // No argument expectations are produced if unification fails.
2742 let origin = self.misc(call_span);
2743 let ures = self.sub_types(false, &origin, formal_ret, ret_ty);
2745 // FIXME(#15760) can't use try! here, FromError doesn't default
2746 // to identity so the resulting type is not constrained.
2749 // Process any obligations locally as much as
2750 // we can. We don't care if some things turn
2751 // out unconstrained or ambiguous, as we're
2752 // just trying to get hints here.
2753 let result = self.save_and_restore_in_snapshot_flag(|_| {
2754 let mut fulfill = FulfillmentContext::new();
2755 let ok = ok; // FIXME(#30046)
2756 for obligation in ok.obligations {
2757 fulfill.register_predicate_obligation(self, obligation);
2759 fulfill.select_where_possible(self)
2764 Err(_) => return Err(()),
2767 Err(_) => return Err(()),
2770 // Record all the argument types, with the substitutions
2771 // produced from the above subtyping unification.
2772 Ok(formal_args.iter().map(|ty| {
2773 self.resolve_type_vars_if_possible(ty)
2776 }).unwrap_or(vec![]);
2777 debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
2778 formal_args, formal_ret,
2779 expected_args, expected_ret);
2783 // Checks a method call.
2784 fn check_method_call(&self,
2785 expr: &'gcx hir::Expr,
2786 method_name: Spanned<ast::Name>,
2787 args: &'gcx [hir::Expr],
2789 expected: Expectation<'tcx>,
2790 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2791 let rcvr = &args[0];
2792 let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2794 // no need to check for bot/err -- callee does that
2795 let expr_t = self.structurally_resolved_type(expr.span, rcvr_t);
2797 let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2798 let fn_ty = match self.lookup_method(method_name.span,
2805 let method_ty = method.ty;
2806 let method_call = MethodCall::expr(expr.id);
2807 self.tables.borrow_mut().method_map.insert(method_call, method);
2811 if method_name.node != keywords::Invalid.name() {
2812 self.report_method_error(method_name.span,
2819 self.write_error(expr.id);
2824 // Call the generic checker.
2825 let ret_ty = self.check_method_argument_types(method_name.span, fn_ty,
2833 fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
2837 .unwrap_or_else(|| span_bug!(return_expr.span,
2838 "check_return_expr called outside fn body"));
2840 let ret_ty = ret_coercion.borrow().expected_ty();
2841 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
2842 ret_coercion.borrow_mut()
2844 &self.misc(return_expr.span),
2847 self.diverges.get());
2851 // A generic function for checking the then and else in an if
2853 fn check_then_else(&self,
2854 cond_expr: &'gcx hir::Expr,
2855 then_expr: &'gcx hir::Expr,
2856 opt_else_expr: Option<&'gcx hir::Expr>,
2858 expected: Expectation<'tcx>) -> Ty<'tcx> {
2859 let cond_ty = self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2860 let cond_diverges = self.diverges.get();
2861 self.diverges.set(Diverges::Maybe);
2863 let expected = expected.adjust_for_branches(self);
2864 let then_ty = self.check_expr_with_expectation(then_expr, expected);
2865 let then_diverges = self.diverges.get();
2866 self.diverges.set(Diverges::Maybe);
2868 // We've already taken the expected type's preferences
2869 // into account when typing the `then` branch. To figure
2870 // out the initial shot at a LUB, we thus only consider
2871 // `expected` if it represents a *hard* constraint
2872 // (`only_has_type`); otherwise, we just go with a
2873 // fresh type variable.
2874 let coerce_to_ty = expected.coercion_target_type(self, sp);
2875 let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty);
2877 let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
2878 coerce.coerce(self, &if_cause, then_expr, then_ty, then_diverges);
2880 if let Some(else_expr) = opt_else_expr {
2881 let else_ty = self.check_expr_with_expectation(else_expr, expected);
2882 let else_diverges = self.diverges.get();
2884 coerce.coerce(self, &if_cause, else_expr, else_ty, else_diverges);
2886 // We won't diverge unless both branches do (or the condition does).
2887 self.diverges.set(cond_diverges | then_diverges & else_diverges);
2889 let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
2890 coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true);
2892 // If the condition is false we can't diverge.
2893 self.diverges.set(cond_diverges);
2896 let result_ty = coerce.complete(self);
2897 if cond_ty.references_error() {
2904 // Check field access expressions
2905 fn check_field(&self,
2906 expr: &'gcx hir::Expr,
2907 lvalue_pref: LvaluePreference,
2908 base: &'gcx hir::Expr,
2909 field: &Spanned<ast::Name>) -> Ty<'tcx> {
2910 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2911 let expr_t = self.structurally_resolved_type(expr.span,
2913 let mut private_candidate = None;
2914 let mut autoderef = self.autoderef(expr.span, expr_t);
2915 while let Some((base_t, autoderefs)) = autoderef.next() {
2917 ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
2918 debug!("struct named {:?}", base_t);
2919 if let Some(field) = base_def.struct_variant().find_field_named(field.node) {
2920 let field_ty = self.field_ty(expr.span, field, substs);
2921 if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
2922 autoderef.finalize(lvalue_pref, base);
2923 self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
2925 self.tcx.check_stability(field.did, expr.id, expr.span);
2929 private_candidate = Some((base_def.did, field_ty));
2935 autoderef.unambiguous_final_ty();
2937 if let Some((did, field_ty)) = private_candidate {
2938 let struct_path = self.tcx().item_path_str(did);
2939 let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
2940 let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
2941 // Also check if an accessible method exists, which is often what is meant.
2942 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2943 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2948 } else if field.node == keywords::Invalid.name() {
2949 self.tcx().types.err
2950 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2951 self.type_error_struct(field.span, |actual| {
2952 format!("attempted to take value of method `{}` on type \
2953 `{}`", field.node, actual)
2955 .help("maybe a `()` to call it is missing? \
2956 If not, try an anonymous function")
2958 self.tcx().types.err
2960 let mut err = self.type_error_struct(field.span, |actual| {
2961 format!("no field `{}` on type `{}`",
2965 ty::TyAdt(def, _) if !def.is_enum() => {
2966 if let Some(suggested_field_name) =
2967 Self::suggest_field_name(def.struct_variant(), field, vec![]) {
2968 err.span_label(field.span,
2969 format!("did you mean `{}`?", suggested_field_name));
2971 err.span_label(field.span,
2975 ty::TyRawPtr(..) => {
2976 err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
2978 self.tcx.hir.node_to_pretty_string(base.id),
2984 self.tcx().types.err
2988 // Return an hint about the closest match in field names
2989 fn suggest_field_name(variant: &'tcx ty::VariantDef,
2990 field: &Spanned<ast::Name>,
2991 skip : Vec<InternedString>)
2993 let name = field.node.as_str();
2994 let names = variant.fields.iter().filter_map(|field| {
2995 // ignore already set fields and private fields from non-local crates
2996 if skip.iter().any(|x| *x == field.name.as_str()) ||
2997 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
3004 // only find fits with at least one matching letter
3005 find_best_match_for_name(names, &name, Some(name.len()))
3008 // Check tuple index expressions
3009 fn check_tup_field(&self,
3010 expr: &'gcx hir::Expr,
3011 lvalue_pref: LvaluePreference,
3012 base: &'gcx hir::Expr,
3013 idx: codemap::Spanned<usize>) -> Ty<'tcx> {
3014 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
3015 let expr_t = self.structurally_resolved_type(expr.span,
3017 let mut private_candidate = None;
3018 let mut tuple_like = false;
3019 let mut autoderef = self.autoderef(expr.span, expr_t);
3020 while let Some((base_t, autoderefs)) = autoderef.next() {
3021 let field = match base_t.sty {
3022 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
3023 tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
3024 if !tuple_like { continue }
3026 debug!("tuple struct named {:?}", base_t);
3027 base_def.struct_variant().fields.get(idx.node).and_then(|field| {
3028 let field_ty = self.field_ty(expr.span, field, substs);
3029 private_candidate = Some((base_def.did, field_ty));
3030 if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
3031 self.tcx.check_stability(field.did, expr.id, expr.span);
3038 ty::TyTuple(ref v, _) => {
3040 v.get(idx.node).cloned()
3045 if let Some(field_ty) = field {
3046 autoderef.finalize(lvalue_pref, base);
3047 self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
3051 autoderef.unambiguous_final_ty();
3053 if let Some((did, field_ty)) = private_candidate {
3054 let struct_path = self.tcx().item_path_str(did);
3055 let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3056 self.tcx().sess.span_err(expr.span, &msg);
3060 self.type_error_message(
3064 format!("attempted out-of-bounds tuple index `{}` on \
3069 format!("attempted tuple index `{}` on type `{}`, but the \
3070 type was not a tuple or tuple struct",
3077 self.tcx().types.err
3080 fn report_unknown_field(&self,
3082 variant: &'tcx ty::VariantDef,
3084 skip_fields: &[hir::Field],
3086 let mut err = self.type_error_struct_with_diag(
3088 |actual| match ty.sty {
3089 ty::TyAdt(adt, ..) if adt.is_enum() => {
3090 struct_span_err!(self.tcx.sess, field.name.span, E0559,
3091 "{} `{}::{}` has no field named `{}`",
3092 kind_name, actual, variant.name, field.name.node)
3095 struct_span_err!(self.tcx.sess, field.name.span, E0560,
3096 "{} `{}` has no field named `{}`",
3097 kind_name, actual, field.name.node)
3101 // prevent all specified fields from being suggested
3102 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3103 if let Some(field_name) = Self::suggest_field_name(variant,
3105 skip_fields.collect()) {
3106 err.span_label(field.name.span,
3107 format!("field does not exist - did you mean `{}`?", field_name));
3110 ty::TyAdt(adt, ..) if adt.is_enum() => {
3111 err.span_label(field.name.span, format!("`{}::{}` does not have this field",
3115 err.span_label(field.name.span, format!("`{}` does not have this field", ty));
3122 fn check_expr_struct_fields(&self,
3124 expected: Expectation<'tcx>,
3125 expr_id: ast::NodeId,
3127 variant: &'tcx ty::VariantDef,
3128 ast_fields: &'gcx [hir::Field],
3129 check_completeness: bool) {
3133 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3134 .get(0).cloned().unwrap_or(adt_ty);
3136 let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
3137 (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
3138 (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
3140 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3143 let mut remaining_fields = FxHashMap();
3144 for field in &variant.fields {
3145 remaining_fields.insert(field.name, field);
3148 let mut seen_fields = FxHashMap();
3150 let mut error_happened = false;
3152 // Typecheck each field.
3153 for field in ast_fields {
3154 let final_field_type;
3155 let field_type_hint;
3157 if let Some(v_field) = remaining_fields.remove(&field.name.node) {
3158 final_field_type = self.field_ty(field.span, v_field, substs);
3159 field_type_hint = self.field_ty(field.span, v_field, hint_substs);
3161 seen_fields.insert(field.name.node, field.span);
3163 // we don't look at stability attributes on
3164 // struct-like enums (yet...), but it's definitely not
3165 // a bug to have construct one.
3166 if adt_kind != ty::AdtKind::Enum {
3167 tcx.check_stability(v_field.did, expr_id, field.span);
3170 error_happened = true;
3171 final_field_type = tcx.types.err;
3172 field_type_hint = tcx.types.err;
3173 if let Some(_) = variant.find_field_named(field.name.node) {
3174 let mut err = struct_span_err!(self.tcx.sess,
3177 "field `{}` specified more than once",
3180 err.span_label(field.name.span, "used more than once");
3182 if let Some(prev_span) = seen_fields.get(&field.name.node) {
3183 err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
3188 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3192 // Make sure to give a type to the field even if there's
3193 // an error, so we can continue typechecking
3194 let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
3195 self.demand_coerce(&field.expr, ty, final_field_type);
3198 // Make sure the programmer specified correct number of fields.
3199 if kind_name == "union" {
3200 if ast_fields.len() != 1 {
3201 tcx.sess.span_err(span, "union expressions should have exactly one field");
3203 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3204 let len = remaining_fields.len();
3206 let mut displayable_field_names = remaining_fields
3208 .map(|x| x.as_str())
3209 .collect::<Vec<_>>();
3211 displayable_field_names.sort();
3213 let truncated_fields_error = if len <= 3 {
3216 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3219 let remaining_fields_names = displayable_field_names.iter().take(3)
3220 .map(|n| format!("`{}`", n))
3221 .collect::<Vec<_>>()
3224 struct_span_err!(tcx.sess, span, E0063,
3225 "missing field{} {}{} in initializer of `{}`",
3226 if remaining_fields.len() == 1 {""} else {"s"},
3227 remaining_fields_names,
3228 truncated_fields_error,
3230 .span_label(span, format!("missing {}{}",
3231 remaining_fields_names,
3232 truncated_fields_error))
3237 fn check_struct_fields_on_error(&self,
3238 fields: &'gcx [hir::Field],
3239 base_expr: &'gcx Option<P<hir::Expr>>) {
3240 for field in fields {
3241 self.check_expr(&field.expr);
3245 self.check_expr(&base);
3251 pub fn check_struct_path(&self,
3253 node_id: ast::NodeId)
3254 -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
3255 let path_span = match *qpath {
3256 hir::QPath::Resolved(_, ref path) => path.span,
3257 hir::QPath::TypeRelative(ref qself, _) => qself.span
3259 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3260 let variant = match def {
3262 self.set_tainted_by_errors();
3265 Def::Variant(..) => {
3267 ty::TyAdt(adt, substs) => {
3268 Some((adt.variant_of_def(def), adt.did, substs))
3270 _ => bug!("unexpected type: {:?}", ty.sty)
3273 Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3274 Def::AssociatedTy(..) | Def::SelfTy(..) => {
3276 ty::TyAdt(adt, substs) if !adt.is_enum() => {
3277 Some((adt.struct_variant(), adt.did, substs))
3282 _ => bug!("unexpected definition: {:?}", def)
3285 if let Some((variant, did, substs)) = variant {
3286 // Check bounds on type arguments used in the path.
3287 let bounds = self.instantiate_bounds(path_span, did, substs);
3288 let cause = traits::ObligationCause::new(path_span, self.body_id,
3289 traits::ItemObligation(did));
3290 self.add_obligations_for_parameters(cause, &bounds);
3294 struct_span_err!(self.tcx.sess, path_span, E0071,
3295 "expected struct, variant or union type, found {}",
3296 ty.sort_string(self.tcx))
3297 .span_label(path_span, "not a struct")
3303 fn check_expr_struct(&self,
3305 expected: Expectation<'tcx>,
3307 fields: &'gcx [hir::Field],
3308 base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3310 // Find the relevant variant
3311 let (variant, struct_ty) =
3312 if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3315 self.check_struct_fields_on_error(fields, base_expr);
3316 return self.tcx.types.err;
3319 let path_span = match *qpath {
3320 hir::QPath::Resolved(_, ref path) => path.span,
3321 hir::QPath::TypeRelative(ref qself, _) => qself.span
3324 self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3325 base_expr.is_none());
3326 if let &Some(ref base_expr) = base_expr {
3327 self.check_expr_has_type(base_expr, struct_ty);
3328 match struct_ty.sty {
3329 ty::TyAdt(adt, substs) if adt.is_struct() => {
3330 self.tables.borrow_mut().fru_field_types.insert(
3332 adt.struct_variant().fields.iter().map(|f| {
3333 self.normalize_associated_types_in(
3334 expr.span, &f.ty(self.tcx, substs)
3340 span_err!(self.tcx.sess, base_expr.span, E0436,
3341 "functional record update syntax requires a struct");
3345 self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3351 /// If an expression has any sub-expressions that result in a type error,
3352 /// inspecting that expression's type with `ty.references_error()` will return
3353 /// true. Likewise, if an expression is known to diverge, inspecting its
3354 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3355 /// strict, _|_ can appear in the type of an expression that does not,
3356 /// itself, diverge: for example, fn() -> _|_.)
3357 /// Note that inspecting a type's structure *directly* may expose the fact
3358 /// that there are actually multiple representations for `TyError`, so avoid
3359 /// that when err needs to be handled differently.
3360 fn check_expr_with_expectation_and_lvalue_pref(&self,
3361 expr: &'gcx hir::Expr,
3362 expected: Expectation<'tcx>,
3363 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3364 debug!(">> typechecking: expr={:?} expected={:?}",
3367 // Warn for expressions after diverging siblings.
3368 self.warn_if_unreachable(expr.id, expr.span, "expression");
3370 // Hide the outer diverging and has_errors flags.
3371 let old_diverges = self.diverges.get();
3372 let old_has_errors = self.has_errors.get();
3373 self.diverges.set(Diverges::Maybe);
3374 self.has_errors.set(false);
3376 let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3378 // Warn for non-block expressions with diverging children.
3381 hir::ExprLoop(..) | hir::ExprWhile(..) |
3382 hir::ExprIf(..) | hir::ExprMatch(..) => {}
3384 _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3387 // Any expression that produces a value of type `!` must have diverged
3389 self.diverges.set(self.diverges.get() | Diverges::Always);
3392 // Record the type, which applies it effects.
3393 // We need to do this after the warning above, so that
3394 // we don't warn for the diverging expression itself.
3395 self.write_ty(expr.id, ty);
3397 // Combine the diverging and has_error flags.
3398 self.diverges.set(self.diverges.get() | old_diverges);
3399 self.has_errors.set(self.has_errors.get() | old_has_errors);
3401 debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3402 debug!("... {:?}, expected is {:?}", ty, expected);
3407 fn check_expr_kind(&self,
3408 expr: &'gcx hir::Expr,
3409 expected: Expectation<'tcx>,
3410 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3414 hir::ExprBox(ref subexpr) => {
3415 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3417 ty::TyAdt(def, _) if def.is_box()
3418 => Expectation::rvalue_hint(self, ty.boxed_ty()),
3422 let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3423 tcx.mk_box(referent_ty)
3426 hir::ExprLit(ref lit) => {
3427 self.check_lit(&lit, expected)
3429 hir::ExprBinary(op, ref lhs, ref rhs) => {
3430 self.check_binop(expr, op, lhs, rhs)
3432 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3433 self.check_binop_assign(expr, op, lhs, rhs)
3435 hir::ExprUnary(unop, ref oprnd) => {
3436 let expected_inner = match unop {
3437 hir::UnNot | hir::UnNeg => {
3444 let lvalue_pref = match unop {
3445 hir::UnDeref => lvalue_pref,
3448 let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3452 if !oprnd_t.references_error() {
3455 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3457 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3459 } else if let Some(ok) = self.try_overloaded_deref(
3460 expr.span, Some(&oprnd), oprnd_t, lvalue_pref) {
3461 let method = self.register_infer_ok_obligations(ok);
3462 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3463 self.tables.borrow_mut().method_map.insert(MethodCall::expr(expr.id),
3466 self.type_error_message(expr.span, |actual| {
3467 format!("type `{}` cannot be \
3468 dereferenced", actual)
3470 oprnd_t = tcx.types.err;
3474 oprnd_t = self.structurally_resolved_type(oprnd.span,
3476 let result = self.check_user_unop("!", "not",
3477 tcx.lang_items.not_trait(),
3478 expr, &oprnd, oprnd_t, unop);
3479 // If it's builtin, we can reuse the type, this helps inference.
3480 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3485 oprnd_t = self.structurally_resolved_type(oprnd.span,
3487 let result = self.check_user_unop("-", "neg",
3488 tcx.lang_items.neg_trait(),
3489 expr, &oprnd, oprnd_t, unop);
3490 // If it's builtin, we can reuse the type, this helps inference.
3491 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3499 hir::ExprAddrOf(mutbl, ref oprnd) => {
3500 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3502 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3503 if self.tcx.expr_is_lval(&oprnd) {
3504 // Lvalues may legitimately have unsized types.
3505 // For example, dereferences of a fat pointer and
3506 // the last field of a struct can be unsized.
3507 ExpectHasType(mt.ty)
3509 Expectation::rvalue_hint(self, mt.ty)
3515 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3516 let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3518 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3519 if tm.ty.references_error() {
3522 // Note: at this point, we cannot say what the best lifetime
3523 // is to use for resulting pointer. We want to use the
3524 // shortest lifetime possible so as to avoid spurious borrowck
3525 // errors. Moreover, the longest lifetime will depend on the
3526 // precise details of the value whose address is being taken
3527 // (and how long it is valid), which we don't know yet until type
3528 // inference is complete.
3530 // Therefore, here we simply generate a region variable. The
3531 // region inferencer will then select the ultimate value.
3532 // Finally, borrowck is charged with guaranteeing that the
3533 // value whose address was taken can actually be made to live
3534 // as long as it needs to live.
3535 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3536 tcx.mk_ref(region, tm)
3539 hir::ExprPath(ref qpath) => {
3540 let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3541 expr.id, expr.span);
3542 let ty = if def != Def::Err {
3543 self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3545 self.set_tainted_by_errors();
3549 // We always require that the type provided as the value for
3550 // a type parameter outlives the moment of instantiation.
3551 self.opt_node_ty_substs(expr.id, |item_substs| {
3552 self.add_wf_bounds(&item_substs.substs, expr);
3557 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3558 for output in outputs {
3559 self.check_expr(output);
3561 for input in inputs {
3562 self.check_expr(input);
3566 hir::ExprBreak(destination, ref expr_opt) => {
3567 if let Some(target_id) = destination.target_id.opt_id() {
3568 let (e_ty, e_diverges, cause);
3569 if let Some(ref e) = *expr_opt {
3570 // If this is a break with a value, we need to type-check
3571 // the expression. Get an expected type from the loop context.
3572 let opt_coerce_to = {
3573 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3574 enclosing_breakables.find_breakable(target_id)
3577 .map(|coerce| coerce.expected_ty())
3580 // If the loop context is not a `loop { }`, then break with
3581 // a value is illegal, and `opt_coerce_to` will be `None`.
3582 // Just set expectation to error in that case.
3583 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3585 // Recurse without `enclosing_breakables` borrowed.
3586 e_ty = self.check_expr_with_hint(e, coerce_to);
3587 e_diverges = self.diverges.get();
3588 cause = self.misc(e.span);
3590 // Otherwise, this is a break *without* a value. That's
3591 // always legal, and is equivalent to `break ()`.
3592 e_ty = tcx.mk_nil();
3593 e_diverges = Diverges::Maybe;
3594 cause = self.misc(expr.span);
3597 // Now that we have type-checked `expr_opt`, borrow
3598 // the `enclosing_loops` field and let's coerce the
3599 // type of `expr_opt` into what is expected.
3600 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3601 let ctxt = enclosing_breakables.find_breakable(target_id);
3602 if let Some(ref mut coerce) = ctxt.coerce {
3603 if let Some(ref e) = *expr_opt {
3604 coerce.coerce(self, &cause, e, e_ty, e_diverges);
3606 assert!(e_ty.is_nil());
3607 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
3610 // If `ctxt.coerce` is `None`, we can just ignore
3611 // the type of the expresison. This is because
3612 // either this was a break *without* a value, in
3613 // which case it is always a legal type (`()`), or
3614 // else an error would have been flagged by the
3615 // `loops` pass for using break with an expression
3616 // where you are not supposed to.
3617 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3620 ctxt.may_break = true;
3622 // Otherwise, we failed to find the enclosing loop;
3623 // this can only happen if the `break` was not
3624 // inside a loop at all, which is caught by the
3625 // loop-checking pass.
3626 assert!(self.tcx.sess.err_count() > 0);
3629 // the type of a `break` is always `!`, since it diverges
3632 hir::ExprAgain(_) => { tcx.types.never }
3633 hir::ExprRet(ref expr_opt) => {
3634 if self.ret_coercion.is_none() {
3635 struct_span_err!(self.tcx.sess, expr.span, E0572,
3636 "return statement outside of function body").emit();
3637 } else if let Some(ref e) = *expr_opt {
3638 self.check_return_expr(e);
3640 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3641 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3642 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
3646 hir::ExprAssign(ref lhs, ref rhs) => {
3647 let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3650 if !tcx.expr_is_lval(&lhs) {
3652 tcx.sess, expr.span, E0070,
3653 "invalid left-hand side expression")
3656 "left-hand of expression not valid")
3660 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3662 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3664 if lhs_ty.references_error() || rhs_ty.references_error() {
3670 hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3671 self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3672 expr.span, expected)
3674 hir::ExprWhile(ref cond, ref body, _) => {
3675 let ctxt = BreakableCtxt {
3676 // cannot use break with a value from a while loop
3681 self.with_breakable_ctxt(expr.id, ctxt, || {
3682 self.check_expr_has_type(&cond, tcx.types.bool);
3683 let cond_diverging = self.diverges.get();
3684 self.check_block_no_value(&body);
3686 // We may never reach the body so it diverging means nothing.
3687 self.diverges.set(cond_diverging);
3692 hir::ExprLoop(ref body, _, source) => {
3693 let coerce = match source {
3694 // you can only use break with a value from a normal `loop { }`
3695 hir::LoopSource::Loop => {
3696 let coerce_to = expected.coercion_target_type(self, body.span);
3697 Some(CoerceMany::new(coerce_to))
3700 hir::LoopSource::WhileLet |
3701 hir::LoopSource::ForLoop => {
3706 let ctxt = BreakableCtxt {
3708 may_break: false, // will get updated if/when we find a `break`
3711 let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3712 self.check_block_no_value(&body);
3716 // No way to know whether it's diverging because
3717 // of a `break` or an outer `break` or `return.
3718 self.diverges.set(Diverges::Maybe);
3721 // If we permit break with a value, then result type is
3722 // the LUB of the breaks (possibly ! if none); else, it
3723 // is nil. This makes sense because infinite loops
3724 // (which would have type !) are only possible iff we
3725 // permit break with a value [1].
3726 assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3727 ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3729 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3730 self.check_match(expr, &discrim, arms, expected, match_src)
3732 hir::ExprClosure(capture, ref decl, body_id, _) => {
3733 self.check_expr_closure(expr, capture, &decl, body_id, expected)
3735 hir::ExprBlock(ref body) => {
3736 self.check_block_with_expected(&body, expected)
3738 hir::ExprCall(ref callee, ref args) => {
3739 self.check_call(expr, &callee, args, expected)
3741 hir::ExprMethodCall(name, ref tps, ref args) => {
3742 self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
3744 hir::ExprCast(ref e, ref t) => {
3745 // Find the type of `e`. Supply hints based on the type we are casting to,
3747 let t_cast = self.to_ty(t);
3748 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3749 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3750 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3751 let diverges = self.diverges.get();
3753 // Eagerly check for some obvious errors.
3754 if t_expr.references_error() || t_cast.references_error() {
3757 // Defer other checks until we're done type checking.
3758 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3759 match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
3761 deferred_cast_checks.push(cast_check);
3764 Err(ErrorReported) => {
3770 hir::ExprType(ref e, ref t) => {
3771 let typ = self.to_ty(&t);
3772 self.check_expr_eq_type(&e, typ);
3775 hir::ExprArray(ref args) => {
3776 let uty = expected.to_option(self).and_then(|uty| {
3778 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3783 let element_ty = if !args.is_empty() {
3784 let coerce_to = uty.unwrap_or_else(
3785 || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3786 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
3787 assert_eq!(self.diverges.get(), Diverges::Maybe);
3789 let e_ty = self.check_expr_with_hint(e, coerce_to);
3790 let cause = self.misc(e.span);
3791 coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
3793 coerce.complete(self)
3795 self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3797 tcx.mk_array(element_ty, args.len())
3799 hir::ExprRepeat(ref element, count) => {
3800 let count = eval_length(self.tcx, count, "repeat count")
3803 let uty = match expected {
3804 ExpectHasType(uty) => {
3806 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3813 let (element_ty, t) = match uty {
3815 self.check_expr_coercable_to_type(&element, uty);
3819 let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3820 let element_ty = self.check_expr_has_type(&element, t);
3826 // For [foo, ..n] where n > 1, `foo` must have
3828 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3829 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3832 if element_ty.references_error() {
3835 tcx.mk_array(t, count)
3838 hir::ExprTup(ref elts) => {
3839 let flds = expected.only_has_type(self).and_then(|ty| {
3841 ty::TyTuple(ref flds, _) => Some(&flds[..]),
3846 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3847 let t = match flds {
3848 Some(ref fs) if i < fs.len() => {
3850 self.check_expr_coercable_to_type(&e, ety);
3854 self.check_expr_with_expectation(&e, NoExpectation)
3859 let tuple = tcx.mk_tup(elt_ts_iter, false);
3860 if tuple.references_error() {
3866 hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3867 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3869 hir::ExprField(ref base, ref field) => {
3870 self.check_field(expr, lvalue_pref, &base, field)
3872 hir::ExprTupField(ref base, idx) => {
3873 self.check_tup_field(expr, lvalue_pref, &base, idx)
3875 hir::ExprIndex(ref base, ref idx) => {
3876 let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3877 let idx_t = self.check_expr(&idx);
3879 if base_t.references_error() {
3881 } else if idx_t.references_error() {
3884 let base_t = self.structurally_resolved_type(expr.span, base_t);
3885 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3886 Some((index_ty, element_ty)) => {
3887 self.demand_coerce(idx, idx_t, index_ty);
3891 let mut err = self.type_error_struct(
3894 format!("cannot index a value of type `{}`",
3898 // Try to give some advice about indexing tuples.
3899 if let ty::TyTuple(..) = base_t.sty {
3900 let mut needs_note = true;
3901 // If the index is an integer, we can show the actual
3902 // fixed expression:
3903 if let hir::ExprLit(ref lit) = idx.node {
3904 if let ast::LitKind::Int(i,
3905 ast::LitIntType::Unsuffixed) = lit.node {
3906 let snip = tcx.sess.codemap().span_to_snippet(base.span);
3907 if let Ok(snip) = snip {
3908 err.span_suggestion(expr.span,
3909 "to access tuple elements, use",
3910 format!("{}.{}", snip, i));
3916 err.help("to access tuple elements, use tuple indexing \
3917 syntax (e.g. `tuple.0`)");
3929 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3930 // The newly resolved definition is written into `type_relative_path_defs`.
3931 fn finish_resolving_struct_path(&self,
3934 node_id: ast::NodeId)
3938 hir::QPath::Resolved(ref maybe_qself, ref path) => {
3939 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
3940 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
3943 hir::QPath::TypeRelative(ref qself, ref segment) => {
3944 let ty = self.to_ty(qself);
3946 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
3951 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
3954 // Write back the new resolution.
3955 self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
3962 // Resolve associated value path into a base type and associated constant or method definition.
3963 // The newly resolved definition is written into `type_relative_path_defs`.
3964 pub fn resolve_ty_and_def_ufcs<'b>(&self,
3965 qpath: &'b hir::QPath,
3966 node_id: ast::NodeId,
3968 -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3970 let (ty, item_segment) = match *qpath {
3971 hir::QPath::Resolved(ref opt_qself, ref path) => {
3973 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
3974 &path.segments[..]);
3976 hir::QPath::TypeRelative(ref qself, ref segment) => {
3977 (self.to_ty(qself), segment)
3980 let item_name = item_segment.name;
3981 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3984 let def = match error {
3985 method::MethodError::PrivateMatch(def) => def,
3988 if item_name != keywords::Invalid.name() {
3989 self.report_method_error(span, ty, item_name, None, error, None);
3995 // Write back the new resolution.
3996 self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
3997 (def, Some(ty), slice::ref_slice(&**item_segment))
4000 pub fn check_decl_initializer(&self,
4001 local: &'gcx hir::Local,
4002 init: &'gcx hir::Expr) -> Ty<'tcx>
4004 let ref_bindings = local.pat.contains_ref_binding();
4006 let local_ty = self.local_ty(init.span, local.id);
4007 if let Some(m) = ref_bindings {
4008 // Somewhat subtle: if we have a `ref` binding in the pattern,
4009 // we want to avoid introducing coercions for the RHS. This is
4010 // both because it helps preserve sanity and, in the case of
4011 // ref mut, for soundness (issue #23116). In particular, in
4012 // the latter case, we need to be clear that the type of the
4013 // referent for the reference that results is *equal to* the
4014 // type of the lvalue it is referencing, and not some
4015 // supertype thereof.
4016 let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
4017 self.demand_eqtype(init.span, init_ty, local_ty);
4020 self.check_expr_coercable_to_type(init, local_ty)
4024 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
4025 let t = self.local_ty(local.span, local.id);
4026 self.write_ty(local.id, t);
4028 if let Some(ref init) = local.init {
4029 let init_ty = self.check_decl_initializer(local, &init);
4030 if init_ty.references_error() {
4031 self.write_ty(local.id, init_ty);
4035 self.check_pat(&local.pat, t);
4036 let pat_ty = self.node_ty(local.pat.id);
4037 if pat_ty.references_error() {
4038 self.write_ty(local.id, pat_ty);
4042 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4043 // Don't do all the complex logic below for DeclItem.
4045 hir::StmtDecl(ref decl, id) => {
4047 hir::DeclLocal(_) => {}
4048 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);
4065 let (node_id, _span) = match stmt.node {
4066 hir::StmtDecl(ref decl, id) => {
4067 let span = match decl.node {
4068 hir::DeclLocal(ref l) => {
4069 self.check_decl_local(&l);
4072 hir::DeclItem(_) => {/* ignore for now */
4078 hir::StmtExpr(ref expr, id) => {
4079 // Check with expected type of ()
4080 self.check_expr_has_type(&expr, self.tcx.mk_nil());
4083 hir::StmtSemi(ref expr, id) => {
4084 self.check_expr(&expr);
4089 if self.has_errors.get() {
4090 self.write_error(node_id);
4092 self.write_nil(node_id);
4095 // Combine the diverging and has_error flags.
4096 self.diverges.set(self.diverges.get() | old_diverges);
4097 self.has_errors.set(self.has_errors.get() | old_has_errors);
4100 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
4101 let unit = self.tcx.mk_nil();
4102 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4104 // if the block produces a `!` value, that can always be
4105 // (effectively) coerced to unit.
4107 self.demand_suptype(blk.span, unit, ty);
4111 fn check_block_with_expected(&self,
4112 blk: &'gcx hir::Block,
4113 expected: Expectation<'tcx>) -> Ty<'tcx> {
4115 let mut fcx_ps = self.ps.borrow_mut();
4116 let unsafety_state = fcx_ps.recurse(blk);
4117 replace(&mut *fcx_ps, unsafety_state)
4120 // In some cases, blocks have just one exit, but other blocks
4121 // can be targeted by multiple breaks. This cannot happen in
4122 // normal Rust syntax today, but it can happen when we desugar
4123 // a `do catch { ... }` expression.
4127 // 'a: { if true { break 'a Err(()); } Ok(()) }
4129 // Here we would wind up with two coercions, one from
4130 // `Err(())` and the other from the tail expression
4131 // `Ok(())`. If the tail expression is omitted, that's a
4132 // "forced unit" -- unless the block diverges, in which
4133 // case we can ignore the tail expression (e.g., `'a: {
4134 // break 'a 22; }` would not force the type of the block
4136 let tail_expr = blk.expr.as_ref();
4137 let coerce_to_ty = expected.coercion_target_type(self, blk.span);
4138 let coerce = if blk.targeted_by_break {
4139 CoerceMany::new(coerce_to_ty)
4141 let tail_expr: &[P<hir::Expr>] = match tail_expr {
4142 Some(e) => ref_slice(e),
4145 CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
4148 let ctxt = BreakableCtxt {
4149 coerce: Some(coerce),
4153 let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
4154 for s in &blk.stmts {
4158 // check the tail expression **without** holding the
4159 // `enclosing_breakables` lock below.
4160 let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
4162 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4163 let mut ctxt = enclosing_breakables.find_breakable(blk.id);
4164 let mut coerce = ctxt.coerce.as_mut().unwrap();
4165 if let Some(tail_expr_ty) = tail_expr_ty {
4166 let tail_expr = tail_expr.unwrap();
4168 &self.misc(tail_expr.span),
4171 self.diverges.get());
4173 // Subtle: if there is no explicit tail expression,
4174 // that is typically equivalent to a tail expression
4175 // of `()` -- except if the block diverges. In that
4176 // case, there is no value supplied from the tail
4177 // expression (assuming there are no other breaks,
4178 // this implies that the type of the block will be
4181 // #41425 -- label the implicit `()` as being the
4182 // "found type" here, rather than the "expected type".
4183 if !self.diverges.get().always() {
4184 coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
4185 if let Some(expected_ty) = expected.only_has_type(self) {
4186 self.consider_hint_about_removing_semicolon(blk,
4195 let mut ty = ctxt.coerce.unwrap().complete(self);
4197 if self.has_errors.get() || ty.references_error() {
4198 ty = self.tcx.types.err
4201 self.write_ty(blk.id, ty);
4203 *self.ps.borrow_mut() = prev;
4207 /// A common error is to add an extra semicolon:
4210 /// fn foo() -> usize {
4215 /// This routine checks if the final statement in a block is an
4216 /// expression with an explicit semicolon whose type is compatible
4217 /// with `expected_ty`. If so, it suggests removing the semicolon.
4218 fn consider_hint_about_removing_semicolon(&self,
4219 blk: &'gcx hir::Block,
4220 expected_ty: Ty<'tcx>,
4221 err: &mut DiagnosticBuilder) {
4222 // Be helpful when the user wrote `{... expr;}` and
4223 // taking the `;` off is enough to fix the error.
4224 let last_stmt = match blk.stmts.last() {
4228 let last_expr = match last_stmt.node {
4229 hir::StmtSemi(ref e, _) => e,
4232 let last_expr_ty = self.expr_ty(last_expr);
4233 if self.can_sub_types(last_expr_ty, expected_ty).is_err() {
4236 let original_span = original_sp(last_stmt.span, blk.span);
4237 let span_semi = Span {
4238 lo: original_span.hi - BytePos(1),
4239 hi: original_span.hi,
4240 ctxt: original_span.ctxt,
4242 err.span_help(span_semi, "consider removing this semicolon:");
4245 // Instantiates the given path, which must refer to an item with the given
4246 // number of type parameters and type.
4247 pub fn instantiate_value_path(&self,
4248 segments: &[hir::PathSegment],
4249 opt_self_ty: Option<Ty<'tcx>>,
4252 node_id: ast::NodeId)
4254 debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4259 // We need to extract the type parameters supplied by the user in
4260 // the path `path`. Due to the current setup, this is a bit of a
4261 // tricky-process; the problem is that resolve only tells us the
4262 // end-point of the path resolution, and not the intermediate steps.
4263 // Luckily, we can (at least for now) deduce the intermediate steps
4264 // just from the end-point.
4266 // There are basically four cases to consider:
4268 // 1. Reference to a constructor of enum variant or struct:
4270 // struct Foo<T>(...)
4271 // enum E<T> { Foo(...) }
4273 // In these cases, the parameters are declared in the type
4276 // 2. Reference to a fn item or a free constant:
4280 // In this case, the path will again always have the form
4281 // `a::b::foo::<T>` where only the final segment should have
4282 // type parameters. However, in this case, those parameters are
4283 // declared on a value, and hence are in the `FnSpace`.
4285 // 3. Reference to a method or an associated constant:
4287 // impl<A> SomeStruct<A> {
4291 // Here we can have a path like
4292 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4293 // may appear in two places. The penultimate segment,
4294 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4295 // final segment, `foo::<B>` contains parameters in fn space.
4297 // 4. Reference to a local variable
4299 // Local variables can't have any type parameters.
4301 // The first step then is to categorize the segments appropriately.
4303 assert!(!segments.is_empty());
4305 let mut ufcs_associated = None;
4306 let mut type_segment = None;
4307 let mut fn_segment = None;
4309 // Case 1. Reference to a struct/variant constructor.
4310 Def::StructCtor(def_id, ..) |
4311 Def::VariantCtor(def_id, ..) => {
4312 // Everything but the final segment should have no
4313 // parameters at all.
4314 let mut generics = self.tcx.generics_of(def_id);
4315 if let Some(def_id) = generics.parent {
4316 // Variant and struct constructors use the
4317 // generics of their parent type definition.
4318 generics = self.tcx.generics_of(def_id);
4320 type_segment = Some((segments.last().unwrap(), generics));
4323 // Case 2. Reference to a top-level value.
4325 Def::Const(def_id) |
4326 Def::Static(def_id, _) => {
4327 fn_segment = Some((segments.last().unwrap(),
4328 self.tcx.generics_of(def_id)));
4331 // Case 3. Reference to a method or associated const.
4332 Def::Method(def_id) |
4333 Def::AssociatedConst(def_id) => {
4334 let container = self.tcx.associated_item(def_id).container;
4336 ty::TraitContainer(trait_did) => {
4337 callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4339 ty::ImplContainer(_) => {}
4342 let generics = self.tcx.generics_of(def_id);
4343 if segments.len() >= 2 {
4344 let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
4345 type_segment = Some((&segments[segments.len() - 2], parent_generics));
4347 // `<T>::assoc` will end up here, and so can `T::assoc`.
4348 let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4349 ufcs_associated = Some((container, self_ty));
4351 fn_segment = Some((segments.last().unwrap(), generics));
4354 // Case 4. Local variable, no generics.
4355 Def::Local(..) | Def::Upvar(..) => {}
4357 _ => bug!("unexpected definition: {:?}", def),
4360 debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4362 // Now that we have categorized what space the parameters for each
4363 // segment belong to, let's sort out the parameters that the user
4364 // provided (if any) into their appropriate spaces. We'll also report
4365 // errors if type parameters are provided in an inappropriate place.
4366 let poly_segments = type_segment.is_some() as usize +
4367 fn_segment.is_some() as usize;
4368 AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4371 Def::Local(def_id) | Def::Upvar(def_id, ..) => {
4372 let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
4373 let ty = self.local_ty(span, nid);
4374 let ty = self.normalize_associated_types_in(span, &ty);
4375 self.write_ty(node_id, ty);
4376 self.write_substs(node_id, ty::ItemSubsts {
4377 substs: self.tcx.intern_substs(&[])
4384 // Now we have to compare the types that the user *actually*
4385 // provided against the types that were *expected*. If the user
4386 // did not provide any types, then we want to substitute inference
4387 // variables. If the user provided some types, we may still need
4388 // to add defaults. If the user provided *too many* types, that's
4390 self.check_path_parameter_count(span, &mut type_segment);
4391 self.check_path_parameter_count(span, &mut fn_segment);
4393 let (fn_start, has_self) = match (type_segment, fn_segment) {
4394 (_, Some((_, generics))) => {
4395 (generics.parent_count(), generics.has_self)
4397 (Some((_, generics)), None) => {
4398 (generics.own_count(), generics.has_self)
4400 (None, None) => (0, false)
4402 let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4403 let mut i = def.index as usize;
4405 let segment = if i < fn_start {
4406 i -= has_self as usize;
4412 let lifetimes = match segment.map(|(s, _)| &s.parameters) {
4413 Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
4414 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4418 if let Some(lifetime) = lifetimes.get(i) {
4419 AstConv::ast_region_to_region(self, lifetime, Some(def))
4421 self.re_infer(span, Some(def)).unwrap()
4424 let mut i = def.index as usize;
4426 let segment = if i < fn_start {
4427 // Handle Self first, so we can adjust the index to match the AST.
4428 if has_self && i == 0 {
4429 return opt_self_ty.unwrap_or_else(|| {
4430 self.type_var_for_def(span, def, substs)
4433 i -= has_self as usize;
4439 let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
4440 Some(&hir::AngleBracketedParameters(ref data)) => {
4441 (&data.types[..], data.infer_types)
4443 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4444 None => (&[][..], true)
4447 // Skip over the lifetimes in the same segment.
4448 if let Some((_, generics)) = segment {
4449 i -= generics.regions.len();
4452 if let Some(ast_ty) = types.get(i) {
4453 // A provided type parameter.
4455 } else if !infer_types && def.has_default {
4456 // No type parameter provided, but a default exists.
4457 let default = self.tcx.type_of(def.def_id);
4460 default.subst_spanned(self.tcx, substs, Some(span))
4463 // No type parameters were provided, we can infer all.
4464 // This can also be reached in some error cases:
4465 // We prefer to use inference variables instead of
4466 // TyError to let type inference recover somewhat.
4467 self.type_var_for_def(span, def, substs)
4471 // The things we are substituting into the type should not contain
4472 // escaping late-bound regions, and nor should the base type scheme.
4473 let ty = self.tcx.type_of(def.def_id());
4474 assert!(!substs.has_escaping_regions());
4475 assert!(!ty.has_escaping_regions());
4477 // Add all the obligations that are required, substituting and
4478 // normalized appropriately.
4479 let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4480 self.add_obligations_for_parameters(
4481 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4484 // Substitute the values for the type parameters into the type of
4485 // the referenced item.
4486 let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4488 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4489 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4490 // is inherent, there is no `Self` parameter, instead, the impl needs
4491 // type parameters, which we can infer by unifying the provided `Self`
4492 // with the substituted impl type.
4493 let ty = self.tcx.type_of(impl_def_id);
4495 let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4496 match self.sub_types(false, &self.misc(span), self_ty, impl_ty) {
4497 Ok(ok) => self.register_infer_ok_obligations(ok),
4500 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4507 debug!("instantiate_value_path: type of {:?} is {:?}",
4510 self.write_substs(node_id, ty::ItemSubsts {
4516 /// Report errors if the provided parameters are too few or too many.
4517 fn check_path_parameter_count(&self,
4519 segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
4520 let (lifetimes, types, infer_types, bindings) = {
4521 match segment.map(|(s, _)| &s.parameters) {
4522 Some(&hir::AngleBracketedParameters(ref data)) => {
4523 (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
4525 Some(&hir::ParenthesizedParameters(_)) => {
4526 span_bug!(span, "parenthesized parameters cannot appear in ExprPath");
4528 None => (&[][..], &[][..], true, &[][..])
4532 let count_lifetime_params = |n| {
4533 format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4535 let count_type_params = |n| {
4536 format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4539 // Check provided lifetime parameters.
4540 let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4541 if lifetimes.len() > lifetime_defs.len() {
4542 let expected_text = count_lifetime_params(lifetime_defs.len());
4543 let actual_text = count_lifetime_params(lifetimes.len());
4544 struct_span_err!(self.tcx.sess, span, E0088,
4545 "too many lifetime parameters provided: \
4546 expected at most {}, found {}",
4547 expected_text, actual_text)
4548 .span_label(span, format!("expected {}", expected_text))
4550 } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
4551 let expected_text = count_lifetime_params(lifetime_defs.len());
4552 let actual_text = count_lifetime_params(lifetimes.len());
4553 struct_span_err!(self.tcx.sess, span, E0090,
4554 "too few lifetime parameters provided: \
4555 expected {}, found {}",
4556 expected_text, actual_text)
4557 .span_label(span, format!("expected {}", expected_text))
4561 // The case where there is not enough lifetime parameters is not checked,
4562 // because this is not possible - a function never takes lifetime parameters.
4563 // See discussion for Pull Request 36208.
4565 // Check provided type parameters.
4566 let type_defs = segment.map_or(&[][..], |(_, generics)| {
4567 if generics.parent.is_none() {
4568 &generics.types[generics.has_self as usize..]
4573 let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4574 if types.len() > type_defs.len() {
4575 let span = types[type_defs.len()].span;
4576 let expected_text = count_type_params(type_defs.len());
4577 let actual_text = count_type_params(types.len());
4578 struct_span_err!(self.tcx.sess, span, E0087,
4579 "too many type parameters provided: \
4580 expected at most {}, found {}",
4581 expected_text, actual_text)
4582 .span_label(span, format!("expected {}", expected_text))
4585 // To prevent derived errors to accumulate due to extra
4586 // type parameters, we force instantiate_value_path to
4587 // use inference variables instead of the provided types.
4589 } else if !infer_types && types.len() < required_len {
4590 let expected_text = count_type_params(required_len);
4591 let actual_text = count_type_params(types.len());
4592 struct_span_err!(self.tcx.sess, span, E0089,
4593 "too few type parameters provided: \
4594 expected {}, found {}",
4595 expected_text, actual_text)
4596 .span_label(span, format!("expected {}", expected_text))
4600 if !bindings.is_empty() {
4601 span_err!(self.tcx.sess, bindings[0].span, E0182,
4602 "unexpected binding of associated item in expression path \
4603 (only allowed in type paths)");
4607 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4609 where F: Fn() -> Ty<'tcx>
4611 let mut ty = self.resolve_type_vars_with_obligations(ty);
4614 let alternative = f();
4617 if alternative.is_ty_var() || alternative.references_error() {
4618 if !self.is_tainted_by_errors() {
4619 self.type_error_message(sp, |_actual| {
4620 "the type of this value must be known in this context".to_string()
4623 self.demand_suptype(sp, self.tcx.types.err, ty);
4624 ty = self.tcx.types.err;
4626 self.demand_suptype(sp, alternative, ty);
4634 // Resolves `typ` by a single level if `typ` is a type variable. If no
4635 // resolution is possible, then an error is reported.
4636 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4637 self.structurally_resolve_type_or_else(sp, ty, || {
4642 fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4643 ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4644 -> (BreakableCtxt<'gcx, 'tcx>, R) {
4647 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4648 index = enclosing_breakables.stack.len();
4649 enclosing_breakables.by_id.insert(id, index);
4650 enclosing_breakables.stack.push(ctxt);
4654 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4655 debug_assert!(enclosing_breakables.stack.len() == index + 1);
4656 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4657 enclosing_breakables.stack.pop().expect("missing breakable context")
4663 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4664 generics: &hir::Generics,
4666 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4667 generics.ty_params.len(), ty);
4669 // make a vector of booleans initially false, set to true when used
4670 if generics.ty_params.is_empty() { return; }
4671 let mut tps_used = vec![false; generics.ty_params.len()];
4673 for leaf_ty in ty.walk() {
4674 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4675 debug!("Found use of ty param num {}", idx);
4676 tps_used[idx as usize - generics.lifetimes.len()] = true;
4680 for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4682 struct_span_err!(tcx.sess, param.span, E0091,
4683 "type parameter `{}` is unused",
4685 .span_label(param.span, "unused type parameter")