1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 Within the check phase of type check, we check each item one at a time
16 (bodies of function expressions are checked as part of the containing
17 function). Inference is used to supply types wherever they are
20 By far the most complex case is checking the body of a function. This
21 can be broken down into several distinct phases:
23 - gather: creates type variables to represent the type of each local
24 variable and pattern binding.
26 - main: the main pass does the lion's share of the work: it
27 determines the types of all expressions, resolves
28 methods, checks for most invalid conditions, and so forth. In
29 some cases, where a type is unknown, it may create a type or region
30 variable and use that as the type of an expression.
32 In the process of checking, various constraints will be placed on
33 these type variables through the subtyping relationships requested
34 through the `demand` module. The `infer` module is in charge
35 of resolving those constraints.
37 - regionck: after main is complete, the regionck pass goes over all
38 types looking for regions and making sure that they did not escape
39 into places they are not in scope. This may also influence the
40 final assignments of the various region variables if there is some
43 - vtable: find and records the impls to use for each trait bound that
44 appears on a type parameter.
46 - writeback: writes the final types within a function body, replacing
47 type variables with their final inferred types. These final types
48 are written into the `tcx.node_types` table, which should *never* contain
49 any reference to a type variable.
53 While type checking a function, the intermediate types for the
54 expressions, blocks, and so forth contained within the function are
55 stored in `fcx.node_types` and `fcx.node_substs`. These types
56 may contain unresolved type variables. After type checking is
57 complete, the functions in the writeback module are used to take the
58 types from this table, resolve them, and then write them into their
59 permanent home in the type context `tcx`.
61 This means that during inferencing you should use `fcx.write_ty()`
62 and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
63 nodes within the function.
65 The types of top-level items, which never contain unbound type
66 variables, are stored directly into the `tcx` tables.
68 n.b.: A type variable is not the same thing as a type parameter. A
69 type variable is rather an "instance" of a type parameter: that is,
70 given a generic function `fn foo<T>(t: T)`: while checking the
71 function `foo`, the type `ty_param(0)` refers to the type `T`, which
72 is treated in abstract. When `foo()` is called, however, `T` will be
73 substituted for a fresh type variable `N`. This variable will
74 eventually be resolved to some concrete type (which might itself be
79 pub use self::Expectation::*;
80 use self::autoderef::Autoderef;
81 use self::callee::DeferredCallResolution;
82 use self::coercion::{CoerceMany, DynamicCoerceMany};
83 pub use self::compare_method::{compare_impl_method, compare_const_impl};
84 use self::method::MethodCallee;
85 use self::TupleArgumentsFlag::*;
88 use fmt_macros::{Parser, Piece, Position};
89 use hir::def::{Def, CtorKind};
90 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
91 use rustc_back::slice::ref_slice;
92 use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
93 use rustc::infer::type_variable::{TypeVariableOrigin};
94 use rustc::middle::region::CodeExtent;
95 use rustc::ty::subst::{Kind, Subst, Substs};
96 use rustc::traits::{self, FulfillmentContext, ObligationCause, ObligationCauseCode, Reveal};
97 use rustc::ty::{ParamTy, LvaluePreference, NoPreference, PreferMutLvalue};
98 use rustc::ty::{self, Ty, TyCtxt, Visibility};
99 use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow, OverloadedDeref};
100 use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
101 use rustc::ty::maps::Providers;
102 use rustc::ty::util::{Representability, IntTypeExt};
103 use errors::DiagnosticBuilder;
104 use require_c_abi_if_variadic;
105 use session::{Session, CompileResult};
108 use util::common::{ErrorReported, indenter};
109 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
111 use std::cell::{Cell, RefCell};
112 use std::collections::hash_map::Entry;
114 use std::mem::replace;
115 use std::ops::{self, Deref};
116 use syntax::abi::Abi;
118 use syntax::codemap::{self, original_sp, Spanned};
119 use syntax::feature_gate::{GateIssue, emit_feature_err};
121 use syntax::symbol::{Symbol, InternedString, keywords};
122 use syntax::util::lev_distance::find_best_match_for_name;
123 use syntax_pos::{self, BytePos, Span, DUMMY_SP};
125 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
126 use rustc::hir::itemlikevisit::ItemLikeVisitor;
127 use rustc::hir::{self, PatKind};
128 use rustc::middle::lang_items;
129 use rustc_back::slice;
130 use rustc::middle::const_val::eval_length;
131 use rustc_const_math::ConstInt;
150 /// closures defined within the function. For example:
153 /// bar(move|| { ... })
156 /// Here, the function `foo()` and the closure passed to
157 /// `bar()` will each have their own `FnCtxt`, but they will
158 /// share the inherited fields.
159 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
160 infcx: InferCtxt<'a, 'gcx, 'tcx>,
162 locals: RefCell<NodeMap<Ty<'tcx>>>,
164 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
166 // When we process a call like `c()` where `c` is a closure type,
167 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
168 // `FnOnce` closure. In that case, we defer full resolution of the
169 // call until upvar inference can kick in and make the
170 // decision. We keep these deferred resolutions grouped by the
171 // def-id of the closure, so that once we decide, we can easily go
172 // back and process them.
173 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'gcx, 'tcx>>>>,
175 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
177 // Anonymized types found in explicit return types and their
178 // associated fresh inference variable. Writeback resolves these
179 // variables to get the concrete type, which can be used to
180 // deanonymize TyAnon, after typeck is done with all functions.
181 anon_types: RefCell<NodeMap<Ty<'tcx>>>,
183 /// Each type parameter has an implicit region bound that
184 /// indicates it must outlive at least the function body (the user
185 /// may specify stronger requirements). This field indicates the
186 /// region of the callee. If it is `None`, then the parameter
187 /// environment is for an item or something where the "callee" is
189 implicit_region_bound: Option<ty::Region<'tcx>>,
192 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
193 type Target = InferCtxt<'a, 'gcx, 'tcx>;
194 fn deref(&self) -> &Self::Target {
199 /// When type-checking an expression, we propagate downward
200 /// whatever type hint we are able in the form of an `Expectation`.
201 #[derive(Copy, Clone, Debug)]
202 pub enum Expectation<'tcx> {
203 /// We know nothing about what type this expression should have.
206 /// This expression should have the type given (or some subtype)
207 ExpectHasType(Ty<'tcx>),
209 /// This expression will be cast to the `Ty`
210 ExpectCastableToType(Ty<'tcx>),
212 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
213 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
214 ExpectRvalueLikeUnsized(Ty<'tcx>),
217 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
218 // Disregard "castable to" expectations because they
219 // can lead us astray. Consider for example `if cond
220 // {22} else {c} as u8` -- if we propagate the
221 // "castable to u8" constraint to 22, it will pick the
222 // type 22u8, which is overly constrained (c might not
223 // be a u8). In effect, the problem is that the
224 // "castable to" expectation is not the tightest thing
225 // we can say, so we want to drop it in this case.
226 // The tightest thing we can say is "must unify with
227 // else branch". Note that in the case of a "has type"
228 // constraint, this limitation does not hold.
230 // If the expected type is just a type variable, then don't use
231 // an expected type. Otherwise, we might write parts of the type
232 // when checking the 'then' block which are incompatible with the
234 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
236 ExpectHasType(ety) => {
237 let ety = fcx.shallow_resolve(ety);
238 if !ety.is_ty_var() {
244 ExpectRvalueLikeUnsized(ety) => {
245 ExpectRvalueLikeUnsized(ety)
251 /// Provide an expectation for an rvalue expression given an *optional*
252 /// hint, which is not required for type safety (the resulting type might
253 /// be checked higher up, as is the case with `&expr` and `box expr`), but
254 /// is useful in determining the concrete type.
256 /// The primary use case is where the expected type is a fat pointer,
257 /// like `&[isize]`. For example, consider the following statement:
259 /// let x: &[isize] = &[1, 2, 3];
261 /// In this case, the expected type for the `&[1, 2, 3]` expression is
262 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
263 /// expectation `ExpectHasType([isize])`, that would be too strong --
264 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
265 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
266 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
267 /// which still is useful, because it informs integer literals and the like.
268 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
269 /// for examples of where this comes up,.
270 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
271 match fcx.tcx.struct_tail(ty).sty {
272 ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
273 ExpectRvalueLikeUnsized(ty)
275 _ => ExpectHasType(ty)
279 // Resolves `expected` by a single level if it is a variable. If
280 // there is no expected type or resolution is not possible (e.g.,
281 // no constraints yet present), just returns `None`.
282 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
287 ExpectCastableToType(t) => {
288 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
290 ExpectHasType(t) => {
291 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
293 ExpectRvalueLikeUnsized(t) => {
294 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
299 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
300 match self.resolve(fcx) {
301 NoExpectation => None,
302 ExpectCastableToType(ty) |
304 ExpectRvalueLikeUnsized(ty) => Some(ty),
308 /// It sometimes happens that we want to turn an expectation into
309 /// a **hard constraint** (i.e., something that must be satisfied
310 /// for the program to type-check). `only_has_type` will return
311 /// such a constraint, if it exists.
312 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
313 match self.resolve(fcx) {
314 ExpectHasType(ty) => Some(ty),
319 /// Like `only_has_type`, but instead of returning `None` if no
320 /// hard constraint exists, creates a fresh type variable.
321 fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
322 self.only_has_type(fcx)
323 .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
327 #[derive(Copy, Clone)]
328 pub struct UnsafetyState {
329 pub def: ast::NodeId,
330 pub unsafety: hir::Unsafety,
331 pub unsafe_push_count: u32,
336 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
337 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
340 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
341 match self.unsafety {
342 // If this unsafe, then if the outer function was already marked as
343 // unsafe we shouldn't attribute the unsafe'ness to the block. This
344 // way the block can be warned about instead of ignoring this
345 // extraneous block (functions are never warned about).
346 hir::Unsafety::Unsafe if self.from_fn => *self,
349 let (unsafety, def, count) = match blk.rules {
350 hir::PushUnsafeBlock(..) =>
351 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
352 hir::PopUnsafeBlock(..) =>
353 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
354 hir::UnsafeBlock(..) =>
355 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
357 (unsafety, self.def, self.unsafe_push_count),
359 UnsafetyState{ def: def,
361 unsafe_push_count: count,
368 #[derive(Debug, Copy, Clone)]
374 /// Tracks whether executing a node may exit normally (versus
375 /// return/break/panic, which "diverge", leaving dead code in their
376 /// wake). Tracked semi-automatically (through type variables marked
377 /// as diverging), with some manual adjustments for control-flow
378 /// primitives (approximating a CFG).
379 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
381 /// Potentially unknown, some cases converge,
382 /// others require a CFG to determine them.
385 /// Definitely known to diverge and therefore
386 /// not reach the next sibling or its parent.
389 /// Same as `Always` but with a reachability
390 /// warning already emitted
394 // Convenience impls for combinig `Diverges`.
396 impl ops::BitAnd for Diverges {
398 fn bitand(self, other: Self) -> Self {
399 cmp::min(self, other)
403 impl ops::BitOr for Diverges {
405 fn bitor(self, other: Self) -> Self {
406 cmp::max(self, other)
410 impl ops::BitAndAssign for Diverges {
411 fn bitand_assign(&mut self, other: Self) {
412 *self = *self & other;
416 impl ops::BitOrAssign for Diverges {
417 fn bitor_assign(&mut self, other: Self) {
418 *self = *self | other;
423 fn always(self) -> bool {
424 self >= Diverges::Always
428 pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
431 // this is `null` for loops where break with a value is illegal,
432 // such as `while`, `for`, and `while let`
433 coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>,
436 pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
437 stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
438 by_id: NodeMap<usize>,
441 impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
442 fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
443 let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
444 bug!("could not find enclosing breakable with id {}", target_id);
450 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
451 body_id: ast::NodeId,
453 // Number of errors that had been reported when we started
454 // checking this function. On exit, if we find that *more* errors
455 // have been reported, we will skip regionck and other work that
456 // expects the types within the function to be consistent.
457 err_count_on_creation: usize,
459 ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>,
461 ps: RefCell<UnsafetyState>,
463 /// Whether the last checked node generates a divergence (e.g.,
464 /// `return` will set this to Always). In general, when entering
465 /// an expression or other node in the tree, the initial value
466 /// indicates whether prior parts of the containing expression may
467 /// have diverged. It is then typically set to `Maybe` (and the
468 /// old value remembered) for processing the subparts of the
469 /// current expression. As each subpart is processed, they may set
470 /// the flag to `Always` etc. Finally, at the end, we take the
471 /// result and "union" it with the original value, so that when we
472 /// return the flag indicates if any subpart of the the parent
473 /// expression (up to and including this part) has diverged. So,
474 /// if you read it after evaluating a subexpression `X`, the value
475 /// you get indicates whether any subexpression that was
476 /// evaluating up to and including `X` diverged.
478 /// We use this flag for two purposes:
480 /// - To warn about unreachable code: if, after processing a
481 /// sub-expression but before we have applied the effects of the
482 /// current node, we see that the flag is set to `Always`, we
483 /// can issue a warning. This corresponds to something like
484 /// `foo(return)`; we warn on the `foo()` expression. (We then
485 /// update the flag to `WarnedAlways` to suppress duplicate
486 /// reports.) Similarly, if we traverse to a fresh statement (or
487 /// tail expression) from a `Always` setting, we will isssue a
488 /// warning. This corresponds to something like `{return;
489 /// foo();}` or `{return; 22}`, where we would warn on the
492 /// - To permit assignment into a local variable or other lvalue
493 /// (including the "return slot") of type `!`. This is allowed
494 /// if **either** the type of value being assigned is `!`, which
495 /// means the current code is dead, **or** the expression's
496 /// divering flag is true, which means that a divering value was
497 /// wrapped (e.g., `let x: ! = foo(return)`).
499 /// To repeat the last point: an expression represents dead-code
500 /// if, after checking it, **either** its type is `!` OR the
501 /// diverges flag is set to something other than `Maybe`.
502 diverges: Cell<Diverges>,
504 /// Whether any child nodes have any type errors.
505 has_errors: Cell<bool>,
507 enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
509 inh: &'a Inherited<'a, 'gcx, 'tcx>,
512 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
513 type Target = Inherited<'a, 'gcx, 'tcx>;
514 fn deref(&self) -> &Self::Target {
519 /// Helper type of a temporary returned by Inherited::build(...).
520 /// Necessary because we can't write the following bound:
521 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
522 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
523 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>,
527 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
528 pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId)
529 -> InheritedBuilder<'a, 'gcx, 'tcx> {
530 let tables = ty::TypeckTables::empty();
531 let param_env = tcx.param_env(def_id);
533 infcx: tcx.infer_ctxt((tables, param_env), Reveal::UserFacing),
539 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
540 fn enter<F, R>(&'tcx mut self, f: F) -> R
541 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
543 let def_id = self.def_id;
544 self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
548 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
549 fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> Self {
551 let item_id = tcx.hir.as_local_node_id(def_id);
552 let body_id = item_id.and_then(|id| tcx.hir.maybe_body_owned_by(id));
553 let implicit_region_bound = body_id.map(|body| {
554 tcx.mk_region(ty::ReScope(CodeExtent::CallSiteScope(body)))
559 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
560 locals: RefCell::new(NodeMap()),
561 deferred_call_resolutions: RefCell::new(DefIdMap()),
562 deferred_cast_checks: RefCell::new(Vec::new()),
563 anon_types: RefCell::new(NodeMap()),
564 implicit_region_bound,
568 fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
569 debug!("register_predicate({:?})", obligation);
570 if obligation.has_escaping_regions() {
571 span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
576 .register_predicate_obligation(self, obligation);
579 fn register_predicates(&self, obligations: Vec<traits::PredicateObligation<'tcx>>) {
580 for obligation in obligations {
581 self.register_predicate(obligation);
585 fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
586 self.register_predicates(infer_ok.obligations);
590 fn normalize_associated_types_in<T>(&self,
592 body_id: ast::NodeId,
594 where T : TypeFoldable<'tcx>
596 let ok = self.normalize_associated_types_in_as_infer_ok(span, body_id, value);
597 self.register_infer_ok_obligations(ok)
600 fn normalize_associated_types_in_as_infer_ok<T>(&self,
602 body_id: ast::NodeId,
605 where T : TypeFoldable<'tcx>
607 debug!("normalize_associated_types_in(value={:?})", value);
608 let mut selcx = traits::SelectionContext::new(self);
609 let cause = ObligationCause::misc(span, body_id);
610 let traits::Normalized { value, obligations } =
611 traits::normalize(&mut selcx, cause, value);
612 debug!("normalize_associated_types_in: result={:?} predicates={:?}",
615 InferOk { value, obligations }
618 /// Replace any late-bound regions bound in `value` with
619 /// free variants attached to `all_outlive_scope`.
620 fn liberate_late_bound_regions<T>(&self,
621 all_outlive_scope: DefId,
622 value: &ty::Binder<T>)
624 where T: TypeFoldable<'tcx>
626 self.tcx.replace_late_bound_regions(value, |br| {
627 self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
628 scope: all_outlive_scope,
635 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
637 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
638 fn visit_item(&mut self, i: &'tcx hir::Item) {
639 check_item_type(self.tcx, i);
641 fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
642 fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
645 pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
646 tcx.sess.track_errors(|| {
647 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
648 tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor());
652 pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
653 tcx.sess.track_errors(|| {
654 tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx });
658 pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
659 tcx.typeck_item_bodies(LOCAL_CRATE)
662 fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> CompileResult {
663 debug_assert!(crate_num == LOCAL_CRATE);
664 tcx.sess.track_errors(|| {
665 for body_owner_def_id in tcx.body_owners() {
666 tcx.typeck_tables_of(body_owner_def_id);
671 pub fn provide(providers: &mut Providers) {
672 *providers = Providers {
683 fn closure_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
685 -> ty::PolyFnSig<'tcx> {
686 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
687 tcx.typeck_tables_of(def_id).closure_tys[&node_id]
690 fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
693 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
694 tcx.typeck_tables_of(def_id).closure_kinds[&node_id].0
697 fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
699 -> Option<ty::Destructor> {
700 tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
703 /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))`
704 /// with information about it's body-id and fn-decl (if any). Otherwise,
707 /// If this function returns "some", then `typeck_tables(def_id)` will
708 /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or
709 /// may not succeed. In some cases where this function returns `None`
710 /// (notably closures), `typeck_tables(def_id)` would wind up
711 /// redirecting to the owning function.
712 fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
714 -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)>
716 match tcx.hir.get(id) {
717 hir::map::NodeItem(item) => {
719 hir::ItemConst(_, body) |
720 hir::ItemStatic(_, _, body) =>
722 hir::ItemFn(ref decl, .., body) =>
723 Some((body, Some(decl))),
728 hir::map::NodeTraitItem(item) => {
730 hir::TraitItemKind::Const(_, Some(body)) =>
732 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) =>
733 Some((body, Some(&sig.decl))),
738 hir::map::NodeImplItem(item) => {
740 hir::ImplItemKind::Const(_, body) =>
742 hir::ImplItemKind::Method(ref sig, body) =>
743 Some((body, Some(&sig.decl))),
748 hir::map::NodeExpr(expr) => {
749 // FIXME(eddyb) Closures should have separate
750 // function definition IDs and expression IDs.
751 // Type-checking should not let closures get
752 // this far in a constant position.
753 // Assume that everything other than closures
754 // is a constant "initializer" expression.
756 hir::ExprClosure(..) =>
759 Some((hir::BodyId { node_id: expr.id }, None)),
766 fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
769 // Closures' tables come from their outermost function,
770 // as they are part of the same "inference environment".
771 let outer_def_id = tcx.closure_base_def_id(def_id);
772 if outer_def_id != def_id {
773 return tcx.has_typeck_tables(outer_def_id);
776 let id = tcx.hir.as_local_node_id(def_id).unwrap();
777 primary_body_of(tcx, id).is_some()
780 fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
782 -> &'tcx ty::TypeckTables<'tcx> {
783 // Closures' tables come from their outermost function,
784 // as they are part of the same "inference environment".
785 let outer_def_id = tcx.closure_base_def_id(def_id);
786 if outer_def_id != def_id {
787 return tcx.typeck_tables_of(outer_def_id);
790 let id = tcx.hir.as_local_node_id(def_id).unwrap();
791 let span = tcx.hir.span(id);
793 // Figure out what primary body this item has.
794 let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| {
795 span_bug!(span, "can't type-check body of {:?}", def_id);
797 let body = tcx.hir.body(body_id);
799 Inherited::build(tcx, def_id).enter(|inh| {
800 let fcx = if let Some(decl) = fn_decl {
801 let fn_sig = tcx.type_of(def_id).fn_sig();
803 check_abi(tcx, span, fn_sig.abi());
805 // Compute the fty from point of view of inside fn.
807 inh.liberate_late_bound_regions(def_id, &fn_sig);
809 inh.normalize_associated_types_in(body.value.span, body_id.node_id, &fn_sig);
811 check_fn(&inh, fn_sig, decl, id, body)
813 let fcx = FnCtxt::new(&inh, body.value.id);
814 let expected_type = tcx.type_of(def_id);
815 let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
816 fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
818 // Gather locals in statics (because of block expressions).
819 // This is technically unnecessary because locals in static items are forbidden,
820 // but prevents type checking from blowing up before const checking can properly
822 GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
824 fcx.check_expr_coercable_to_type(&body.value, expected_type);
829 fcx.select_all_obligations_and_apply_defaults();
830 fcx.closure_analyze(body);
831 fcx.select_obligations_where_possible();
833 fcx.select_all_obligations_or_error();
835 if fn_decl.is_some() {
836 fcx.regionck_fn(id, body);
838 fcx.regionck_expr(body);
841 fcx.resolve_type_vars_in_body(body)
845 fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
846 if !tcx.sess.target.target.is_abi_supported(abi) {
847 struct_span_err!(tcx.sess, span, E0570,
848 "The ABI `{}` is not supported for the current target", abi).emit()
852 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
853 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
856 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
857 fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
860 // infer the variable's type
861 let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
862 self.fcx.locals.borrow_mut().insert(nid, var_ty);
866 // take type that the user specified
867 self.fcx.locals.borrow_mut().insert(nid, typ);
874 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
875 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
876 NestedVisitorMap::None
879 // Add explicitly-declared locals.
880 fn visit_local(&mut self, local: &'gcx hir::Local) {
881 let o_ty = match local.ty {
882 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
885 self.assign(local.span, local.id, o_ty);
886 debug!("Local variable {:?} is assigned type {}",
888 self.fcx.ty_to_string(
889 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
890 intravisit::walk_local(self, local);
893 // Add pattern bindings.
894 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
895 if let PatKind::Binding(_, _, ref path1, _) = p.node {
896 let var_ty = self.assign(p.span, p.id, None);
898 self.fcx.require_type_is_sized(var_ty, p.span,
899 traits::VariableType(p.id));
901 debug!("Pattern binding {} is assigned to {} with type {:?}",
903 self.fcx.ty_to_string(
904 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
907 intravisit::walk_pat(self, p);
910 // Don't descend into the bodies of nested closures
911 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
912 _: hir::BodyId, _: Span, _: ast::NodeId) { }
915 /// Helper used for fns and closures. Does the grungy work of checking a function
916 /// body and returns the function context used for that purpose, since in the case of a fn item
917 /// there is still a bit more to do.
920 /// * inherited: other fields inherited from the enclosing fn (if any)
921 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
922 fn_sig: ty::FnSig<'tcx>,
923 decl: &'gcx hir::FnDecl,
925 body: &'gcx hir::Body)
926 -> FnCtxt<'a, 'gcx, 'tcx>
928 let mut fn_sig = fn_sig.clone();
930 debug!("check_fn(sig={:?}, fn_id={})", fn_sig, fn_id);
932 // Create the function context. This is either derived from scratch or,
933 // in the case of function expressions, based on the outer context.
934 let mut fcx = FnCtxt::new(inherited, body.value.id);
935 *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
937 let ret_ty = fn_sig.output();
938 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
939 let ret_ty = fcx.instantiate_anon_types(&ret_ty);
940 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
941 fn_sig = fcx.tcx.mk_fn_sig(
942 fn_sig.inputs().iter().cloned(),
949 GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
951 // Add formal parameters.
952 for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
953 // The type of the argument must be well-formed.
955 // NB -- this is now checked in wfcheck, but that
956 // currently only results in warnings, so we issue an
957 // old-style WF obligation here so that we still get the
958 // errors that we used to get.
959 fcx.register_old_wf_obligation(arg_ty, arg.pat.span, traits::MiscObligation);
961 // Check the pattern.
962 fcx.check_pat_arg(&arg.pat, arg_ty, true);
963 fcx.write_ty(arg.id, arg_ty);
966 inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig);
968 fcx.check_return_expr(&body.value);
970 // Finalize the return check by taking the LUB of the return types
971 // we saw and assigning it to the expected return type. This isn't
972 // really expected to fail, since the coercions would have failed
973 // earlier when trying to find a LUB.
975 // However, the behavior around `!` is sort of complex. In the
976 // event that the `actual_return_ty` comes back as `!`, that
977 // indicates that the fn either does not return or "returns" only
978 // values of type `!`. In this case, if there is an expected
979 // return type that is *not* `!`, that should be ok. But if the
980 // return type is being inferred, we want to "fallback" to `!`:
982 // let x = move || panic!();
984 // To allow for that, I am creating a type variable with diverging
985 // fallback. This was deemed ever so slightly better than unifying
986 // the return value with `!` because it allows for the caller to
987 // make more assumptions about the return type (e.g., they could do
989 // let y: Option<u32> = Some(x());
991 // which would then cause this return type to become `u32`, not
993 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
994 let mut actual_return_ty = coercion.complete(&fcx);
995 if actual_return_ty.is_never() {
996 actual_return_ty = fcx.next_diverging_ty_var(
997 TypeVariableOrigin::DivergingFn(body.value.span));
999 fcx.demand_suptype(body.value.span, ret_ty, actual_return_ty);
1004 fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1007 let def_id = tcx.hir.local_def_id(id);
1008 let def = tcx.adt_def(def_id);
1009 def.destructor(tcx); // force the destructor to be evaluated
1010 check_representable(tcx, span, def_id);
1012 if def.repr.simd() {
1013 check_simd(tcx, span, def_id);
1016 // if struct is packed and not aligned, check fields for alignment.
1017 // Checks for combining packed and align attrs on single struct are done elsewhere.
1018 if tcx.adt_def(def_id).repr.packed() && tcx.adt_def(def_id).repr.align == 0 {
1019 check_packed(tcx, span, def_id);
1023 fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1026 let def_id = tcx.hir.local_def_id(id);
1027 let def = tcx.adt_def(def_id);
1028 def.destructor(tcx); // force the destructor to be evaluated
1029 check_representable(tcx, span, def_id);
1032 pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
1033 debug!("check_item_type(it.id={}, it.name={})",
1035 tcx.item_path_str(tcx.hir.local_def_id(it.id)));
1036 let _indenter = indenter();
1038 // Consts can play a role in type-checking, so they are included here.
1039 hir::ItemStatic(..) |
1040 hir::ItemConst(..) => {
1041 tcx.typeck_tables_of(tcx.hir.local_def_id(it.id));
1043 hir::ItemEnum(ref enum_definition, _) => {
1046 &enum_definition.variants,
1049 hir::ItemFn(..) => {} // entirely within check_item_body
1050 hir::ItemImpl(.., ref impl_item_refs) => {
1051 debug!("ItemImpl {} with id {}", it.name, it.id);
1052 let impl_def_id = tcx.hir.local_def_id(it.id);
1053 if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1054 check_impl_items_against_trait(tcx,
1059 let trait_def_id = impl_trait_ref.def_id;
1060 check_on_unimplemented(tcx, trait_def_id, it);
1063 hir::ItemTrait(..) => {
1064 let def_id = tcx.hir.local_def_id(it.id);
1065 check_on_unimplemented(tcx, def_id, it);
1067 hir::ItemStruct(..) => {
1068 check_struct(tcx, it.id, it.span);
1070 hir::ItemUnion(..) => {
1071 check_union(tcx, it.id, it.span);
1073 hir::ItemTy(_, ref generics) => {
1074 let def_id = tcx.hir.local_def_id(it.id);
1075 let pty_ty = tcx.type_of(def_id);
1076 check_bounds_are_used(tcx, generics, pty_ty);
1078 hir::ItemForeignMod(ref m) => {
1079 check_abi(tcx, it.span, m.abi);
1081 if m.abi == Abi::RustIntrinsic {
1082 for item in &m.items {
1083 intrinsic::check_intrinsic_type(tcx, item);
1085 } else if m.abi == Abi::PlatformIntrinsic {
1086 for item in &m.items {
1087 intrinsic::check_platform_intrinsic_type(tcx, item);
1090 for item in &m.items {
1091 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
1092 if !generics.types.is_empty() {
1093 let mut err = struct_span_err!(tcx.sess, item.span, E0044,
1094 "foreign items may not have type parameters");
1095 span_help!(&mut err, item.span,
1096 "consider using specialization instead of \
1101 if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
1102 require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
1107 _ => {/* nothing to do */ }
1111 fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1114 let generics = tcx.generics_of(def_id);
1115 if let Some(ref attr) = item.attrs.iter().find(|a| {
1116 a.check_name("rustc_on_unimplemented")
1118 if let Some(istring) = attr.value_str() {
1119 let istring = istring.as_str();
1120 let parser = Parser::new(&istring);
1121 let types = &generics.types;
1122 for token in parser {
1124 Piece::String(_) => (), // Normal string, no need to check it
1125 Piece::NextArgument(a) => match a.position {
1126 // `{Self}` is allowed
1127 Position::ArgumentNamed(s) if s == "Self" => (),
1128 // So is `{A}` if A is a type parameter
1129 Position::ArgumentNamed(s) => match types.iter().find(|t| {
1134 let name = tcx.item_name(def_id);
1135 span_err!(tcx.sess, attr.span, E0230,
1136 "there is no type parameter \
1141 // `{:1}` and `{}` are not to be used
1142 Position::ArgumentIs(_) => {
1143 span_err!(tcx.sess, attr.span, E0231,
1144 "only named substitution \
1145 parameters are allowed");
1152 tcx.sess, attr.span, E0232,
1153 "this attribute must have a value")
1154 .span_label(attr.span, "attribute requires a value")
1155 .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
1161 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1162 impl_item: &hir::ImplItem,
1165 let mut err = struct_span_err!(
1166 tcx.sess, impl_item.span, E0520,
1167 "`{}` specializes an item from a parent `impl`, but \
1168 that item is not marked `default`",
1170 err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
1173 match tcx.span_of_impl(parent_impl) {
1175 err.span_label(span, "parent `impl` is here");
1176 err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
1180 err.note(&format!("parent implementation is in crate `{}`", cname));
1187 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1188 trait_def: &ty::TraitDef,
1190 impl_item: &hir::ImplItem)
1192 let ancestors = trait_def.ancestors(tcx, impl_id);
1194 let kind = match impl_item.node {
1195 hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
1196 hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
1197 hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
1199 let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
1200 .map(|node_item| node_item.map(|parent| parent.defaultness));
1202 if let Some(parent) = parent {
1203 if tcx.impl_item_is_final(&parent) {
1204 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1210 fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1213 impl_trait_ref: ty::TraitRef<'tcx>,
1214 impl_item_refs: &[hir::ImplItemRef]) {
1215 // If the trait reference itself is erroneous (so the compilation is going
1216 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1217 // isn't populated for such impls.
1218 if impl_trait_ref.references_error() { return; }
1220 // Locate trait definition and items
1221 let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1222 let mut overridden_associated_type = None;
1224 let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
1226 // Check existing impl methods to see if they are both present in trait
1227 // and compatible with trait signature
1228 for impl_item in impl_items() {
1229 let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
1230 let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
1231 .find(|ac| ac.name == ty_impl_item.name);
1233 // Check that impl definition matches trait definition
1234 if let Some(ty_trait_item) = ty_trait_item {
1235 match impl_item.node {
1236 hir::ImplItemKind::Const(..) => {
1237 // Find associated const definition.
1238 if ty_trait_item.kind == ty::AssociatedKind::Const {
1239 compare_const_impl(tcx,
1245 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1246 "item `{}` is an associated const, \
1247 which doesn't match its trait `{}`",
1250 err.span_label(impl_item.span, "does not match trait");
1251 // We can only get the spans from local trait definition
1252 // Same for E0324 and E0325
1253 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1254 err.span_label(trait_span, "item in trait");
1259 hir::ImplItemKind::Method(..) => {
1260 let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
1261 if ty_trait_item.kind == ty::AssociatedKind::Method {
1262 let err_count = tcx.sess.err_count();
1263 compare_impl_method(tcx,
1269 true); // start with old-broken-mode
1270 if err_count == tcx.sess.err_count() {
1271 // old broken mode did not report an error. Try with the new mode.
1272 compare_impl_method(tcx,
1278 false); // use the new mode
1281 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1282 "item `{}` is an associated method, \
1283 which doesn't match its trait `{}`",
1286 err.span_label(impl_item.span, "does not match trait");
1287 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1288 err.span_label(trait_span, "item in trait");
1293 hir::ImplItemKind::Type(_) => {
1294 if ty_trait_item.kind == ty::AssociatedKind::Type {
1295 if ty_trait_item.defaultness.has_value() {
1296 overridden_associated_type = Some(impl_item);
1299 let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1300 "item `{}` is an associated type, \
1301 which doesn't match its trait `{}`",
1304 err.span_label(impl_item.span, "does not match trait");
1305 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1306 err.span_label(trait_span, "item in trait");
1314 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1317 // Check for missing items from trait
1318 let mut missing_items = Vec::new();
1319 let mut invalidated_items = Vec::new();
1320 let associated_type_overridden = overridden_associated_type.is_some();
1321 for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
1322 let is_implemented = trait_def.ancestors(tcx, impl_id)
1323 .defs(tcx, trait_item.name, trait_item.kind)
1325 .map(|node_item| !node_item.node.is_from_trait())
1328 if !is_implemented {
1329 if !trait_item.defaultness.has_value() {
1330 missing_items.push(trait_item);
1331 } else if associated_type_overridden {
1332 invalidated_items.push(trait_item.name);
1337 let signature = |item: &ty::AssociatedItem| {
1339 ty::AssociatedKind::Method => {
1340 format!("{}", tcx.type_of(item.def_id).fn_sig().0)
1342 ty::AssociatedKind::Type => format!("type {};", item.name.to_string()),
1343 ty::AssociatedKind::Const => {
1344 format!("const {}: {:?};", item.name.to_string(), tcx.type_of(item.def_id))
1349 if !missing_items.is_empty() {
1350 let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
1351 "not all trait items implemented, missing: `{}`",
1352 missing_items.iter()
1353 .map(|trait_item| trait_item.name.to_string())
1354 .collect::<Vec<_>>().join("`, `"));
1355 err.span_label(impl_span, format!("missing `{}` in implementation",
1356 missing_items.iter()
1357 .map(|trait_item| trait_item.name.to_string())
1358 .collect::<Vec<_>>().join("`, `")));
1359 for trait_item in missing_items {
1360 if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
1361 err.span_label(span, format!("`{}` from trait", trait_item.name));
1363 err.note(&format!("`{}` from trait: `{}`",
1365 signature(&trait_item)));
1371 if !invalidated_items.is_empty() {
1372 let invalidator = overridden_associated_type.unwrap();
1373 span_err!(tcx.sess, invalidator.span, E0399,
1374 "the following trait items need to be reimplemented \
1375 as `{}` was overridden: `{}`",
1377 invalidated_items.iter()
1378 .map(|name| name.to_string())
1379 .collect::<Vec<_>>().join("`, `"))
1383 /// Checks whether a type can be represented in memory. In particular, it
1384 /// identifies types that contain themselves without indirection through a
1385 /// pointer, which would mean their size is unbounded.
1386 fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1390 let rty = tcx.type_of(item_def_id);
1392 // Check that it is possible to represent this type. This call identifies
1393 // (1) types that contain themselves and (2) types that contain a different
1394 // recursive type. It is only necessary to throw an error on those that
1395 // contain themselves. For case 2, there must be an inner type that will be
1396 // caught by case 1.
1397 match rty.is_representable(tcx, sp) {
1398 Representability::SelfRecursive(spans) => {
1399 let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
1401 err.span_label(span, "recursive without indirection");
1406 Representability::Representable | Representability::ContainsRecursive => (),
1411 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1412 let t = tcx.type_of(def_id);
1414 ty::TyAdt(def, substs) if def.is_struct() => {
1415 let fields = &def.struct_variant().fields;
1416 if fields.is_empty() {
1417 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1420 let e = fields[0].ty(tcx, substs);
1421 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1422 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1423 .span_label(sp, "SIMD elements must have the same type")
1428 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1429 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1431 span_err!(tcx.sess, sp, E0077,
1432 "SIMD vector element type should be machine type");
1441 fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1442 if check_packed_inner(tcx, def_id, &mut Vec::new()) {
1443 struct_span_err!(tcx.sess, sp, E0588,
1444 "packed struct cannot transitively contain a `[repr(align)]` struct").emit();
1448 fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1450 stack: &mut Vec<DefId>) -> bool {
1451 let t = tcx.type_of(def_id);
1452 if stack.contains(&def_id) {
1453 debug!("check_packed_inner: {:?} is recursive", t);
1457 ty::TyAdt(def, substs) if def.is_struct() => {
1458 if tcx.adt_def(def.did).repr.align > 0 {
1461 // push struct def_id before checking fields
1463 for field in &def.struct_variant().fields {
1464 let f = field.ty(tcx, substs);
1466 ty::TyAdt(def, _) => {
1467 if check_packed_inner(tcx, def.did, stack) {
1474 // only need to pop if not early out
1482 #[allow(trivial_numeric_casts)]
1483 pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1485 vs: &'tcx [hir::Variant],
1487 let def_id = tcx.hir.local_def_id(id);
1488 let def = tcx.adt_def(def_id);
1489 def.destructor(tcx); // force the destructor to be evaluated
1491 if vs.is_empty() && tcx.has_attr(def_id, "repr") {
1493 tcx.sess, sp, E0084,
1494 "unsupported representation for zero-variant enum")
1495 .span_label(sp, "unsupported enum representation")
1499 let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1500 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1501 if !tcx.sess.features.borrow().i128_type {
1502 emit_feature_err(&tcx.sess.parse_sess,
1503 "i128_type", sp, GateIssue::Language, "128-bit type is unstable");
1508 if let Some(e) = v.node.disr_expr {
1509 tcx.typeck_tables_of(tcx.hir.local_def_id(e.node_id));
1513 let mut disr_vals: Vec<ConstInt> = Vec::new();
1514 for (discr, v) in def.discriminants(tcx).zip(vs) {
1515 // Check for duplicate discriminant values
1516 if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
1517 let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
1518 let variant_i = tcx.hir.expect_variant(variant_i_node_id);
1519 let i_span = match variant_i.node.disr_expr {
1520 Some(expr) => tcx.hir.span(expr.node_id),
1521 None => tcx.hir.span(variant_i_node_id)
1523 let span = match v.node.disr_expr {
1524 Some(expr) => tcx.hir.span(expr.node_id),
1527 struct_span_err!(tcx.sess, span, E0081,
1528 "discriminant value `{}` already exists", disr_vals[i])
1529 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1530 .span_label(span , format!("enum already has `{}`", disr_vals[i]))
1533 disr_vals.push(discr);
1536 check_representable(tcx, sp, def_id);
1539 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1540 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1542 fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
1543 -> ty::GenericPredicates<'tcx>
1546 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1547 let item_id = tcx.hir.ty_param_owner(node_id);
1548 let item_def_id = tcx.hir.local_def_id(item_id);
1549 let generics = tcx.generics_of(item_def_id);
1550 let index = generics.type_param_to_index[&def_id.index];
1551 ty::GenericPredicates {
1553 predicates: self.param_env.caller_bounds.iter().filter(|predicate| {
1555 ty::Predicate::Trait(ref data) => {
1556 data.0.self_ty().is_param(index)
1560 }).cloned().collect()
1564 fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
1565 -> Option<ty::Region<'tcx>> {
1567 Some(def) => infer::EarlyBoundRegion(span, def.name, def.issue_32330),
1568 None => infer::MiscVariable(span)
1570 Some(self.next_region_var(v))
1573 fn ty_infer(&self, span: Span) -> Ty<'tcx> {
1574 self.next_ty_var(TypeVariableOrigin::TypeInference(span))
1577 fn ty_infer_for_def(&self,
1578 ty_param_def: &ty::TypeParameterDef,
1579 substs: &[Kind<'tcx>],
1580 span: Span) -> Ty<'tcx> {
1581 self.type_var_for_def(span, ty_param_def, substs)
1584 fn projected_ty_from_poly_trait_ref(&self,
1586 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1587 item_name: ast::Name)
1590 let (trait_ref, _) =
1591 self.replace_late_bound_regions_with_fresh_var(
1593 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1596 self.tcx().mk_projection(trait_ref, item_name)
1599 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1600 if ty.has_escaping_regions() {
1601 ty // FIXME: normalization and escaping regions
1603 self.normalize_associated_types_in(span, &ty)
1607 fn set_tainted_by_errors(&self) {
1608 self.infcx.set_tainted_by_errors()
1612 /// Controls whether the arguments are tupled. This is used for the call
1615 /// Tupling means that all call-side arguments are packed into a tuple and
1616 /// passed as a single parameter. For example, if tupling is enabled, this
1619 /// fn f(x: (isize, isize))
1621 /// Can be called as:
1628 #[derive(Clone, Eq, PartialEq)]
1629 enum TupleArgumentsFlag {
1634 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1635 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1636 body_id: ast::NodeId)
1637 -> FnCtxt<'a, 'gcx, 'tcx> {
1640 err_count_on_creation: inh.tcx.sess.err_count(),
1642 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
1643 ast::CRATE_NODE_ID)),
1644 diverges: Cell::new(Diverges::Maybe),
1645 has_errors: Cell::new(false),
1646 enclosing_breakables: RefCell::new(EnclosingBreakables {
1654 pub fn sess(&self) -> &Session {
1658 pub fn err_count_since_creation(&self) -> usize {
1659 self.tcx.sess.err_count() - self.err_count_on_creation
1662 /// Produce warning on the given node, if the current point in the
1663 /// function is unreachable, and there hasn't been another warning.
1664 fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
1665 if self.diverges.get() == Diverges::Always {
1666 self.diverges.set(Diverges::WarnedAlways);
1668 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
1670 self.tables.borrow_mut().lints.add_lint(
1671 lint::builtin::UNREACHABLE_CODE,
1673 format!("unreachable {}", kind));
1679 code: ObligationCauseCode<'tcx>)
1680 -> ObligationCause<'tcx> {
1681 ObligationCause::new(span, self.body_id, code)
1684 pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
1685 self.cause(span, ObligationCauseCode::MiscObligation)
1688 /// Resolves type variables in `ty` if possible. Unlike the infcx
1689 /// version (resolve_type_vars_if_possible), this version will
1690 /// also select obligations if it seems useful, in an effort
1691 /// to get more type information.
1692 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1693 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1695 // No TyInfer()? Nothing needs doing.
1696 if !ty.has_infer_types() {
1697 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1701 // If `ty` is a type variable, see whether we already know what it is.
1702 ty = self.resolve_type_vars_if_possible(&ty);
1703 if !ty.has_infer_types() {
1704 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1708 // If not, try resolving pending obligations as much as
1709 // possible. This can help substantially when there are
1710 // indirect dependencies that don't seem worth tracking
1712 self.select_obligations_where_possible();
1713 ty = self.resolve_type_vars_if_possible(&ty);
1715 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1719 fn record_deferred_call_resolution(&self,
1720 closure_def_id: DefId,
1721 r: DeferredCallResolution<'gcx, 'tcx>) {
1722 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1723 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1726 fn remove_deferred_call_resolutions(&self,
1727 closure_def_id: DefId)
1728 -> Vec<DeferredCallResolution<'gcx, 'tcx>>
1730 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1731 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![])
1734 pub fn tag(&self) -> String {
1735 let self_ptr: *const FnCtxt = self;
1736 format!("{:?}", self_ptr)
1739 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1740 match self.locals.borrow().get(&nid) {
1743 span_bug!(span, "no type for local variable {}",
1744 self.tcx.hir.node_to_string(nid));
1750 pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
1751 debug!("write_ty({}, {:?}) in fcx {}",
1752 node_id, self.resolve_type_vars_if_possible(&ty), self.tag());
1753 self.tables.borrow_mut().node_types.insert(node_id, ty);
1755 if ty.references_error() {
1756 self.has_errors.set(true);
1757 self.set_tainted_by_errors();
1761 pub fn write_method_call(&self, node_id: ast::NodeId, method: MethodCallee<'tcx>) {
1762 self.tables.borrow_mut().type_dependent_defs.insert(node_id, Def::Method(method.def_id));
1763 self.write_substs(node_id, method.substs);
1766 pub fn write_substs(&self, node_id: ast::NodeId, substs: &'tcx Substs<'tcx>) {
1767 if !substs.is_noop() {
1768 debug!("write_substs({}, {:?}) in fcx {}",
1773 self.tables.borrow_mut().node_substs.insert(node_id, substs);
1777 pub fn apply_autoderef_adjustment(&self,
1778 node_id: ast::NodeId,
1779 autoderefs: Vec<Option<OverloadedDeref<'tcx>>>,
1780 adjusted_ty: Ty<'tcx>) {
1781 self.apply_adjustment(node_id, Adjustment {
1782 kind: Adjust::Deref(autoderefs),
1789 pub fn apply_adjustment(&self, node_id: ast::NodeId, adj: Adjustment<'tcx>) {
1790 debug!("apply_adjustment(node_id={}, adj={:?})", node_id, adj);
1792 if adj.is_identity() {
1796 match self.tables.borrow_mut().adjustments.entry(node_id) {
1797 Entry::Vacant(entry) => { entry.insert(adj); },
1798 Entry::Occupied(mut entry) => {
1799 debug!(" - composing on top of {:?}", entry.get());
1800 match (entry.get(), &adj) {
1801 // Applying any adjustment on top of a NeverToAny
1802 // is a valid NeverToAny adjustment, because it can't
1804 (&Adjustment { kind: Adjust::NeverToAny, .. }, _) => return,
1806 kind: Adjust::Deref(ref old),
1807 autoref: Some(AutoBorrow::Ref(..)),
1810 kind: Adjust::Deref(ref new), ..
1811 }) if old.len() == 1 && new.len() >= 1 => {
1812 // A reborrow has no effect before a dereference.
1814 // FIXME: currently we never try to compose autoderefs
1815 // and ReifyFnPointer/UnsafeFnPointer, but we could.
1817 bug!("while adjusting {}, can't compose {:?} and {:?}",
1818 node_id, entry.get(), adj)
1820 *entry.get_mut() = adj;
1825 /// Basically whenever we are converting from a type scheme into
1826 /// the fn body space, we always want to normalize associated
1827 /// types as well. This function combines the two.
1828 fn instantiate_type_scheme<T>(&self,
1830 substs: &Substs<'tcx>,
1833 where T : TypeFoldable<'tcx>
1835 let value = value.subst(self.tcx, substs);
1836 let result = self.normalize_associated_types_in(span, &value);
1837 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1844 /// As `instantiate_type_scheme`, but for the bounds found in a
1845 /// generic type scheme.
1846 fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
1847 -> ty::InstantiatedPredicates<'tcx> {
1848 let bounds = self.tcx.predicates_of(def_id);
1849 let result = bounds.instantiate(self.tcx, substs);
1850 let result = self.normalize_associated_types_in(span, &result);
1851 debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
1858 /// Replace all anonymized types with fresh inference variables
1859 /// and record them for writeback.
1860 fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
1861 value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
1862 if let ty::TyAnon(def_id, substs) = ty.sty {
1863 // Use the same type variable if the exact same TyAnon appears more
1864 // than once in the return type (e.g. if it's pased to a type alias).
1865 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1866 if let Some(ty_var) = self.anon_types.borrow().get(&id) {
1869 let span = self.tcx.def_span(def_id);
1870 let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
1871 self.anon_types.borrow_mut().insert(id, ty_var);
1873 let predicates_of = self.tcx.predicates_of(def_id);
1874 let bounds = predicates_of.instantiate(self.tcx, substs);
1876 for predicate in bounds.predicates {
1877 // Change the predicate to refer to the type variable,
1878 // which will be the concrete type, instead of the TyAnon.
1879 // This also instantiates nested `impl Trait`.
1880 let predicate = self.instantiate_anon_types(&predicate);
1882 // Require that the predicate holds for the concrete type.
1883 let cause = traits::ObligationCause::new(span, self.body_id,
1884 traits::ReturnType);
1885 self.register_predicate(traits::Obligation::new(cause, predicate));
1895 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1896 where T : TypeFoldable<'tcx>
1898 let ok = self.normalize_associated_types_in_as_infer_ok(span, value);
1899 self.register_infer_ok_obligations(ok)
1902 fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T)
1904 where T : TypeFoldable<'tcx>
1906 self.inh.normalize_associated_types_in_as_infer_ok(span, self.body_id, value)
1909 pub fn write_nil(&self, node_id: ast::NodeId) {
1910 self.write_ty(node_id, self.tcx.mk_nil());
1913 pub fn write_error(&self, node_id: ast::NodeId) {
1914 self.write_ty(node_id, self.tcx.types.err);
1917 pub fn require_type_meets(&self,
1920 code: traits::ObligationCauseCode<'tcx>,
1923 self.register_bound(
1926 traits::ObligationCause::new(span, self.body_id, code));
1929 pub fn require_type_is_sized(&self,
1932 code: traits::ObligationCauseCode<'tcx>)
1934 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1935 self.require_type_meets(ty, span, code, lang_item);
1938 pub fn register_bound(&self,
1941 cause: traits::ObligationCause<'tcx>)
1943 self.fulfillment_cx.borrow_mut()
1944 .register_bound(self, ty, def_id, cause);
1947 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
1948 let t = AstConv::ast_ty_to_ty(self, ast_t);
1949 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1953 pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
1954 match self.tables.borrow().node_types.get(&id) {
1956 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1958 bug!("no type for node {}: {} in fcx {}",
1959 id, self.tcx.hir.node_to_string(id),
1965 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1966 /// outlive the region `r`.
1967 pub fn register_region_obligation(&self,
1969 region: ty::Region<'tcx>,
1970 cause: traits::ObligationCause<'tcx>)
1972 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
1973 fulfillment_cx.register_region_obligation(ty, region, cause);
1976 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1977 /// outlive the region `r`.
1978 pub fn register_wf_obligation(&self,
1981 code: traits::ObligationCauseCode<'tcx>)
1983 // WF obligations never themselves fail, so no real need to give a detailed cause:
1984 let cause = traits::ObligationCause::new(span, self.body_id, code);
1985 self.register_predicate(traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
1988 pub fn register_old_wf_obligation(&self,
1991 code: traits::ObligationCauseCode<'tcx>)
1993 // Registers an "old-style" WF obligation that uses the
1994 // implicator code. This is basically a buggy version of
1995 // `register_wf_obligation` that is being kept around
1996 // temporarily just to help with phasing in the newer rules.
1998 // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
1999 let cause = traits::ObligationCause::new(span, self.body_id, code);
2000 self.register_region_obligation(ty, self.tcx.types.re_empty, cause);
2003 /// Registers obligations that all types appearing in `substs` are well-formed.
2004 pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
2006 for ty in substs.types() {
2007 self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
2011 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
2012 /// type/region parameter was instantiated (`substs`), creates and registers suitable
2013 /// trait/region obligations.
2015 /// For example, if there is a function:
2018 /// fn foo<'a,T:'a>(...)
2021 /// and a reference:
2027 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
2028 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
2029 pub fn add_obligations_for_parameters(&self,
2030 cause: traits::ObligationCause<'tcx>,
2031 predicates: &ty::InstantiatedPredicates<'tcx>)
2033 assert!(!predicates.has_escaping_regions());
2035 debug!("add_obligations_for_parameters(predicates={:?})",
2038 for obligation in traits::predicates_for_generics(cause, predicates) {
2039 self.register_predicate(obligation);
2043 // FIXME(arielb1): use this instead of field.ty everywhere
2044 // Only for fields! Returns <none> for methods>
2045 // Indifferent to privacy flags
2046 pub fn field_ty(&self,
2048 field: &'tcx ty::FieldDef,
2049 substs: &Substs<'tcx>)
2052 self.normalize_associated_types_in(span,
2053 &field.ty(self.tcx, substs))
2056 fn check_casts(&self) {
2057 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
2058 for cast in deferred_cast_checks.drain(..) {
2063 /// Apply "fallbacks" to some types
2064 /// unconstrained types get replaced with ! or () (depending on whether
2065 /// feature(never_type) is enabled), unconstrained ints with i32, and
2066 /// unconstrained floats with f64.
2067 fn default_type_parameters(&self) {
2068 use rustc::ty::error::UnconstrainedNumeric::Neither;
2069 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
2071 // Defaulting inference variables becomes very dubious if we have
2072 // encountered type-checking errors. Therefore, if we think we saw
2073 // some errors in this function, just resolve all uninstanted type
2074 // varibles to TyError.
2075 if self.is_tainted_by_errors() {
2076 for ty in &self.unsolved_variables() {
2077 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
2078 debug!("default_type_parameters: defaulting `{:?}` to error", ty);
2079 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
2085 for ty in &self.unsolved_variables() {
2086 let resolved = self.resolve_type_vars_if_possible(ty);
2087 if self.type_var_diverges(resolved) {
2088 debug!("default_type_parameters: defaulting `{:?}` to `!` because it diverges",
2090 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
2091 self.tcx.mk_diverging_default());
2093 match self.type_is_unconstrained_numeric(resolved) {
2094 UnconstrainedInt => {
2095 debug!("default_type_parameters: defaulting `{:?}` to `i32`",
2097 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
2099 UnconstrainedFloat => {
2100 debug!("default_type_parameters: defaulting `{:?}` to `f32`",
2102 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
2110 // Implements type inference fallback algorithm
2111 fn select_all_obligations_and_apply_defaults(&self) {
2112 self.select_obligations_where_possible();
2113 self.default_type_parameters();
2114 self.select_obligations_where_possible();
2117 fn select_all_obligations_or_error(&self) {
2118 debug!("select_all_obligations_or_error");
2120 // upvar inference should have ensured that all deferred call
2121 // resolutions are handled by now.
2122 assert!(self.deferred_call_resolutions.borrow().is_empty());
2124 self.select_all_obligations_and_apply_defaults();
2126 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2128 match fulfillment_cx.select_all_or_error(self) {
2130 Err(errors) => { self.report_fulfillment_errors(&errors); }
2134 /// Select as many obligations as we can at present.
2135 fn select_obligations_where_possible(&self) {
2136 match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
2138 Err(errors) => { self.report_fulfillment_errors(&errors); }
2142 /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2143 /// returns a type of `&T`, but the actual type we assign to the
2144 /// *expression* is `T`. So this function just peels off the return
2145 /// type by one layer to yield `T`.
2146 fn make_overloaded_lvalue_return_type(&self,
2147 method: MethodCallee<'tcx>)
2148 -> ty::TypeAndMut<'tcx>
2150 // extract method return type, which will be &T;
2151 // all LB regions should have been instantiated during method lookup
2152 let ret_ty = method.sig.output();
2154 // method returns &T, but the type as visible to user is T, so deref
2155 ret_ty.builtin_deref(true, NoPreference).unwrap()
2158 fn lookup_indexing(&self,
2160 base_expr: &'gcx hir::Expr,
2163 lvalue_pref: LvaluePreference)
2164 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2166 // FIXME(#18741) -- this is almost but not quite the same as the
2167 // autoderef that normal method probing does. They could likely be
2170 let mut autoderef = self.autoderef(base_expr.span, base_ty);
2171 let mut result = None;
2172 while result.is_none() && autoderef.next().is_some() {
2173 result = self.try_index_step(expr, base_expr, &autoderef, lvalue_pref, idx_ty);
2175 autoderef.finalize();
2179 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2180 /// (and otherwise adjust) `base_expr`, looking for a type which either
2181 /// supports builtin indexing or overloaded indexing.
2182 /// This loop implements one step in that search; the autoderef loop
2183 /// is implemented by `lookup_indexing`.
2184 fn try_index_step(&self,
2186 base_expr: &hir::Expr,
2187 autoderef: &Autoderef<'a, 'gcx, 'tcx>,
2188 lvalue_pref: LvaluePreference,
2190 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2192 let mut adjusted_ty = autoderef.unambiguous_final_ty();
2193 debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
2201 // First, try built-in indexing.
2202 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2203 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2204 debug!("try_index_step: success, using built-in indexing");
2205 let autoderefs = autoderef.adjust_steps(lvalue_pref);
2206 self.apply_autoderef_adjustment(
2207 base_expr.id, autoderefs, adjusted_ty);
2208 return Some((self.tcx.types.usize, ty));
2213 for &unsize in &[false, true] {
2215 // We only unsize arrays here.
2216 if let ty::TyArray(element_ty, _) = adjusted_ty.sty {
2217 adjusted_ty = self.tcx.mk_slice(element_ty);
2223 // If some lookup succeeds, write callee into table and extract index/element
2224 // type from the method signature.
2225 // If some lookup succeeded, install method in table
2226 let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_expr.span));
2227 let method = self.try_overloaded_lvalue_op(
2228 expr.span, adjusted_ty, &[input_ty], lvalue_pref, LvalueOp::Index);
2230 let result = method.map(|ok| {
2231 debug!("try_index_step: success, using overloaded indexing");
2232 let (autoref, method) = self.register_infer_ok_obligations(ok);
2234 let autoderefs = autoderef.adjust_steps(lvalue_pref);
2235 self.apply_adjustment(base_expr.id, Adjustment {
2236 kind: Adjust::Deref(autoderefs),
2239 target: method.sig.inputs()[0]
2242 self.write_method_call(expr.id, method);
2243 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2245 if result.is_some() {
2253 fn resolve_lvalue_op(&self, op: LvalueOp, is_mut: bool) -> (Option<DefId>, Symbol) {
2254 let (tr, name) = match (op, is_mut) {
2255 (LvalueOp::Deref, false) =>
2256 (self.tcx.lang_items.deref_trait(), "deref"),
2257 (LvalueOp::Deref, true) =>
2258 (self.tcx.lang_items.deref_mut_trait(), "deref_mut"),
2259 (LvalueOp::Index, false) =>
2260 (self.tcx.lang_items.index_trait(), "index"),
2261 (LvalueOp::Index, true) =>
2262 (self.tcx.lang_items.index_mut_trait(), "index_mut"),
2264 (tr, Symbol::intern(name))
2267 fn try_overloaded_lvalue_op(&self,
2270 arg_tys: &[Ty<'tcx>],
2271 lvalue_pref: LvaluePreference,
2273 -> Option<InferOk<'tcx,
2274 (Option<AutoBorrow<'tcx>>,
2275 MethodCallee<'tcx>)>>
2277 debug!("try_overloaded_lvalue_op({:?},{:?},{:?},{:?})",
2283 // Try Mut first, if preferred.
2284 let (mut_tr, mut_op) = self.resolve_lvalue_op(op, true);
2285 let method = match (lvalue_pref, mut_tr) {
2286 (PreferMutLvalue, Some(trait_did)) => {
2287 self.lookup_method_in_trait_adjusted(span,
2296 // Otherwise, fall back to the immutable version.
2297 let (imm_tr, imm_op) = self.resolve_lvalue_op(op, false);
2298 let method = match (method, imm_tr) {
2299 (None, Some(trait_did)) => {
2300 self.lookup_method_in_trait_adjusted(span,
2306 (method, _) => method,
2312 fn check_method_argument_types(&self,
2314 method: Result<MethodCallee<'tcx>, ()>,
2315 args_no_rcvr: &'gcx [hir::Expr],
2316 tuple_arguments: TupleArgumentsFlag,
2317 expected: Expectation<'tcx>)
2319 let has_error = match method {
2321 method.substs.references_error() || method.sig.references_error()
2326 let err_inputs = self.err_args(args_no_rcvr.len());
2328 let err_inputs = match tuple_arguments {
2329 DontTupleArguments => err_inputs,
2330 TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
2333 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2334 false, tuple_arguments, None);
2335 return self.tcx.types.err;
2338 let method = method.unwrap();
2339 // HACK(eddyb) ignore self in the definition (see above).
2340 let expected_arg_tys = self.expected_inputs_for_expected_output(
2343 method.sig.output(),
2344 &method.sig.inputs()[1..]
2346 self.check_argument_types(sp, &method.sig.inputs()[1..], &expected_arg_tys[..],
2347 args_no_rcvr, method.sig.variadic, tuple_arguments,
2348 self.tcx.hir.span_if_local(method.def_id));
2352 /// Generic function that factors out common logic from function calls,
2353 /// method calls and overloaded operators.
2354 fn check_argument_types(&self,
2356 fn_inputs: &[Ty<'tcx>],
2357 expected_arg_tys: &[Ty<'tcx>],
2358 args: &'gcx [hir::Expr],
2360 tuple_arguments: TupleArgumentsFlag,
2361 def_span: Option<Span>) {
2364 // Grab the argument types, supplying fresh type variables
2365 // if the wrong number of arguments were supplied
2366 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2372 // All the input types from the fn signature must outlive the call
2373 // so as to validate implied bounds.
2374 for &fn_input_ty in fn_inputs {
2375 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2378 let mut expected_arg_tys = expected_arg_tys;
2379 let expected_arg_count = fn_inputs.len();
2381 let sp_args = if args.len() > 0 {
2382 let (first, args) = args.split_at(1);
2383 let mut sp_tmp = first[0].span;
2385 let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
2386 if ! sp_opt.is_some() {
2389 sp_tmp = sp_opt.unwrap();
2396 fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
2397 arg_count: usize, error_code: &str, variadic: bool,
2398 def_span: Option<Span>) {
2399 let mut err = sess.struct_span_err_with_code(sp,
2400 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2401 if variadic {"at least "} else {""},
2403 if expected_count == 1 {""} else {"s"},
2405 if arg_count == 1 {" was"} else {"s were"}),
2408 err.span_label(sp, format!("expected {}{} parameter{}",
2409 if variadic {"at least "} else {""},
2411 if expected_count == 1 {""} else {"s"}));
2412 if let Some(def_s) = def_span {
2413 err.span_label(def_s, "defined here");
2418 let formal_tys = if tuple_arguments == TupleArguments {
2419 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2420 match tuple_type.sty {
2421 ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
2422 parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
2423 "E0057", false, def_span);
2424 expected_arg_tys = &[];
2425 self.err_args(args.len())
2427 ty::TyTuple(arg_types, _) => {
2428 expected_arg_tys = match expected_arg_tys.get(0) {
2429 Some(&ty) => match ty.sty {
2430 ty::TyTuple(ref tys, _) => &tys,
2438 span_err!(tcx.sess, sp, E0059,
2439 "cannot use call notation; the first type parameter \
2440 for the function trait is neither a tuple nor unit");
2441 expected_arg_tys = &[];
2442 self.err_args(args.len())
2445 } else if expected_arg_count == supplied_arg_count {
2447 } else if variadic {
2448 if supplied_arg_count >= expected_arg_count {
2451 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2452 supplied_arg_count, "E0060", true, def_span);
2453 expected_arg_tys = &[];
2454 self.err_args(supplied_arg_count)
2457 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2458 supplied_arg_count, "E0061", false, def_span);
2459 expected_arg_tys = &[];
2460 self.err_args(supplied_arg_count)
2463 debug!("check_argument_types: formal_tys={:?}",
2464 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2466 // Check the arguments.
2467 // We do this in a pretty awful way: first we typecheck any arguments
2468 // that are not closures, then we typecheck the closures. This is so
2469 // that we have more information about the types of arguments when we
2470 // typecheck the functions. This isn't really the right way to do this.
2471 for &check_closures in &[false, true] {
2472 debug!("check_closures={}", check_closures);
2474 // More awful hacks: before we check argument types, try to do
2475 // an "opportunistic" vtable resolution of any trait bounds on
2476 // the call. This helps coercions.
2478 self.select_obligations_where_possible();
2481 // For variadic functions, we don't have a declared type for all of
2482 // the arguments hence we only do our usual type checking with
2483 // the arguments who's types we do know.
2484 let t = if variadic {
2486 } else if tuple_arguments == TupleArguments {
2491 for (i, arg) in args.iter().take(t).enumerate() {
2492 // Warn only for the first loop (the "no closures" one).
2493 // Closure arguments themselves can't be diverging, but
2494 // a previous argument can, e.g. `foo(panic!(), || {})`.
2495 if !check_closures {
2496 self.warn_if_unreachable(arg.id, arg.span, "expression");
2499 let is_closure = match arg.node {
2500 hir::ExprClosure(..) => true,
2504 if is_closure != check_closures {
2508 debug!("checking the argument");
2509 let formal_ty = formal_tys[i];
2511 // The special-cased logic below has three functions:
2512 // 1. Provide as good of an expected type as possible.
2513 let expected = expected_arg_tys.get(i).map(|&ty| {
2514 Expectation::rvalue_hint(self, ty)
2517 let checked_ty = self.check_expr_with_expectation(
2519 expected.unwrap_or(ExpectHasType(formal_ty)));
2521 // 2. Coerce to the most detailed type that could be coerced
2522 // to, which is `expected_ty` if `rvalue_hint` returns an
2523 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2524 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2525 self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
2527 // 3. Relate the expected type and the formal one,
2528 // if the expected type was used for the coercion.
2529 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2533 // We also need to make sure we at least write the ty of the other
2534 // arguments which we skipped above.
2536 for arg in args.iter().skip(expected_arg_count) {
2537 let arg_ty = self.check_expr(&arg);
2539 // There are a few types which get autopromoted when passed via varargs
2540 // in C but we just error out instead and require explicit casts.
2541 let arg_ty = self.structurally_resolved_type(arg.span,
2544 ty::TyFloat(ast::FloatTy::F32) => {
2545 self.type_error_message(arg.span, |t| {
2546 format!("can't pass an `{}` to variadic \
2547 function, cast to `c_double`", t)
2550 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2551 self.type_error_message(arg.span, |t| {
2552 format!("can't pass `{}` to variadic \
2553 function, cast to `c_int`",
2557 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2558 self.type_error_message(arg.span, |t| {
2559 format!("can't pass `{}` to variadic \
2560 function, cast to `c_uint`",
2564 ty::TyFnDef(.., f) => {
2565 let ptr_ty = self.tcx.mk_fn_ptr(f);
2566 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2567 self.type_error_message(arg.span,
2569 format!("can't pass `{}` to variadic \
2570 function, cast to `{}`", t, ptr_ty)
2579 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2580 (0..len).map(|_| self.tcx.types.err).collect()
2583 // AST fragment checking
2586 expected: Expectation<'tcx>)
2592 ast::LitKind::Str(..) => tcx.mk_static_str(),
2593 ast::LitKind::ByteStr(ref v) => {
2594 tcx.mk_imm_ref(tcx.types.re_static,
2595 tcx.mk_array(tcx.types.u8, v.len()))
2597 ast::LitKind::Byte(_) => tcx.types.u8,
2598 ast::LitKind::Char(_) => tcx.types.char,
2599 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2600 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2601 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2602 let opt_ty = expected.to_option(self).and_then(|ty| {
2604 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2605 ty::TyChar => Some(tcx.types.u8),
2606 ty::TyRawPtr(..) => Some(tcx.types.usize),
2607 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2611 opt_ty.unwrap_or_else(
2612 || tcx.mk_int_var(self.next_int_var_id()))
2614 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2615 ast::LitKind::FloatUnsuffixed(_) => {
2616 let opt_ty = expected.to_option(self).and_then(|ty| {
2618 ty::TyFloat(_) => Some(ty),
2622 opt_ty.unwrap_or_else(
2623 || tcx.mk_float_var(self.next_float_var_id()))
2625 ast::LitKind::Bool(_) => tcx.types.bool
2629 fn check_expr_eq_type(&self,
2630 expr: &'gcx hir::Expr,
2631 expected: Ty<'tcx>) {
2632 let ty = self.check_expr_with_hint(expr, expected);
2633 self.demand_eqtype(expr.span, expected, ty);
2636 pub fn check_expr_has_type(&self,
2637 expr: &'gcx hir::Expr,
2638 expected: Ty<'tcx>) -> Ty<'tcx> {
2639 let mut ty = self.check_expr_with_hint(expr, expected);
2641 // While we don't allow *arbitrary* coercions here, we *do* allow
2642 // coercions from ! to `expected`.
2644 assert!(!self.tables.borrow().adjustments.contains_key(&expr.id),
2645 "expression with never type wound up being adjusted");
2646 let adj_ty = self.next_diverging_ty_var(
2647 TypeVariableOrigin::AdjustmentType(expr.span));
2648 self.apply_adjustment(expr.id, Adjustment {
2649 kind: Adjust::NeverToAny,
2657 self.demand_suptype(expr.span, expected, ty);
2661 fn check_expr_coercable_to_type(&self,
2662 expr: &'gcx hir::Expr,
2663 expected: Ty<'tcx>) -> Ty<'tcx> {
2664 let ty = self.check_expr_with_hint(expr, expected);
2665 self.demand_coerce(expr, ty, expected);
2669 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2670 expected: Ty<'tcx>) -> Ty<'tcx> {
2671 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2674 fn check_expr_with_expectation(&self,
2675 expr: &'gcx hir::Expr,
2676 expected: Expectation<'tcx>) -> Ty<'tcx> {
2677 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2680 fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
2681 self.check_expr_with_expectation(expr, NoExpectation)
2684 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2685 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2686 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2689 // determine the `self` type, using fresh variables for all variables
2690 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2691 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2693 pub fn impl_self_ty(&self,
2694 span: Span, // (potential) receiver for this impl
2696 -> TypeAndSubsts<'tcx> {
2697 let ity = self.tcx.type_of(did);
2698 debug!("impl_self_ty: ity={:?}", ity);
2700 let substs = self.fresh_substs_for_item(span, did);
2701 let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
2703 TypeAndSubsts { substs: substs, ty: substd_ty }
2706 /// Unifies the output type with the expected type early, for more coercions
2707 /// and forward type information on the input expressions.
2708 fn expected_inputs_for_expected_output(&self,
2710 expected_ret: Expectation<'tcx>,
2711 formal_ret: Ty<'tcx>,
2712 formal_args: &[Ty<'tcx>])
2714 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2715 self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
2716 // Attempt to apply a subtyping relationship between the formal
2717 // return type (likely containing type variables if the function
2718 // is polymorphic) and the expected return type.
2719 // No argument expectations are produced if unification fails.
2720 let origin = self.misc(call_span);
2721 let ures = self.sub_types(false, &origin, formal_ret, ret_ty);
2723 // FIXME(#15760) can't use try! here, FromError doesn't default
2724 // to identity so the resulting type is not constrained.
2727 // Process any obligations locally as much as
2728 // we can. We don't care if some things turn
2729 // out unconstrained or ambiguous, as we're
2730 // just trying to get hints here.
2731 let result = self.save_and_restore_in_snapshot_flag(|_| {
2732 let mut fulfill = FulfillmentContext::new();
2733 let ok = ok; // FIXME(#30046)
2734 for obligation in ok.obligations {
2735 fulfill.register_predicate_obligation(self, obligation);
2737 fulfill.select_where_possible(self)
2742 Err(_) => return Err(()),
2745 Err(_) => return Err(()),
2748 // Record all the argument types, with the substitutions
2749 // produced from the above subtyping unification.
2750 Ok(formal_args.iter().map(|ty| {
2751 self.resolve_type_vars_if_possible(ty)
2754 }).unwrap_or(vec![]);
2755 debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
2756 formal_args, formal_ret,
2757 expected_args, expected_ret);
2761 // Checks a method call.
2762 fn check_method_call(&self,
2763 expr: &'gcx hir::Expr,
2764 method_name: Spanned<ast::Name>,
2765 args: &'gcx [hir::Expr],
2767 expected: Expectation<'tcx>,
2768 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2769 let rcvr = &args[0];
2770 let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2772 // no need to check for bot/err -- callee does that
2773 let expr_t = self.structurally_resolved_type(expr.span, rcvr_t);
2775 let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2776 let method = match self.lookup_method(method_name.span,
2783 self.write_method_call(expr.id, method);
2787 if method_name.node != keywords::Invalid.name() {
2788 self.report_method_error(method_name.span,
2799 // Call the generic checker.
2800 self.check_method_argument_types(method_name.span, method,
2806 fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
2810 .unwrap_or_else(|| span_bug!(return_expr.span,
2811 "check_return_expr called outside fn body"));
2813 let ret_ty = ret_coercion.borrow().expected_ty();
2814 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
2815 ret_coercion.borrow_mut()
2817 &self.misc(return_expr.span),
2820 self.diverges.get());
2824 // A generic function for checking the then and else in an if
2826 fn check_then_else(&self,
2827 cond_expr: &'gcx hir::Expr,
2828 then_expr: &'gcx hir::Expr,
2829 opt_else_expr: Option<&'gcx hir::Expr>,
2831 expected: Expectation<'tcx>) -> Ty<'tcx> {
2832 let cond_ty = self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2833 let cond_diverges = self.diverges.get();
2834 self.diverges.set(Diverges::Maybe);
2836 let expected = expected.adjust_for_branches(self);
2837 let then_ty = self.check_expr_with_expectation(then_expr, expected);
2838 let then_diverges = self.diverges.get();
2839 self.diverges.set(Diverges::Maybe);
2841 // We've already taken the expected type's preferences
2842 // into account when typing the `then` branch. To figure
2843 // out the initial shot at a LUB, we thus only consider
2844 // `expected` if it represents a *hard* constraint
2845 // (`only_has_type`); otherwise, we just go with a
2846 // fresh type variable.
2847 let coerce_to_ty = expected.coercion_target_type(self, sp);
2848 let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty);
2850 let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
2851 coerce.coerce(self, &if_cause, then_expr, then_ty, then_diverges);
2853 if let Some(else_expr) = opt_else_expr {
2854 let else_ty = self.check_expr_with_expectation(else_expr, expected);
2855 let else_diverges = self.diverges.get();
2857 coerce.coerce(self, &if_cause, else_expr, else_ty, else_diverges);
2859 // We won't diverge unless both branches do (or the condition does).
2860 self.diverges.set(cond_diverges | then_diverges & else_diverges);
2862 let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
2863 coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true);
2865 // If the condition is false we can't diverge.
2866 self.diverges.set(cond_diverges);
2869 let result_ty = coerce.complete(self);
2870 if cond_ty.references_error() {
2877 // Check field access expressions
2878 fn check_field(&self,
2879 expr: &'gcx hir::Expr,
2880 lvalue_pref: LvaluePreference,
2881 base: &'gcx hir::Expr,
2882 field: &Spanned<ast::Name>) -> Ty<'tcx> {
2883 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2884 let expr_t = self.structurally_resolved_type(expr.span,
2886 let mut private_candidate = None;
2887 let mut autoderef = self.autoderef(expr.span, expr_t);
2888 while let Some((base_t, _)) = autoderef.next() {
2890 ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
2891 debug!("struct named {:?}", base_t);
2892 let (ident, def_scope) =
2893 self.tcx.adjust(field.node, base_def.did, self.body_id);
2894 let fields = &base_def.struct_variant().fields;
2895 if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
2896 let field_ty = self.field_ty(expr.span, field, substs);
2897 if field.vis.is_accessible_from(def_scope, self.tcx) {
2898 let autoderefs = autoderef.adjust_steps(lvalue_pref);
2899 self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
2900 autoderef.finalize();
2902 self.tcx.check_stability(field.did, expr.id, expr.span);
2906 private_candidate = Some((base_def.did, field_ty));
2912 autoderef.unambiguous_final_ty();
2914 if let Some((did, field_ty)) = private_candidate {
2915 let struct_path = self.tcx().item_path_str(did);
2916 let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
2917 let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
2918 // Also check if an accessible method exists, which is often what is meant.
2919 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2920 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2925 } else if field.node == keywords::Invalid.name() {
2926 self.tcx().types.err
2927 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2928 self.type_error_struct(field.span, |actual| {
2929 format!("attempted to take value of method `{}` on type \
2930 `{}`", field.node, actual)
2932 .help("maybe a `()` to call it is missing? \
2933 If not, try an anonymous function")
2935 self.tcx().types.err
2937 let mut err = self.type_error_struct(field.span, |actual| {
2938 format!("no field `{}` on type `{}`",
2942 ty::TyAdt(def, _) if !def.is_enum() => {
2943 if let Some(suggested_field_name) =
2944 Self::suggest_field_name(def.struct_variant(), field, vec![]) {
2945 err.span_label(field.span,
2946 format!("did you mean `{}`?", suggested_field_name));
2948 err.span_label(field.span,
2952 ty::TyRawPtr(..) => {
2953 err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
2955 self.tcx.hir.node_to_pretty_string(base.id),
2961 self.tcx().types.err
2965 // Return an hint about the closest match in field names
2966 fn suggest_field_name(variant: &'tcx ty::VariantDef,
2967 field: &Spanned<ast::Name>,
2968 skip : Vec<InternedString>)
2970 let name = field.node.as_str();
2971 let names = variant.fields.iter().filter_map(|field| {
2972 // ignore already set fields and private fields from non-local crates
2973 if skip.iter().any(|x| *x == field.name.as_str()) ||
2974 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
2981 // only find fits with at least one matching letter
2982 find_best_match_for_name(names, &name, Some(name.len()))
2985 // Check tuple index expressions
2986 fn check_tup_field(&self,
2987 expr: &'gcx hir::Expr,
2988 lvalue_pref: LvaluePreference,
2989 base: &'gcx hir::Expr,
2990 idx: codemap::Spanned<usize>) -> Ty<'tcx> {
2991 let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2992 let expr_t = self.structurally_resolved_type(expr.span,
2994 let mut private_candidate = None;
2995 let mut tuple_like = false;
2996 let mut autoderef = self.autoderef(expr.span, expr_t);
2997 while let Some((base_t, _)) = autoderef.next() {
2998 let field = match base_t.sty {
2999 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
3000 tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
3001 if !tuple_like { continue }
3003 debug!("tuple struct named {:?}", base_t);
3004 let ident = ast::Ident {
3005 name: Symbol::intern(&idx.node.to_string()),
3006 ctxt: idx.span.ctxt.modern(),
3008 let (ident, def_scope) =
3009 self.tcx.adjust_ident(ident, base_def.did, self.body_id);
3010 let fields = &base_def.struct_variant().fields;
3011 if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
3012 let field_ty = self.field_ty(expr.span, field, substs);
3013 if field.vis.is_accessible_from(def_scope, self.tcx) {
3014 self.tcx.check_stability(field.did, expr.id, expr.span);
3017 private_candidate = Some((base_def.did, field_ty));
3024 ty::TyTuple(ref v, _) => {
3026 v.get(idx.node).cloned()
3031 if let Some(field_ty) = field {
3032 let autoderefs = autoderef.adjust_steps(lvalue_pref);
3033 self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
3034 autoderef.finalize();
3038 autoderef.unambiguous_final_ty();
3040 if let Some((did, field_ty)) = private_candidate {
3041 let struct_path = self.tcx().item_path_str(did);
3042 let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3043 self.tcx().sess.span_err(expr.span, &msg);
3047 self.type_error_message(
3051 format!("attempted out-of-bounds tuple index `{}` on \
3056 format!("attempted tuple index `{}` on type `{}`, but the \
3057 type was not a tuple or tuple struct",
3064 self.tcx().types.err
3067 fn report_unknown_field(&self,
3069 variant: &'tcx ty::VariantDef,
3071 skip_fields: &[hir::Field],
3073 let mut err = self.type_error_struct_with_diag(
3075 |actual| match ty.sty {
3076 ty::TyAdt(adt, ..) if adt.is_enum() => {
3077 struct_span_err!(self.tcx.sess, field.name.span, E0559,
3078 "{} `{}::{}` has no field named `{}`",
3079 kind_name, actual, variant.name, field.name.node)
3082 struct_span_err!(self.tcx.sess, field.name.span, E0560,
3083 "{} `{}` has no field named `{}`",
3084 kind_name, actual, field.name.node)
3088 // prevent all specified fields from being suggested
3089 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3090 if let Some(field_name) = Self::suggest_field_name(variant,
3092 skip_fields.collect()) {
3093 err.span_label(field.name.span,
3094 format!("field does not exist - did you mean `{}`?", field_name));
3097 ty::TyAdt(adt, ..) if adt.is_enum() => {
3098 err.span_label(field.name.span, format!("`{}::{}` does not have this field",
3102 err.span_label(field.name.span, format!("`{}` does not have this field", ty));
3109 fn check_expr_struct_fields(&self,
3111 expected: Expectation<'tcx>,
3112 expr_id: ast::NodeId,
3114 variant: &'tcx ty::VariantDef,
3115 ast_fields: &'gcx [hir::Field],
3116 check_completeness: bool) {
3120 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3121 .get(0).cloned().unwrap_or(adt_ty);
3123 let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
3124 (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
3125 (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
3127 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3130 let mut remaining_fields = FxHashMap();
3131 for field in &variant.fields {
3132 remaining_fields.insert(field.name.to_ident(), field);
3135 let mut seen_fields = FxHashMap();
3137 let mut error_happened = false;
3139 // Typecheck each field.
3140 for field in ast_fields {
3141 let final_field_type;
3142 let field_type_hint;
3144 let ident = tcx.adjust(field.name.node, variant.did, self.body_id).0;
3145 if let Some(v_field) = remaining_fields.remove(&ident) {
3146 final_field_type = self.field_ty(field.span, v_field, substs);
3147 field_type_hint = self.field_ty(field.span, v_field, hint_substs);
3149 seen_fields.insert(field.name.node, field.span);
3151 // we don't look at stability attributes on
3152 // struct-like enums (yet...), but it's definitely not
3153 // a bug to have construct one.
3154 if adt_kind != ty::AdtKind::Enum {
3155 tcx.check_stability(v_field.did, expr_id, field.span);
3158 error_happened = true;
3159 final_field_type = tcx.types.err;
3160 field_type_hint = tcx.types.err;
3161 if let Some(_) = variant.find_field_named(field.name.node) {
3162 let mut err = struct_span_err!(self.tcx.sess,
3165 "field `{}` specified more than once",
3168 err.span_label(field.name.span, "used more than once");
3170 if let Some(prev_span) = seen_fields.get(&field.name.node) {
3171 err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
3176 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3180 // Make sure to give a type to the field even if there's
3181 // an error, so we can continue typechecking
3182 let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
3183 self.demand_coerce(&field.expr, ty, final_field_type);
3186 // Make sure the programmer specified correct number of fields.
3187 if kind_name == "union" {
3188 if ast_fields.len() != 1 {
3189 tcx.sess.span_err(span, "union expressions should have exactly one field");
3191 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3192 let len = remaining_fields.len();
3194 let mut displayable_field_names = remaining_fields
3196 .map(|ident| ident.name.as_str())
3197 .collect::<Vec<_>>();
3199 displayable_field_names.sort();
3201 let truncated_fields_error = if len <= 3 {
3204 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3207 let remaining_fields_names = displayable_field_names.iter().take(3)
3208 .map(|n| format!("`{}`", n))
3209 .collect::<Vec<_>>()
3212 struct_span_err!(tcx.sess, span, E0063,
3213 "missing field{} {}{} in initializer of `{}`",
3214 if remaining_fields.len() == 1 {""} else {"s"},
3215 remaining_fields_names,
3216 truncated_fields_error,
3218 .span_label(span, format!("missing {}{}",
3219 remaining_fields_names,
3220 truncated_fields_error))
3225 fn check_struct_fields_on_error(&self,
3226 fields: &'gcx [hir::Field],
3227 base_expr: &'gcx Option<P<hir::Expr>>) {
3228 for field in fields {
3229 self.check_expr(&field.expr);
3233 self.check_expr(&base);
3239 pub fn check_struct_path(&self,
3241 node_id: ast::NodeId)
3242 -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
3243 let path_span = match *qpath {
3244 hir::QPath::Resolved(_, ref path) => path.span,
3245 hir::QPath::TypeRelative(ref qself, _) => qself.span
3247 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3248 let variant = match def {
3250 self.set_tainted_by_errors();
3253 Def::Variant(..) => {
3255 ty::TyAdt(adt, substs) => {
3256 Some((adt.variant_of_def(def), adt.did, substs))
3258 _ => bug!("unexpected type: {:?}", ty.sty)
3261 Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3262 Def::AssociatedTy(..) | Def::SelfTy(..) => {
3264 ty::TyAdt(adt, substs) if !adt.is_enum() => {
3265 Some((adt.struct_variant(), adt.did, substs))
3270 _ => bug!("unexpected definition: {:?}", def)
3273 if let Some((variant, did, substs)) = variant {
3274 // Check bounds on type arguments used in the path.
3275 let bounds = self.instantiate_bounds(path_span, did, substs);
3276 let cause = traits::ObligationCause::new(path_span, self.body_id,
3277 traits::ItemObligation(did));
3278 self.add_obligations_for_parameters(cause, &bounds);
3282 struct_span_err!(self.tcx.sess, path_span, E0071,
3283 "expected struct, variant or union type, found {}",
3284 ty.sort_string(self.tcx))
3285 .span_label(path_span, "not a struct")
3291 fn check_expr_struct(&self,
3293 expected: Expectation<'tcx>,
3295 fields: &'gcx [hir::Field],
3296 base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3298 // Find the relevant variant
3299 let (variant, struct_ty) =
3300 if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3303 self.check_struct_fields_on_error(fields, base_expr);
3304 return self.tcx.types.err;
3307 let path_span = match *qpath {
3308 hir::QPath::Resolved(_, ref path) => path.span,
3309 hir::QPath::TypeRelative(ref qself, _) => qself.span
3312 self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3313 base_expr.is_none());
3314 if let &Some(ref base_expr) = base_expr {
3315 self.check_expr_has_type(base_expr, struct_ty);
3316 match struct_ty.sty {
3317 ty::TyAdt(adt, substs) if adt.is_struct() => {
3318 self.tables.borrow_mut().fru_field_types.insert(
3320 adt.struct_variant().fields.iter().map(|f| {
3321 self.normalize_associated_types_in(
3322 expr.span, &f.ty(self.tcx, substs)
3328 span_err!(self.tcx.sess, base_expr.span, E0436,
3329 "functional record update syntax requires a struct");
3333 self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3339 /// If an expression has any sub-expressions that result in a type error,
3340 /// inspecting that expression's type with `ty.references_error()` will return
3341 /// true. Likewise, if an expression is known to diverge, inspecting its
3342 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3343 /// strict, _|_ can appear in the type of an expression that does not,
3344 /// itself, diverge: for example, fn() -> _|_.)
3345 /// Note that inspecting a type's structure *directly* may expose the fact
3346 /// that there are actually multiple representations for `TyError`, so avoid
3347 /// that when err needs to be handled differently.
3348 fn check_expr_with_expectation_and_lvalue_pref(&self,
3349 expr: &'gcx hir::Expr,
3350 expected: Expectation<'tcx>,
3351 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3352 debug!(">> typechecking: expr={:?} expected={:?}",
3355 // Warn for expressions after diverging siblings.
3356 self.warn_if_unreachable(expr.id, expr.span, "expression");
3358 // Hide the outer diverging and has_errors flags.
3359 let old_diverges = self.diverges.get();
3360 let old_has_errors = self.has_errors.get();
3361 self.diverges.set(Diverges::Maybe);
3362 self.has_errors.set(false);
3364 let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3366 // Warn for non-block expressions with diverging children.
3369 hir::ExprLoop(..) | hir::ExprWhile(..) |
3370 hir::ExprIf(..) | hir::ExprMatch(..) => {}
3372 _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3375 // Any expression that produces a value of type `!` must have diverged
3377 self.diverges.set(self.diverges.get() | Diverges::Always);
3380 // Record the type, which applies it effects.
3381 // We need to do this after the warning above, so that
3382 // we don't warn for the diverging expression itself.
3383 self.write_ty(expr.id, ty);
3385 // Combine the diverging and has_error flags.
3386 self.diverges.set(self.diverges.get() | old_diverges);
3387 self.has_errors.set(self.has_errors.get() | old_has_errors);
3389 debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3390 debug!("... {:?}, expected is {:?}", ty, expected);
3395 fn check_expr_kind(&self,
3396 expr: &'gcx hir::Expr,
3397 expected: Expectation<'tcx>,
3398 lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3402 hir::ExprBox(ref subexpr) => {
3403 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3405 ty::TyAdt(def, _) if def.is_box()
3406 => Expectation::rvalue_hint(self, ty.boxed_ty()),
3410 let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3411 tcx.mk_box(referent_ty)
3414 hir::ExprLit(ref lit) => {
3415 self.check_lit(&lit, expected)
3417 hir::ExprBinary(op, ref lhs, ref rhs) => {
3418 self.check_binop(expr, op, lhs, rhs)
3420 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3421 self.check_binop_assign(expr, op, lhs, rhs)
3423 hir::ExprUnary(unop, ref oprnd) => {
3424 let expected_inner = match unop {
3425 hir::UnNot | hir::UnNeg => {
3432 let lvalue_pref = match unop {
3433 hir::UnDeref => lvalue_pref,
3436 let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3440 if !oprnd_t.references_error() {
3443 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3445 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3447 } else if let Some(ok) = self.try_overloaded_deref(
3448 expr.span, oprnd_t, lvalue_pref) {
3449 let (autoref, method) = self.register_infer_ok_obligations(ok);
3450 self.apply_adjustment(oprnd.id, Adjustment {
3451 kind: Adjust::Deref(vec![]),
3454 target: method.sig.inputs()[0]
3456 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3457 self.write_method_call(expr.id, method);
3459 self.type_error_message(expr.span, |actual| {
3460 format!("type `{}` cannot be \
3461 dereferenced", actual)
3463 oprnd_t = tcx.types.err;
3467 oprnd_t = self.structurally_resolved_type(oprnd.span,
3469 let result = self.check_user_unop("!", "not",
3470 tcx.lang_items.not_trait(),
3471 expr, &oprnd, oprnd_t, unop);
3472 // If it's builtin, we can reuse the type, this helps inference.
3473 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3478 oprnd_t = self.structurally_resolved_type(oprnd.span,
3480 let result = self.check_user_unop("-", "neg",
3481 tcx.lang_items.neg_trait(),
3482 expr, &oprnd, oprnd_t, unop);
3483 // If it's builtin, we can reuse the type, this helps inference.
3484 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3492 hir::ExprAddrOf(mutbl, ref oprnd) => {
3493 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3495 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3496 if self.tcx.expr_is_lval(&oprnd) {
3497 // Lvalues may legitimately have unsized types.
3498 // For example, dereferences of a fat pointer and
3499 // the last field of a struct can be unsized.
3500 ExpectHasType(mt.ty)
3502 Expectation::rvalue_hint(self, mt.ty)
3508 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3509 let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3511 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3512 if tm.ty.references_error() {
3515 // Note: at this point, we cannot say what the best lifetime
3516 // is to use for resulting pointer. We want to use the
3517 // shortest lifetime possible so as to avoid spurious borrowck
3518 // errors. Moreover, the longest lifetime will depend on the
3519 // precise details of the value whose address is being taken
3520 // (and how long it is valid), which we don't know yet until type
3521 // inference is complete.
3523 // Therefore, here we simply generate a region variable. The
3524 // region inferencer will then select the ultimate value.
3525 // Finally, borrowck is charged with guaranteeing that the
3526 // value whose address was taken can actually be made to live
3527 // as long as it needs to live.
3528 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3529 tcx.mk_ref(region, tm)
3532 hir::ExprPath(ref qpath) => {
3533 let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3534 expr.id, expr.span);
3535 let ty = if def != Def::Err {
3536 self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3538 self.set_tainted_by_errors();
3542 // We always require that the type provided as the value for
3543 // a type parameter outlives the moment of instantiation.
3544 let substs = self.tables.borrow().node_substs(expr.id);
3545 self.add_wf_bounds(substs, expr);
3549 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3550 for output in outputs {
3551 self.check_expr(output);
3553 for input in inputs {
3554 self.check_expr(input);
3558 hir::ExprBreak(destination, ref expr_opt) => {
3559 if let Some(target_id) = destination.target_id.opt_id() {
3560 let (e_ty, e_diverges, cause);
3561 if let Some(ref e) = *expr_opt {
3562 // If this is a break with a value, we need to type-check
3563 // the expression. Get an expected type from the loop context.
3564 let opt_coerce_to = {
3565 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3566 enclosing_breakables.find_breakable(target_id)
3569 .map(|coerce| coerce.expected_ty())
3572 // If the loop context is not a `loop { }`, then break with
3573 // a value is illegal, and `opt_coerce_to` will be `None`.
3574 // Just set expectation to error in that case.
3575 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3577 // Recurse without `enclosing_breakables` borrowed.
3578 e_ty = self.check_expr_with_hint(e, coerce_to);
3579 e_diverges = self.diverges.get();
3580 cause = self.misc(e.span);
3582 // Otherwise, this is a break *without* a value. That's
3583 // always legal, and is equivalent to `break ()`.
3584 e_ty = tcx.mk_nil();
3585 e_diverges = Diverges::Maybe;
3586 cause = self.misc(expr.span);
3589 // Now that we have type-checked `expr_opt`, borrow
3590 // the `enclosing_loops` field and let's coerce the
3591 // type of `expr_opt` into what is expected.
3592 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3593 let ctxt = enclosing_breakables.find_breakable(target_id);
3594 if let Some(ref mut coerce) = ctxt.coerce {
3595 if let Some(ref e) = *expr_opt {
3596 coerce.coerce(self, &cause, e, e_ty, e_diverges);
3598 assert!(e_ty.is_nil());
3599 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
3602 // If `ctxt.coerce` is `None`, we can just ignore
3603 // the type of the expresison. This is because
3604 // either this was a break *without* a value, in
3605 // which case it is always a legal type (`()`), or
3606 // else an error would have been flagged by the
3607 // `loops` pass for using break with an expression
3608 // where you are not supposed to.
3609 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3612 ctxt.may_break = true;
3614 // Otherwise, we failed to find the enclosing loop;
3615 // this can only happen if the `break` was not
3616 // inside a loop at all, which is caught by the
3617 // loop-checking pass.
3618 assert!(self.tcx.sess.err_count() > 0);
3621 // the type of a `break` is always `!`, since it diverges
3624 hir::ExprAgain(_) => { tcx.types.never }
3625 hir::ExprRet(ref expr_opt) => {
3626 if self.ret_coercion.is_none() {
3627 struct_span_err!(self.tcx.sess, expr.span, E0572,
3628 "return statement outside of function body").emit();
3629 } else if let Some(ref e) = *expr_opt {
3630 self.check_return_expr(e);
3632 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3633 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3634 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
3638 hir::ExprAssign(ref lhs, ref rhs) => {
3639 let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3642 if !tcx.expr_is_lval(&lhs) {
3644 tcx.sess, expr.span, E0070,
3645 "invalid left-hand side expression")
3648 "left-hand of expression not valid")
3652 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3654 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3656 if lhs_ty.references_error() || rhs_ty.references_error() {
3662 hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3663 self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3664 expr.span, expected)
3666 hir::ExprWhile(ref cond, ref body, _) => {
3667 let ctxt = BreakableCtxt {
3668 // cannot use break with a value from a while loop
3673 self.with_breakable_ctxt(expr.id, ctxt, || {
3674 self.check_expr_has_type(&cond, tcx.types.bool);
3675 let cond_diverging = self.diverges.get();
3676 self.check_block_no_value(&body);
3678 // We may never reach the body so it diverging means nothing.
3679 self.diverges.set(cond_diverging);
3684 hir::ExprLoop(ref body, _, source) => {
3685 let coerce = match source {
3686 // you can only use break with a value from a normal `loop { }`
3687 hir::LoopSource::Loop => {
3688 let coerce_to = expected.coercion_target_type(self, body.span);
3689 Some(CoerceMany::new(coerce_to))
3692 hir::LoopSource::WhileLet |
3693 hir::LoopSource::ForLoop => {
3698 let ctxt = BreakableCtxt {
3700 may_break: false, // will get updated if/when we find a `break`
3703 let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3704 self.check_block_no_value(&body);
3708 // No way to know whether it's diverging because
3709 // of a `break` or an outer `break` or `return.
3710 self.diverges.set(Diverges::Maybe);
3713 // If we permit break with a value, then result type is
3714 // the LUB of the breaks (possibly ! if none); else, it
3715 // is nil. This makes sense because infinite loops
3716 // (which would have type !) are only possible iff we
3717 // permit break with a value [1].
3718 assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3719 ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3721 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3722 self.check_match(expr, &discrim, arms, expected, match_src)
3724 hir::ExprClosure(capture, ref decl, body_id, _) => {
3725 self.check_expr_closure(expr, capture, &decl, body_id, expected)
3727 hir::ExprBlock(ref body) => {
3728 self.check_block_with_expected(&body, expected)
3730 hir::ExprCall(ref callee, ref args) => {
3731 self.check_call(expr, &callee, args, expected)
3733 hir::ExprMethodCall(name, ref tps, ref args) => {
3734 self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
3736 hir::ExprCast(ref e, ref t) => {
3737 // Find the type of `e`. Supply hints based on the type we are casting to,
3739 let t_cast = self.to_ty(t);
3740 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3741 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3742 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3743 let diverges = self.diverges.get();
3745 // Eagerly check for some obvious errors.
3746 if t_expr.references_error() || t_cast.references_error() {
3749 // Defer other checks until we're done type checking.
3750 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3751 match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
3753 deferred_cast_checks.push(cast_check);
3756 Err(ErrorReported) => {
3762 hir::ExprType(ref e, ref t) => {
3763 let typ = self.to_ty(&t);
3764 self.check_expr_eq_type(&e, typ);
3767 hir::ExprArray(ref args) => {
3768 let uty = expected.to_option(self).and_then(|uty| {
3770 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3775 let element_ty = if !args.is_empty() {
3776 let coerce_to = uty.unwrap_or_else(
3777 || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3778 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
3779 assert_eq!(self.diverges.get(), Diverges::Maybe);
3781 let e_ty = self.check_expr_with_hint(e, coerce_to);
3782 let cause = self.misc(e.span);
3783 coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
3785 coerce.complete(self)
3787 self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3789 tcx.mk_array(element_ty, args.len())
3791 hir::ExprRepeat(ref element, count) => {
3792 let count = eval_length(self.tcx, count, "repeat count")
3795 let uty = match expected {
3796 ExpectHasType(uty) => {
3798 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3805 let (element_ty, t) = match uty {
3807 self.check_expr_coercable_to_type(&element, uty);
3811 let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3812 let element_ty = self.check_expr_has_type(&element, t);
3818 // For [foo, ..n] where n > 1, `foo` must have
3820 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3821 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3824 if element_ty.references_error() {
3827 tcx.mk_array(t, count)
3830 hir::ExprTup(ref elts) => {
3831 let flds = expected.only_has_type(self).and_then(|ty| {
3833 ty::TyTuple(ref flds, _) => Some(&flds[..]),
3838 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3839 let t = match flds {
3840 Some(ref fs) if i < fs.len() => {
3842 self.check_expr_coercable_to_type(&e, ety);
3846 self.check_expr_with_expectation(&e, NoExpectation)
3851 let tuple = tcx.mk_tup(elt_ts_iter, false);
3852 if tuple.references_error() {
3858 hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3859 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3861 hir::ExprField(ref base, ref field) => {
3862 self.check_field(expr, lvalue_pref, &base, field)
3864 hir::ExprTupField(ref base, idx) => {
3865 self.check_tup_field(expr, lvalue_pref, &base, idx)
3867 hir::ExprIndex(ref base, ref idx) => {
3868 let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3869 let idx_t = self.check_expr(&idx);
3871 if base_t.references_error() {
3873 } else if idx_t.references_error() {
3876 let base_t = self.structurally_resolved_type(expr.span, base_t);
3877 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3878 Some((index_ty, element_ty)) => {
3879 self.demand_coerce(idx, idx_t, index_ty);
3883 let mut err = self.type_error_struct(
3886 format!("cannot index a value of type `{}`",
3890 // Try to give some advice about indexing tuples.
3891 if let ty::TyTuple(..) = base_t.sty {
3892 let mut needs_note = true;
3893 // If the index is an integer, we can show the actual
3894 // fixed expression:
3895 if let hir::ExprLit(ref lit) = idx.node {
3896 if let ast::LitKind::Int(i,
3897 ast::LitIntType::Unsuffixed) = lit.node {
3898 let snip = tcx.sess.codemap().span_to_snippet(base.span);
3899 if let Ok(snip) = snip {
3900 err.span_suggestion(expr.span,
3901 "to access tuple elements, use",
3902 format!("{}.{}", snip, i));
3908 err.help("to access tuple elements, use tuple indexing \
3909 syntax (e.g. `tuple.0`)");
3921 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3922 // The newly resolved definition is written into `type_dependent_defs`.
3923 fn finish_resolving_struct_path(&self,
3926 node_id: ast::NodeId)
3930 hir::QPath::Resolved(ref maybe_qself, ref path) => {
3931 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
3932 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
3935 hir::QPath::TypeRelative(ref qself, ref segment) => {
3936 let ty = self.to_ty(qself);
3938 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
3943 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
3946 // Write back the new resolution.
3947 self.tables.borrow_mut().type_dependent_defs.insert(node_id, def);
3954 // Resolve associated value path into a base type and associated constant or method definition.
3955 // The newly resolved definition is written into `type_dependent_defs`.
3956 pub fn resolve_ty_and_def_ufcs<'b>(&self,
3957 qpath: &'b hir::QPath,
3958 node_id: ast::NodeId,
3960 -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3962 let (ty, item_segment) = match *qpath {
3963 hir::QPath::Resolved(ref opt_qself, ref path) => {
3965 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
3966 &path.segments[..]);
3968 hir::QPath::TypeRelative(ref qself, ref segment) => {
3969 (self.to_ty(qself), segment)
3972 let item_name = item_segment.name;
3973 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3976 let def = match error {
3977 method::MethodError::PrivateMatch(def) => def,
3980 if item_name != keywords::Invalid.name() {
3981 self.report_method_error(span, ty, item_name, None, error, None);
3987 // Write back the new resolution.
3988 self.tables.borrow_mut().type_dependent_defs.insert(node_id, def);
3989 (def, Some(ty), slice::ref_slice(&**item_segment))
3992 pub fn check_decl_initializer(&self,
3993 local: &'gcx hir::Local,
3994 init: &'gcx hir::Expr) -> Ty<'tcx>
3996 let ref_bindings = local.pat.contains_ref_binding();
3998 let local_ty = self.local_ty(init.span, local.id);
3999 if let Some(m) = ref_bindings {
4000 // Somewhat subtle: if we have a `ref` binding in the pattern,
4001 // we want to avoid introducing coercions for the RHS. This is
4002 // both because it helps preserve sanity and, in the case of
4003 // ref mut, for soundness (issue #23116). In particular, in
4004 // the latter case, we need to be clear that the type of the
4005 // referent for the reference that results is *equal to* the
4006 // type of the lvalue it is referencing, and not some
4007 // supertype thereof.
4008 let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
4009 self.demand_eqtype(init.span, init_ty, local_ty);
4012 self.check_expr_coercable_to_type(init, local_ty)
4016 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
4017 let t = self.local_ty(local.span, local.id);
4018 self.write_ty(local.id, t);
4020 if let Some(ref init) = local.init {
4021 let init_ty = self.check_decl_initializer(local, &init);
4022 if init_ty.references_error() {
4023 self.write_ty(local.id, init_ty);
4027 self.check_pat(&local.pat, t);
4028 let pat_ty = self.node_ty(local.pat.id);
4029 if pat_ty.references_error() {
4030 self.write_ty(local.id, pat_ty);
4034 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4035 // Don't do all the complex logic below for DeclItem.
4037 hir::StmtDecl(ref decl, id) => {
4039 hir::DeclLocal(_) => {}
4040 hir::DeclItem(_) => {
4046 hir::StmtExpr(..) | hir::StmtSemi(..) => {}
4049 self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
4051 // Hide the outer diverging and has_errors flags.
4052 let old_diverges = self.diverges.get();
4053 let old_has_errors = self.has_errors.get();
4054 self.diverges.set(Diverges::Maybe);
4055 self.has_errors.set(false);
4057 let (node_id, _span) = match stmt.node {
4058 hir::StmtDecl(ref decl, id) => {
4059 let span = match decl.node {
4060 hir::DeclLocal(ref l) => {
4061 self.check_decl_local(&l);
4064 hir::DeclItem(_) => {/* ignore for now */
4070 hir::StmtExpr(ref expr, id) => {
4071 // Check with expected type of ()
4072 self.check_expr_has_type(&expr, self.tcx.mk_nil());
4075 hir::StmtSemi(ref expr, id) => {
4076 self.check_expr(&expr);
4081 if self.has_errors.get() {
4082 self.write_error(node_id);
4084 self.write_nil(node_id);
4087 // Combine the diverging and has_error flags.
4088 self.diverges.set(self.diverges.get() | old_diverges);
4089 self.has_errors.set(self.has_errors.get() | old_has_errors);
4092 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
4093 let unit = self.tcx.mk_nil();
4094 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4096 // if the block produces a `!` value, that can always be
4097 // (effectively) coerced to unit.
4099 self.demand_suptype(blk.span, unit, ty);
4103 fn check_block_with_expected(&self,
4104 blk: &'gcx hir::Block,
4105 expected: Expectation<'tcx>) -> Ty<'tcx> {
4107 let mut fcx_ps = self.ps.borrow_mut();
4108 let unsafety_state = fcx_ps.recurse(blk);
4109 replace(&mut *fcx_ps, unsafety_state)
4112 // In some cases, blocks have just one exit, but other blocks
4113 // can be targeted by multiple breaks. This cannot happen in
4114 // normal Rust syntax today, but it can happen when we desugar
4115 // a `do catch { ... }` expression.
4119 // 'a: { if true { break 'a Err(()); } Ok(()) }
4121 // Here we would wind up with two coercions, one from
4122 // `Err(())` and the other from the tail expression
4123 // `Ok(())`. If the tail expression is omitted, that's a
4124 // "forced unit" -- unless the block diverges, in which
4125 // case we can ignore the tail expression (e.g., `'a: {
4126 // break 'a 22; }` would not force the type of the block
4128 let tail_expr = blk.expr.as_ref();
4129 let coerce_to_ty = expected.coercion_target_type(self, blk.span);
4130 let coerce = if blk.targeted_by_break {
4131 CoerceMany::new(coerce_to_ty)
4133 let tail_expr: &[P<hir::Expr>] = match tail_expr {
4134 Some(e) => ref_slice(e),
4137 CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
4140 let ctxt = BreakableCtxt {
4141 coerce: Some(coerce),
4145 let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
4146 for s in &blk.stmts {
4150 // check the tail expression **without** holding the
4151 // `enclosing_breakables` lock below.
4152 let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
4154 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4155 let mut ctxt = enclosing_breakables.find_breakable(blk.id);
4156 let mut coerce = ctxt.coerce.as_mut().unwrap();
4157 if let Some(tail_expr_ty) = tail_expr_ty {
4158 let tail_expr = tail_expr.unwrap();
4160 &self.misc(tail_expr.span),
4163 self.diverges.get());
4165 // Subtle: if there is no explicit tail expression,
4166 // that is typically equivalent to a tail expression
4167 // of `()` -- except if the block diverges. In that
4168 // case, there is no value supplied from the tail
4169 // expression (assuming there are no other breaks,
4170 // this implies that the type of the block will be
4173 // #41425 -- label the implicit `()` as being the
4174 // "found type" here, rather than the "expected type".
4175 if !self.diverges.get().always() {
4176 coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
4177 if let Some(expected_ty) = expected.only_has_type(self) {
4178 self.consider_hint_about_removing_semicolon(blk,
4187 let mut ty = ctxt.coerce.unwrap().complete(self);
4189 if self.has_errors.get() || ty.references_error() {
4190 ty = self.tcx.types.err
4193 self.write_ty(blk.id, ty);
4195 *self.ps.borrow_mut() = prev;
4199 /// A common error is to add an extra semicolon:
4202 /// fn foo() -> usize {
4207 /// This routine checks if the final statement in a block is an
4208 /// expression with an explicit semicolon whose type is compatible
4209 /// with `expected_ty`. If so, it suggests removing the semicolon.
4210 fn consider_hint_about_removing_semicolon(&self,
4211 blk: &'gcx hir::Block,
4212 expected_ty: Ty<'tcx>,
4213 err: &mut DiagnosticBuilder) {
4214 // Be helpful when the user wrote `{... expr;}` and
4215 // taking the `;` off is enough to fix the error.
4216 let last_stmt = match blk.stmts.last() {
4220 let last_expr = match last_stmt.node {
4221 hir::StmtSemi(ref e, _) => e,
4224 let last_expr_ty = self.expr_ty(last_expr);
4225 if self.can_sub_types(last_expr_ty, expected_ty).is_err() {
4228 let original_span = original_sp(last_stmt.span, blk.span);
4229 let span_semi = Span {
4230 lo: original_span.hi - BytePos(1),
4231 hi: original_span.hi,
4232 ctxt: original_span.ctxt,
4234 err.span_help(span_semi, "consider removing this semicolon:");
4237 // Instantiates the given path, which must refer to an item with the given
4238 // number of type parameters and type.
4239 pub fn instantiate_value_path(&self,
4240 segments: &[hir::PathSegment],
4241 opt_self_ty: Option<Ty<'tcx>>,
4244 node_id: ast::NodeId)
4246 debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4251 // We need to extract the type parameters supplied by the user in
4252 // the path `path`. Due to the current setup, this is a bit of a
4253 // tricky-process; the problem is that resolve only tells us the
4254 // end-point of the path resolution, and not the intermediate steps.
4255 // Luckily, we can (at least for now) deduce the intermediate steps
4256 // just from the end-point.
4258 // There are basically four cases to consider:
4260 // 1. Reference to a constructor of enum variant or struct:
4262 // struct Foo<T>(...)
4263 // enum E<T> { Foo(...) }
4265 // In these cases, the parameters are declared in the type
4268 // 2. Reference to a fn item or a free constant:
4272 // In this case, the path will again always have the form
4273 // `a::b::foo::<T>` where only the final segment should have
4274 // type parameters. However, in this case, those parameters are
4275 // declared on a value, and hence are in the `FnSpace`.
4277 // 3. Reference to a method or an associated constant:
4279 // impl<A> SomeStruct<A> {
4283 // Here we can have a path like
4284 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4285 // may appear in two places. The penultimate segment,
4286 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4287 // final segment, `foo::<B>` contains parameters in fn space.
4289 // 4. Reference to a local variable
4291 // Local variables can't have any type parameters.
4293 // The first step then is to categorize the segments appropriately.
4295 assert!(!segments.is_empty());
4297 let mut ufcs_associated = None;
4298 let mut type_segment = None;
4299 let mut fn_segment = None;
4301 // Case 1. Reference to a struct/variant constructor.
4302 Def::StructCtor(def_id, ..) |
4303 Def::VariantCtor(def_id, ..) => {
4304 // Everything but the final segment should have no
4305 // parameters at all.
4306 let mut generics = self.tcx.generics_of(def_id);
4307 if let Some(def_id) = generics.parent {
4308 // Variant and struct constructors use the
4309 // generics of their parent type definition.
4310 generics = self.tcx.generics_of(def_id);
4312 type_segment = Some((segments.last().unwrap(), generics));
4315 // Case 2. Reference to a top-level value.
4317 Def::Const(def_id) |
4318 Def::Static(def_id, _) => {
4319 fn_segment = Some((segments.last().unwrap(),
4320 self.tcx.generics_of(def_id)));
4323 // Case 3. Reference to a method or associated const.
4324 Def::Method(def_id) |
4325 Def::AssociatedConst(def_id) => {
4326 let container = self.tcx.associated_item(def_id).container;
4328 ty::TraitContainer(trait_did) => {
4329 callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4331 ty::ImplContainer(_) => {}
4334 let generics = self.tcx.generics_of(def_id);
4335 if segments.len() >= 2 {
4336 let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
4337 type_segment = Some((&segments[segments.len() - 2], parent_generics));
4339 // `<T>::assoc` will end up here, and so can `T::assoc`.
4340 let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4341 ufcs_associated = Some((container, self_ty));
4343 fn_segment = Some((segments.last().unwrap(), generics));
4346 // Case 4. Local variable, no generics.
4347 Def::Local(..) | Def::Upvar(..) => {}
4349 _ => bug!("unexpected definition: {:?}", def),
4352 debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4354 // Now that we have categorized what space the parameters for each
4355 // segment belong to, let's sort out the parameters that the user
4356 // provided (if any) into their appropriate spaces. We'll also report
4357 // errors if type parameters are provided in an inappropriate place.
4358 let poly_segments = type_segment.is_some() as usize +
4359 fn_segment.is_some() as usize;
4360 AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4363 Def::Local(def_id) | Def::Upvar(def_id, ..) => {
4364 let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
4365 let ty = self.local_ty(span, nid);
4366 let ty = self.normalize_associated_types_in(span, &ty);
4367 self.write_ty(node_id, ty);
4373 // Now we have to compare the types that the user *actually*
4374 // provided against the types that were *expected*. If the user
4375 // did not provide any types, then we want to substitute inference
4376 // variables. If the user provided some types, we may still need
4377 // to add defaults. If the user provided *too many* types, that's
4379 self.check_path_parameter_count(span, &mut type_segment);
4380 self.check_path_parameter_count(span, &mut fn_segment);
4382 let (fn_start, has_self) = match (type_segment, fn_segment) {
4383 (_, Some((_, generics))) => {
4384 (generics.parent_count(), generics.has_self)
4386 (Some((_, generics)), None) => {
4387 (generics.own_count(), generics.has_self)
4389 (None, None) => (0, false)
4391 let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4392 let mut i = def.index as usize;
4394 let segment = if i < fn_start {
4395 i -= has_self as usize;
4401 let lifetimes = match segment.map(|(s, _)| &s.parameters) {
4402 Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
4403 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4407 if let Some(lifetime) = lifetimes.get(i) {
4408 AstConv::ast_region_to_region(self, lifetime, Some(def))
4410 self.re_infer(span, Some(def)).unwrap()
4413 let mut i = def.index as usize;
4415 let segment = if i < fn_start {
4416 // Handle Self first, so we can adjust the index to match the AST.
4417 if has_self && i == 0 {
4418 return opt_self_ty.unwrap_or_else(|| {
4419 self.type_var_for_def(span, def, substs)
4422 i -= has_self as usize;
4428 let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
4429 Some(&hir::AngleBracketedParameters(ref data)) => {
4430 (&data.types[..], data.infer_types)
4432 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4433 None => (&[][..], true)
4436 // Skip over the lifetimes in the same segment.
4437 if let Some((_, generics)) = segment {
4438 i -= generics.regions.len();
4441 if let Some(ast_ty) = types.get(i) {
4442 // A provided type parameter.
4444 } else if !infer_types && def.has_default {
4445 // No type parameter provided, but a default exists.
4446 let default = self.tcx.type_of(def.def_id);
4449 default.subst_spanned(self.tcx, substs, Some(span))
4452 // No type parameters were provided, we can infer all.
4453 // This can also be reached in some error cases:
4454 // We prefer to use inference variables instead of
4455 // TyError to let type inference recover somewhat.
4456 self.type_var_for_def(span, def, substs)
4460 // The things we are substituting into the type should not contain
4461 // escaping late-bound regions, and nor should the base type scheme.
4462 let ty = self.tcx.type_of(def.def_id());
4463 assert!(!substs.has_escaping_regions());
4464 assert!(!ty.has_escaping_regions());
4466 // Add all the obligations that are required, substituting and
4467 // normalized appropriately.
4468 let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4469 self.add_obligations_for_parameters(
4470 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4473 // Substitute the values for the type parameters into the type of
4474 // the referenced item.
4475 let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4477 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4478 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4479 // is inherent, there is no `Self` parameter, instead, the impl needs
4480 // type parameters, which we can infer by unifying the provided `Self`
4481 // with the substituted impl type.
4482 let ty = self.tcx.type_of(impl_def_id);
4484 let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4485 match self.sub_types(false, &self.misc(span), self_ty, impl_ty) {
4486 Ok(ok) => self.register_infer_ok_obligations(ok),
4489 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4496 debug!("instantiate_value_path: type of {:?} is {:?}",
4499 self.write_substs(node_id, substs);
4503 /// Report errors if the provided parameters are too few or too many.
4504 fn check_path_parameter_count(&self,
4506 segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
4507 let (lifetimes, types, infer_types, bindings) = {
4508 match segment.map(|(s, _)| &s.parameters) {
4509 Some(&hir::AngleBracketedParameters(ref data)) => {
4510 (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
4512 Some(&hir::ParenthesizedParameters(_)) => {
4513 AstConv::prohibit_parenthesized_params(self, &segment.as_ref().unwrap().0,
4515 (&[][..], &[][..], true, &[][..])
4517 None => (&[][..], &[][..], true, &[][..])
4521 let count_lifetime_params = |n| {
4522 format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4524 let count_type_params = |n| {
4525 format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4528 // Check provided lifetime parameters.
4529 let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4530 if lifetimes.len() > lifetime_defs.len() {
4531 let expected_text = count_lifetime_params(lifetime_defs.len());
4532 let actual_text = count_lifetime_params(lifetimes.len());
4533 struct_span_err!(self.tcx.sess, span, E0088,
4534 "too many lifetime parameters provided: \
4535 expected at most {}, found {}",
4536 expected_text, actual_text)
4537 .span_label(span, format!("expected {}", expected_text))
4539 } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
4540 let expected_text = count_lifetime_params(lifetime_defs.len());
4541 let actual_text = count_lifetime_params(lifetimes.len());
4542 struct_span_err!(self.tcx.sess, span, E0090,
4543 "too few lifetime parameters provided: \
4544 expected {}, found {}",
4545 expected_text, actual_text)
4546 .span_label(span, format!("expected {}", expected_text))
4550 // The case where there is not enough lifetime parameters is not checked,
4551 // because this is not possible - a function never takes lifetime parameters.
4552 // See discussion for Pull Request 36208.
4554 // Check provided type parameters.
4555 let type_defs = segment.map_or(&[][..], |(_, generics)| {
4556 if generics.parent.is_none() {
4557 &generics.types[generics.has_self as usize..]
4562 let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4563 if types.len() > type_defs.len() {
4564 let span = types[type_defs.len()].span;
4565 let expected_text = count_type_params(type_defs.len());
4566 let actual_text = count_type_params(types.len());
4567 struct_span_err!(self.tcx.sess, span, E0087,
4568 "too many type parameters provided: \
4569 expected at most {}, found {}",
4570 expected_text, actual_text)
4571 .span_label(span, format!("expected {}", expected_text))
4574 // To prevent derived errors to accumulate due to extra
4575 // type parameters, we force instantiate_value_path to
4576 // use inference variables instead of the provided types.
4578 } else if !infer_types && types.len() < required_len {
4579 let expected_text = count_type_params(required_len);
4580 let actual_text = count_type_params(types.len());
4581 struct_span_err!(self.tcx.sess, span, E0089,
4582 "too few type parameters provided: \
4583 expected {}, found {}",
4584 expected_text, actual_text)
4585 .span_label(span, format!("expected {}", expected_text))
4589 if !bindings.is_empty() {
4590 span_err!(self.tcx.sess, bindings[0].span, E0182,
4591 "unexpected binding of associated item in expression path \
4592 (only allowed in type paths)");
4596 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4598 where F: Fn() -> Ty<'tcx>
4600 let mut ty = self.resolve_type_vars_with_obligations(ty);
4603 let alternative = f();
4606 if alternative.is_ty_var() || alternative.references_error() {
4607 if !self.is_tainted_by_errors() {
4608 self.type_error_message(sp, |_actual| {
4609 "the type of this value must be known in this context".to_string()
4612 self.demand_suptype(sp, self.tcx.types.err, ty);
4613 ty = self.tcx.types.err;
4615 self.demand_suptype(sp, alternative, ty);
4623 // Resolves `typ` by a single level if `typ` is a type variable. If no
4624 // resolution is possible, then an error is reported.
4625 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4626 self.structurally_resolve_type_or_else(sp, ty, || {
4631 fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4632 ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4633 -> (BreakableCtxt<'gcx, 'tcx>, R) {
4636 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4637 index = enclosing_breakables.stack.len();
4638 enclosing_breakables.by_id.insert(id, index);
4639 enclosing_breakables.stack.push(ctxt);
4643 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4644 debug_assert!(enclosing_breakables.stack.len() == index + 1);
4645 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4646 enclosing_breakables.stack.pop().expect("missing breakable context")
4652 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4653 generics: &hir::Generics,
4655 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4656 generics.ty_params.len(), ty);
4658 // make a vector of booleans initially false, set to true when used
4659 if generics.ty_params.is_empty() { return; }
4660 let mut tps_used = vec![false; generics.ty_params.len()];
4662 for leaf_ty in ty.walk() {
4663 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4664 debug!("Found use of ty param num {}", idx);
4665 tps_used[idx as usize - generics.lifetimes.len()] = true;
4669 for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4671 struct_span_err!(tcx.sess, param.span, E0091,
4672 "type parameter `{}` is unused",
4674 .span_label(param.span, "unused type parameter")