]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/expr.rs
typeck/expr.rs: move check_method_call here.
[rust.git] / src / librustc_typeck / check / expr.rs
1 //! Type checking expressions.
2 //!
3 //! See `mod.rs` for more context on type checking in general.
4
5 use crate::check::BreakableCtxt;
6 use crate::check::cast;
7 use crate::check::coercion::CoerceMany;
8 use crate::check::Diverges;
9 use crate::check::FnCtxt;
10 use crate::check::Expectation::{self, NoExpectation, ExpectHasType, ExpectCastableToType};
11 use crate::check::fatally_break_rust;
12 use crate::check::report_unexpected_variant_res;
13 use crate::check::Needs;
14 use crate::check::TupleArgumentsFlag::DontTupleArguments;
15 use crate::check::method::SelfSource;
16 use crate::middle::lang_items;
17 use crate::util::common::ErrorReported;
18
19 use errors::Applicability;
20 use syntax::ast;
21 use syntax::ptr::P;
22 use syntax::symbol::{kw, sym};
23 use syntax::source_map::Span;
24 use rustc::hir;
25 use rustc::hir::{ExprKind, QPath};
26 use rustc::hir::def::{CtorKind, Res, DefKind};
27 use rustc::infer;
28 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
29 use rustc::mir::interpret::GlobalId;
30 use rustc::ty;
31 use rustc::ty::adjustment::{
32     Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
33 };
34 use rustc::ty::Ty;
35 use rustc::ty::TypeFoldable;
36 use rustc::ty::subst::InternalSubsts;
37 use rustc::traits::{self, ObligationCauseCode};
38
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40     fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
41         let ty = self.check_expr_with_hint(expr, expected);
42         self.demand_eqtype(expr.span, expected, ty);
43     }
44
45     pub fn check_expr_has_type_or_error(
46         &self,
47         expr: &'tcx hir::Expr,
48         expected: Ty<'tcx>,
49     ) -> Ty<'tcx> {
50         self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected))
51     }
52
53     fn check_expr_meets_expectation_or_error(
54         &self,
55         expr: &'tcx hir::Expr,
56         expected: Expectation<'tcx>,
57     ) -> Ty<'tcx> {
58         let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
59         let mut ty = self.check_expr_with_expectation(expr, expected);
60
61         // While we don't allow *arbitrary* coercions here, we *do* allow
62         // coercions from ! to `expected`.
63         if ty.is_never() {
64             assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
65                     "expression with never type wound up being adjusted");
66             let adj_ty = self.next_diverging_ty_var(
67                 TypeVariableOrigin {
68                     kind: TypeVariableOriginKind::AdjustmentType,
69                     span: expr.span,
70                 },
71             );
72             self.apply_adjustments(expr, vec![Adjustment {
73                 kind: Adjust::NeverToAny,
74                 target: adj_ty
75             }]);
76             ty = adj_ty;
77         }
78
79         if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
80             let expr = match &expr.node {
81                 ExprKind::DropTemps(expr) => expr,
82                 _ => expr,
83             };
84             // Error possibly reported in `check_assign` so avoid emitting error again.
85             err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
86         }
87         ty
88     }
89
90     pub(super) fn check_expr_coercable_to_type(
91         &self,
92         expr: &'tcx hir::Expr,
93         expected: Ty<'tcx>
94     ) -> Ty<'tcx> {
95         let ty = self.check_expr_with_hint(expr, expected);
96         // checks don't need two phase
97         self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
98     }
99
100     pub(super) fn check_expr_with_hint(
101         &self,
102         expr: &'tcx hir::Expr,
103         expected: Ty<'tcx>
104     ) -> Ty<'tcx> {
105         self.check_expr_with_expectation(expr, ExpectHasType(expected))
106     }
107
108     pub(super) fn check_expr_with_expectation(
109         &self,
110         expr: &'tcx hir::Expr,
111         expected: Expectation<'tcx>,
112     ) -> Ty<'tcx> {
113         self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
114     }
115
116     pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
117         self.check_expr_with_expectation(expr, NoExpectation)
118     }
119
120     pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
121         self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
122     }
123
124     /// Invariant:
125     /// If an expression has any sub-expressions that result in a type error,
126     /// inspecting that expression's type with `ty.references_error()` will return
127     /// true. Likewise, if an expression is known to diverge, inspecting its
128     /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
129     /// strict, _|_ can appear in the type of an expression that does not,
130     /// itself, diverge: for example, fn() -> _|_.)
131     /// Note that inspecting a type's structure *directly* may expose the fact
132     /// that there are actually multiple representations for `Error`, so avoid
133     /// that when err needs to be handled differently.
134     fn check_expr_with_expectation_and_needs(
135         &self,
136         expr: &'tcx hir::Expr,
137         expected: Expectation<'tcx>,
138         needs: Needs,
139     ) -> Ty<'tcx> {
140         debug!(">> type-checking: expr={:?} expected={:?}",
141                expr, expected);
142
143         // Warn for expressions after diverging siblings.
144         self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
145
146         // Hide the outer diverging and has_errors flags.
147         let old_diverges = self.diverges.get();
148         let old_has_errors = self.has_errors.get();
149         self.diverges.set(Diverges::Maybe);
150         self.has_errors.set(false);
151
152         let ty = self.check_expr_kind(expr, expected, needs);
153
154         // Warn for non-block expressions with diverging children.
155         match expr.node {
156             ExprKind::Block(..) |
157             ExprKind::Loop(..) | ExprKind::While(..) |
158             ExprKind::Match(..) => {}
159
160             _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression")
161         }
162
163         // Any expression that produces a value of type `!` must have diverged
164         if ty.is_never() {
165             self.diverges.set(self.diverges.get() | Diverges::Always);
166         }
167
168         // Record the type, which applies it effects.
169         // We need to do this after the warning above, so that
170         // we don't warn for the diverging expression itself.
171         self.write_ty(expr.hir_id, ty);
172
173         // Combine the diverging and has_error flags.
174         self.diverges.set(self.diverges.get() | old_diverges);
175         self.has_errors.set(self.has_errors.get() | old_has_errors);
176
177         debug!("type of {} is...", self.tcx.hir().hir_to_string(expr.hir_id));
178         debug!("... {:?}, expected is {:?}", ty, expected);
179
180         ty
181     }
182
183     fn check_expr_kind(
184         &self,
185         expr: &'tcx hir::Expr,
186         expected: Expectation<'tcx>,
187         needs: Needs,
188     ) -> Ty<'tcx> {
189         debug!(
190             "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
191             expr,
192             expected,
193             needs,
194         );
195
196         let tcx = self.tcx;
197         match expr.node {
198             ExprKind::Box(ref subexpr) => {
199                 self.check_expr_box(subexpr, expected)
200             }
201             ExprKind::Lit(ref lit) => {
202                 self.check_lit(&lit, expected)
203             }
204             ExprKind::Binary(op, ref lhs, ref rhs) => {
205                 self.check_binop(expr, op, lhs, rhs)
206             }
207             ExprKind::AssignOp(op, ref lhs, ref rhs) => {
208                 self.check_binop_assign(expr, op, lhs, rhs)
209             }
210             ExprKind::Unary(unop, ref oprnd) => {
211                 self.check_expr_unary(unop, oprnd, expected, needs, expr)
212             }
213             ExprKind::AddrOf(mutbl, ref oprnd) => {
214                 self.check_expr_addr_of(mutbl, oprnd, expected, expr)
215             }
216             ExprKind::Path(ref qpath) => {
217                 self.check_expr_path(qpath, expr)
218             }
219             ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
220                 for expr in outputs.iter().chain(inputs.iter()) {
221                     self.check_expr(expr);
222                 }
223                 tcx.mk_unit()
224             }
225             ExprKind::Break(destination, ref expr_opt) => {
226                 self.check_expr_break(destination, expr_opt.deref(), expr)
227             }
228             ExprKind::Continue(destination) => {
229                 if destination.target_id.is_ok() {
230                     tcx.types.never
231                 } else {
232                     // There was an error; make type-check fail.
233                     tcx.types.err
234                 }
235             }
236             ExprKind::Ret(ref expr_opt) => {
237                 self.check_expr_return(expr_opt.deref(), expr)
238             }
239             ExprKind::Assign(ref lhs, ref rhs) => {
240                 self.check_expr_assign(expr, expected, lhs, rhs)
241             }
242             ExprKind::While(ref cond, ref body, _) => {
243                 self.check_expr_while(cond, body, expr)
244             }
245             ExprKind::Loop(ref body, _, source) => {
246                 self.check_expr_loop(body, source, expected, expr)
247             }
248             ExprKind::Match(ref discrim, ref arms, match_src) => {
249                 self.check_match(expr, &discrim, arms, expected, match_src)
250             }
251             ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
252                 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
253             }
254             ExprKind::Block(ref body, _) => {
255                 self.check_block_with_expected(&body, expected)
256             }
257             ExprKind::Call(ref callee, ref args) => {
258                 self.check_call(expr, &callee, args, expected)
259             }
260             ExprKind::MethodCall(ref segment, span, ref args) => {
261                 self.check_method_call(expr, segment, span, args, expected, needs)
262             }
263             ExprKind::Cast(ref e, ref t) => {
264                 self.check_expr_cast(e, t, expr)
265             }
266             ExprKind::Type(ref e, ref t) => {
267                 let ty = self.to_ty_saving_user_provided_ty(&t);
268                 self.check_expr_eq_type(&e, ty);
269                 ty
270             }
271             ExprKind::DropTemps(ref e) => {
272                 self.check_expr_with_expectation(e, expected)
273             }
274             ExprKind::Array(ref args) => {
275                 self.check_expr_array(args, expected, expr)
276             }
277             ExprKind::Repeat(ref element, ref count) => {
278                 self.check_expr_repeat(element, count, expected, expr)
279             }
280             ExprKind::Tup(ref elts) => {
281                 self.check_expr_tuple(elts, expected, expr)
282             }
283             ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
284                 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
285             }
286             ExprKind::Field(ref base, field) => {
287                 self.check_field(expr, needs, &base, field)
288             }
289             ExprKind::Index(ref base, ref idx) => {
290                 self.check_expr_index(base, idx, needs, expr)
291             }
292             ExprKind::Yield(ref value) => {
293                 self.check_expr_yield(value, expr)
294             }
295             hir::ExprKind::Err => {
296                 tcx.types.err
297             }
298         }
299     }
300
301     fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
302         let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
303             match ty.sty {
304                 ty::Adt(def, _) if def.is_box()
305                     => Expectation::rvalue_hint(self, ty.boxed_ty()),
306                 _ => NoExpectation
307             }
308         });
309         let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
310         self.tcx.mk_box(referent_ty)
311     }
312
313     fn check_expr_unary(
314         &self,
315         unop: hir::UnOp,
316         oprnd: &'tcx hir::Expr,
317         expected: Expectation<'tcx>,
318         needs: Needs,
319         expr: &'tcx hir::Expr,
320     ) -> Ty<'tcx> {
321         let tcx = self.tcx;
322         let expected_inner = match unop {
323             hir::UnNot | hir::UnNeg => expected,
324             hir::UnDeref => NoExpectation,
325         };
326         let needs = match unop {
327             hir::UnDeref => needs,
328             _ => Needs::None
329         };
330         let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
331
332         if !oprnd_t.references_error() {
333             oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
334             match unop {
335                 hir::UnDeref => {
336                     if let Some(mt) = oprnd_t.builtin_deref(true) {
337                         oprnd_t = mt.ty;
338                     } else if let Some(ok) = self.try_overloaded_deref(
339                             expr.span, oprnd_t, needs) {
340                         let method = self.register_infer_ok_obligations(ok);
341                         if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].sty {
342                             let mutbl = match mutbl {
343                                 hir::MutImmutable => AutoBorrowMutability::Immutable,
344                                 hir::MutMutable => AutoBorrowMutability::Mutable {
345                                     // (It shouldn't actually matter for unary ops whether
346                                     // we enable two-phase borrows or not, since a unary
347                                     // op has no additional operands.)
348                                     allow_two_phase_borrow: AllowTwoPhase::No,
349                                 }
350                             };
351                             self.apply_adjustments(oprnd, vec![Adjustment {
352                                 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
353                                 target: method.sig.inputs()[0]
354                             }]);
355                         }
356                         oprnd_t = self.make_overloaded_place_return_type(method).ty;
357                         self.write_method_call(expr.hir_id, method);
358                     } else {
359                         let mut err = type_error_struct!(
360                             tcx.sess,
361                             expr.span,
362                             oprnd_t,
363                             E0614,
364                             "type `{}` cannot be dereferenced",
365                             oprnd_t,
366                         );
367                         let sp = tcx.sess.source_map().start_point(expr.span);
368                         if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
369                             .borrow().get(&sp)
370                         {
371                             tcx.sess.parse_sess.expr_parentheses_needed(
372                                 &mut err,
373                                 *sp,
374                                 None,
375                             );
376                         }
377                         err.emit();
378                         oprnd_t = tcx.types.err;
379                     }
380                 }
381                 hir::UnNot => {
382                     let result = self.check_user_unop(expr, oprnd_t, unop);
383                     // If it's builtin, we can reuse the type, this helps inference.
384                     if !(oprnd_t.is_integral() || oprnd_t.sty == ty::Bool) {
385                         oprnd_t = result;
386                     }
387                 }
388                 hir::UnNeg => {
389                     let result = self.check_user_unop(expr, oprnd_t, unop);
390                     // If it's builtin, we can reuse the type, this helps inference.
391                     if !oprnd_t.is_numeric() {
392                         oprnd_t = result;
393                     }
394                 }
395             }
396         }
397         oprnd_t
398     }
399
400     fn check_expr_addr_of(
401         &self,
402         mutbl: hir::Mutability,
403         oprnd: &'tcx hir::Expr,
404         expected: Expectation<'tcx>,
405         expr: &'tcx hir::Expr,
406     ) -> Ty<'tcx> {
407         let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
408             match ty.sty {
409                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
410                     if oprnd.is_place_expr() {
411                         // Places may legitimately have unsized types.
412                         // For example, dereferences of a fat pointer and
413                         // the last field of a struct can be unsized.
414                         ExpectHasType(ty)
415                     } else {
416                         Expectation::rvalue_hint(self, ty)
417                     }
418                 }
419                 _ => NoExpectation
420             }
421         });
422         let needs = Needs::maybe_mut_place(mutbl);
423         let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
424
425         let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
426         if tm.ty.references_error() {
427             self.tcx.types.err
428         } else {
429             // Note: at this point, we cannot say what the best lifetime
430             // is to use for resulting pointer.  We want to use the
431             // shortest lifetime possible so as to avoid spurious borrowck
432             // errors.  Moreover, the longest lifetime will depend on the
433             // precise details of the value whose address is being taken
434             // (and how long it is valid), which we don't know yet until type
435             // inference is complete.
436             //
437             // Therefore, here we simply generate a region variable.  The
438             // region inferencer will then select the ultimate value.
439             // Finally, borrowck is charged with guaranteeing that the
440             // value whose address was taken can actually be made to live
441             // as long as it needs to live.
442             let region = self.next_region_var(infer::AddrOfRegion(expr.span));
443             self.tcx.mk_ref(region, tm)
444         }
445     }
446
447     fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
448         let tcx = self.tcx;
449         let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
450         let ty = match res {
451             Res::Err => {
452                 self.set_tainted_by_errors();
453                 tcx.types.err
454             }
455             Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
456                 report_unexpected_variant_res(tcx, res, expr.span, qpath);
457                 tcx.types.err
458             }
459             _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
460         };
461
462         if let ty::FnDef(..) = ty.sty {
463             let fn_sig = ty.fn_sig(tcx);
464             if !tcx.features().unsized_locals {
465                 // We want to remove some Sized bounds from std functions,
466                 // but don't want to expose the removal to stable Rust.
467                 // i.e., we don't want to allow
468                 //
469                 // ```rust
470                 // drop as fn(str);
471                 // ```
472                 //
473                 // to work in stable even if the Sized bound on `drop` is relaxed.
474                 for i in 0..fn_sig.inputs().skip_binder().len() {
475                     // We just want to check sizedness, so instead of introducing
476                     // placeholder lifetimes with probing, we just replace higher lifetimes
477                     // with fresh vars.
478                     let input = self.replace_bound_vars_with_fresh_vars(
479                         expr.span,
480                         infer::LateBoundRegionConversionTime::FnCall,
481                         &fn_sig.input(i)).0;
482                     self.require_type_is_sized_deferred(input, expr.span,
483                                                         traits::SizedArgumentType);
484                 }
485             }
486             // Here we want to prevent struct constructors from returning unsized types.
487             // There were two cases this happened: fn pointer coercion in stable
488             // and usual function call in presense of unsized_locals.
489             // Also, as we just want to check sizedness, instead of introducing
490             // placeholder lifetimes with probing, we just replace higher lifetimes
491             // with fresh vars.
492             let output = self.replace_bound_vars_with_fresh_vars(
493                 expr.span,
494                 infer::LateBoundRegionConversionTime::FnCall,
495                 &fn_sig.output()).0;
496             self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
497         }
498
499         // We always require that the type provided as the value for
500         // a type parameter outlives the moment of instantiation.
501         let substs = self.tables.borrow().node_substs(expr.hir_id);
502         self.add_wf_bounds(substs, expr);
503
504         ty
505     }
506
507     fn check_expr_break(
508         &self,
509         destination: hir::Destination,
510         expr_opt: Option<&'tcx hir::Expr>,
511         expr: &'tcx hir::Expr,
512     ) -> Ty<'tcx> {
513         let tcx = self.tcx;
514         if let Ok(target_id) = destination.target_id {
515             let (e_ty, cause);
516             if let Some(ref e) = expr_opt {
517                 // If this is a break with a value, we need to type-check
518                 // the expression. Get an expected type from the loop context.
519                 let opt_coerce_to = {
520                     let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
521                     enclosing_breakables.find_breakable(target_id)
522                                         .coerce
523                                         .as_ref()
524                                         .map(|coerce| coerce.expected_ty())
525                 };
526
527                 // If the loop context is not a `loop { }`, then break with
528                 // a value is illegal, and `opt_coerce_to` will be `None`.
529                 // Just set expectation to error in that case.
530                 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
531
532                 // Recurse without `enclosing_breakables` borrowed.
533                 e_ty = self.check_expr_with_hint(e, coerce_to);
534                 cause = self.misc(e.span);
535             } else {
536                 // Otherwise, this is a break *without* a value. That's
537                 // always legal, and is equivalent to `break ()`.
538                 e_ty = tcx.mk_unit();
539                 cause = self.misc(expr.span);
540             }
541
542             // Now that we have type-checked `expr_opt`, borrow
543             // the `enclosing_loops` field and let's coerce the
544             // type of `expr_opt` into what is expected.
545             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
546             let ctxt = enclosing_breakables.find_breakable(target_id);
547             if let Some(ref mut coerce) = ctxt.coerce {
548                 if let Some(ref e) = expr_opt {
549                     coerce.coerce(self, &cause, e, e_ty);
550                 } else {
551                     assert!(e_ty.is_unit());
552                     coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
553                 }
554             } else {
555                 // If `ctxt.coerce` is `None`, we can just ignore
556                 // the type of the expresison.  This is because
557                 // either this was a break *without* a value, in
558                 // which case it is always a legal type (`()`), or
559                 // else an error would have been flagged by the
560                 // `loops` pass for using break with an expression
561                 // where you are not supposed to.
562                 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
563             }
564
565             ctxt.may_break = true;
566
567             // the type of a `break` is always `!`, since it diverges
568             tcx.types.never
569         } else {
570             // Otherwise, we failed to find the enclosing loop;
571             // this can only happen if the `break` was not
572             // inside a loop at all, which is caught by the
573             // loop-checking pass.
574             if self.tcx.sess.err_count() == 0 {
575                 self.tcx.sess.delay_span_bug(expr.span,
576                     "break was outside loop, but no error was emitted");
577             }
578
579             // We still need to assign a type to the inner expression to
580             // prevent the ICE in #43162.
581             if let Some(ref e) = expr_opt {
582                 self.check_expr_with_hint(e, tcx.types.err);
583
584                 // ... except when we try to 'break rust;'.
585                 // ICE this expression in particular (see #43162).
586                 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node {
587                     if path.segments.len() == 1 &&
588                         path.segments[0].ident.name == sym::rust {
589                         fatally_break_rust(self.tcx.sess);
590                     }
591                 }
592             }
593             // There was an error; make type-check fail.
594             tcx.types.err
595         }
596     }
597
598     fn check_expr_return(
599         &self,
600         expr_opt: Option<&'tcx hir::Expr>,
601         expr: &'tcx hir::Expr
602     ) -> Ty<'tcx> {
603         if self.ret_coercion.is_none() {
604             struct_span_err!(self.tcx.sess, expr.span, E0572,
605                                 "return statement outside of function body").emit();
606         } else if let Some(ref e) = expr_opt {
607             if self.ret_coercion_span.borrow().is_none() {
608                 *self.ret_coercion_span.borrow_mut() = Some(e.span);
609             }
610             self.check_return_expr(e);
611         } else {
612             let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
613             if self.ret_coercion_span.borrow().is_none() {
614                 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
615             }
616             let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
617             if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
618                 coercion.coerce_forced_unit(
619                     self,
620                     &cause,
621                     &mut |db| {
622                         db.span_label(
623                             fn_decl.output.span(),
624                             format!(
625                                 "expected `{}` because of this return type",
626                                 fn_decl.output,
627                             ),
628                         );
629                     },
630                     true,
631                 );
632             } else {
633                 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
634             }
635         }
636         self.tcx.types.never
637     }
638
639     pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
640         let ret_coercion =
641             self.ret_coercion
642                 .as_ref()
643                 .unwrap_or_else(|| span_bug!(return_expr.span,
644                                              "check_return_expr called outside fn body"));
645
646         let ret_ty = ret_coercion.borrow().expected_ty();
647         let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
648         ret_coercion.borrow_mut()
649                     .coerce(self,
650                             &self.cause(return_expr.span,
651                                         ObligationCauseCode::ReturnType(return_expr.hir_id)),
652                             return_expr,
653                             return_expr_ty);
654     }
655
656     /// Type check assignment expression `expr` of form `lhs = rhs`.
657     /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
658     fn check_expr_assign(
659         &self,
660         expr: &'tcx hir::Expr,
661         expected: Expectation<'tcx>,
662         lhs: &'tcx hir::Expr,
663         rhs: &'tcx hir::Expr,
664     ) -> Ty<'tcx> {
665         let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
666         let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
667
668         let expected_ty = expected.coercion_target_type(self, expr.span);
669         if expected_ty == self.tcx.types.bool {
670             // The expected type is `bool` but this will result in `()` so we can reasonably
671             // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
672             // The likely cause of this is `if foo = bar { .. }`.
673             let actual_ty = self.tcx.mk_unit();
674             let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
675             let msg = "try comparing for equality";
676             let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
677             let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
678             if let (Ok(left), Ok(right)) = (left, right) {
679                 let help = format!("{} == {}", left, right);
680                 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
681             } else {
682                 err.help(msg);
683             }
684             err.emit();
685         } else if !lhs.is_place_expr() {
686             struct_span_err!(self.tcx.sess, expr.span, E0070,
687                                 "invalid left-hand side expression")
688                 .span_label(expr.span, "left-hand of expression not valid")
689                 .emit();
690         }
691
692         self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
693
694         if lhs_ty.references_error() || rhs_ty.references_error() {
695             self.tcx.types.err
696         } else {
697             self.tcx.mk_unit()
698         }
699     }
700
701     fn check_expr_while(
702         &self,
703         cond: &'tcx hir::Expr,
704         body: &'tcx hir::Block,
705         expr: &'tcx hir::Expr
706     ) -> Ty<'tcx> {
707         let ctxt = BreakableCtxt {
708             // Cannot use break with a value from a while loop.
709             coerce: None,
710             may_break: false, // Will get updated if/when we find a `break`.
711         };
712
713         let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
714             self.check_expr_has_type_or_error(&cond, self.tcx.types.bool);
715             let cond_diverging = self.diverges.get();
716             self.check_block_no_value(&body);
717
718             // We may never reach the body so it diverging means nothing.
719             self.diverges.set(cond_diverging);
720         });
721
722         if ctxt.may_break {
723             // No way to know whether it's diverging because
724             // of a `break` or an outer `break` or `return`.
725             self.diverges.set(Diverges::Maybe);
726         }
727
728         self.tcx.mk_unit()
729     }
730
731     fn check_expr_loop(
732         &self,
733         body: &'tcx hir::Block,
734         source: hir::LoopSource,
735         expected: Expectation<'tcx>,
736         expr: &'tcx hir::Expr,
737     ) -> Ty<'tcx> {
738         let coerce = match source {
739             // you can only use break with a value from a normal `loop { }`
740             hir::LoopSource::Loop => {
741                 let coerce_to = expected.coercion_target_type(self, body.span);
742                 Some(CoerceMany::new(coerce_to))
743             }
744
745             hir::LoopSource::WhileLet |
746             hir::LoopSource::ForLoop => {
747                 None
748             }
749         };
750
751         let ctxt = BreakableCtxt {
752             coerce,
753             may_break: false, // Will get updated if/when we find a `break`.
754         };
755
756         let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
757             self.check_block_no_value(&body);
758         });
759
760         if ctxt.may_break {
761             // No way to know whether it's diverging because
762             // of a `break` or an outer `break` or `return`.
763             self.diverges.set(Diverges::Maybe);
764         }
765
766         // If we permit break with a value, then result type is
767         // the LUB of the breaks (possibly ! if none); else, it
768         // is nil. This makes sense because infinite loops
769         // (which would have type !) are only possible iff we
770         // permit break with a value [1].
771         if ctxt.coerce.is_none() && !ctxt.may_break {
772             // [1]
773             self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
774         }
775         ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
776     }
777
778     /// Checks a method call.
779     fn check_method_call(
780         &self,
781         expr: &'tcx hir::Expr,
782         segment: &hir::PathSegment,
783         span: Span,
784         args: &'tcx [hir::Expr],
785         expected: Expectation<'tcx>,
786         needs: Needs,
787     ) -> Ty<'tcx> {
788         let rcvr = &args[0];
789         let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
790         // no need to check for bot/err -- callee does that
791         let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
792
793         let method = match self.lookup_method(rcvr_t,
794                                               segment,
795                                               span,
796                                               expr,
797                                               rcvr) {
798             Ok(method) => {
799                 self.write_method_call(expr.hir_id, method);
800                 Ok(method)
801             }
802             Err(error) => {
803                 if segment.ident.name != kw::Invalid {
804                     self.report_method_error(span,
805                                              rcvr_t,
806                                              segment.ident,
807                                              SelfSource::MethodCall(rcvr),
808                                              error,
809                                              Some(args));
810                 }
811                 Err(())
812             }
813         };
814
815         // Call the generic checker.
816         self.check_method_argument_types(span,
817                                          expr.span,
818                                          method,
819                                          &args[1..],
820                                          DontTupleArguments,
821                                          expected)
822     }
823
824     fn check_expr_cast(
825         &self,
826         e: &'tcx hir::Expr,
827         t: &'tcx hir::Ty,
828         expr: &'tcx hir::Expr,
829     ) -> Ty<'tcx> {
830         // Find the type of `e`. Supply hints based on the type we are casting to,
831         // if appropriate.
832         let t_cast = self.to_ty_saving_user_provided_ty(t);
833         let t_cast = self.resolve_vars_if_possible(&t_cast);
834         let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
835         let t_cast = self.resolve_vars_if_possible(&t_cast);
836
837         // Eagerly check for some obvious errors.
838         if t_expr.references_error() || t_cast.references_error() {
839             self.tcx.types.err
840         } else {
841             // Defer other checks until we're done type checking.
842             let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
843             match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
844                 Ok(cast_check) => {
845                     deferred_cast_checks.push(cast_check);
846                     t_cast
847                 }
848                 Err(ErrorReported) => {
849                     self.tcx.types.err
850                 }
851             }
852         }
853     }
854
855     fn check_expr_array(
856         &self,
857         args: &'tcx [hir::Expr],
858         expected: Expectation<'tcx>,
859         expr: &'tcx hir::Expr
860     ) -> Ty<'tcx> {
861         let uty = expected.to_option(self).and_then(|uty| {
862             match uty.sty {
863                 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
864                 _ => None
865             }
866         });
867
868         let element_ty = if !args.is_empty() {
869             let coerce_to = uty.unwrap_or_else(|| {
870                 self.next_ty_var(TypeVariableOrigin {
871                     kind: TypeVariableOriginKind::TypeInference,
872                     span: expr.span,
873                 })
874             });
875             let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
876             assert_eq!(self.diverges.get(), Diverges::Maybe);
877             for e in args {
878                 let e_ty = self.check_expr_with_hint(e, coerce_to);
879                 let cause = self.misc(e.span);
880                 coerce.coerce(self, &cause, e, e_ty);
881             }
882             coerce.complete(self)
883         } else {
884             self.next_ty_var(TypeVariableOrigin {
885                 kind: TypeVariableOriginKind::TypeInference,
886                 span: expr.span,
887             })
888         };
889         self.tcx.mk_array(element_ty, args.len() as u64)
890     }
891
892     fn check_expr_repeat(
893         &self,
894         element: &'tcx hir::Expr,
895         count: &'tcx hir::AnonConst,
896         expected: Expectation<'tcx>,
897         expr: &'tcx hir::Expr,
898     ) -> Ty<'tcx> {
899         let tcx = self.tcx;
900         let count_def_id = tcx.hir().local_def_id_from_hir_id(count.hir_id);
901         let count = if self.const_param_def_id(count).is_some() {
902             Ok(self.to_const(count, tcx.type_of(count_def_id)))
903         } else {
904             let param_env = ty::ParamEnv::empty();
905             let substs = InternalSubsts::identity_for_item(tcx.global_tcx(), count_def_id);
906             let instance = ty::Instance::resolve(
907                 tcx.global_tcx(),
908                 param_env,
909                 count_def_id,
910                 substs,
911             ).unwrap();
912             let global_id = GlobalId {
913                 instance,
914                 promoted: None
915             };
916
917             tcx.const_eval(param_env.and(global_id))
918         };
919
920         let uty = match expected {
921             ExpectHasType(uty) => {
922                 match uty.sty {
923                     ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
924                     _ => None
925                 }
926             }
927             _ => None
928         };
929
930         let (element_ty, t) = match uty {
931             Some(uty) => {
932                 self.check_expr_coercable_to_type(&element, uty);
933                 (uty, uty)
934             }
935             None => {
936                 let ty = self.next_ty_var(TypeVariableOrigin {
937                     kind: TypeVariableOriginKind::MiscVariable,
938                     span: element.span,
939                 });
940                 let element_ty = self.check_expr_has_type_or_error(&element, ty);
941                 (element_ty, ty)
942             }
943         };
944
945         if let Ok(count) = count {
946             let zero_or_one = count.assert_usize(tcx).map_or(false, |count| count <= 1);
947             if !zero_or_one {
948                 // For [foo, ..n] where n > 1, `foo` must have
949                 // Copy type:
950                 let lang_item = tcx.require_lang_item(lang_items::CopyTraitLangItem);
951                 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
952             }
953         }
954
955         if element_ty.references_error() {
956             tcx.types.err
957         } else if let Ok(count) = count {
958             tcx.mk_ty(ty::Array(t, count))
959         } else {
960             tcx.types.err
961         }
962     }
963
964     fn check_expr_tuple(
965         &self,
966         elts: &'tcx [hir::Expr],
967         expected: Expectation<'tcx>,
968         expr: &'tcx hir::Expr,
969     ) -> Ty<'tcx> {
970         let flds = expected.only_has_type(self).and_then(|ty| {
971             let ty = self.resolve_type_vars_with_obligations(ty);
972             match ty.sty {
973                 ty::Tuple(ref flds) => Some(&flds[..]),
974                 _ => None
975             }
976         });
977
978         let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
979             let t = match flds {
980                 Some(ref fs) if i < fs.len() => {
981                     let ety = fs[i].expect_ty();
982                     self.check_expr_coercable_to_type(&e, ety);
983                     ety
984                 }
985                 _ => {
986                     self.check_expr_with_expectation(&e, NoExpectation)
987                 }
988             };
989             t
990         });
991         let tuple = self.tcx.mk_tup(elt_ts_iter);
992         if tuple.references_error() {
993             self.tcx.types.err
994         } else {
995             self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
996             tuple
997         }
998     }
999
1000     fn check_expr_struct(
1001         &self,
1002         expr: &hir::Expr,
1003         expected: Expectation<'tcx>,
1004         qpath: &QPath,
1005         fields: &'tcx [hir::Field],
1006         base_expr: &'tcx Option<P<hir::Expr>>,
1007     ) -> Ty<'tcx> {
1008         // Find the relevant variant
1009         let (variant, adt_ty) =
1010             if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1011                 variant_ty
1012             } else {
1013                 self.check_struct_fields_on_error(fields, base_expr);
1014                 return self.tcx.types.err;
1015             };
1016
1017         let path_span = match *qpath {
1018             QPath::Resolved(_, ref path) => path.span,
1019             QPath::TypeRelative(ref qself, _) => qself.span
1020         };
1021
1022         // Prohibit struct expressions when non-exhaustive flag is set.
1023         let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1024         if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1025             span_err!(self.tcx.sess, expr.span, E0639,
1026                       "cannot create non-exhaustive {} using struct expression",
1027                       adt.variant_descr());
1028         }
1029
1030         let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1031                                                            variant, fields, base_expr.is_none());
1032         if let &Some(ref base_expr) = base_expr {
1033             // If check_expr_struct_fields hit an error, do not attempt to populate
1034             // the fields with the base_expr. This could cause us to hit errors later
1035             // when certain fields are assumed to exist that in fact do not.
1036             if !error_happened {
1037                 self.check_expr_has_type_or_error(base_expr, adt_ty);
1038                 match adt_ty.sty {
1039                     ty::Adt(adt, substs) if adt.is_struct() => {
1040                         let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1041                             self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1042                         }).collect();
1043
1044                         self.tables
1045                             .borrow_mut()
1046                             .fru_field_types_mut()
1047                             .insert(expr.hir_id, fru_field_types);
1048                     }
1049                     _ => {
1050                         span_err!(self.tcx.sess, base_expr.span, E0436,
1051                                   "functional record update syntax requires a struct");
1052                     }
1053                 }
1054             }
1055         }
1056         self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1057         adt_ty
1058     }
1059
1060     fn check_expr_index(
1061         &self,
1062         base: &'tcx hir::Expr,
1063         idx: &'tcx hir::Expr,
1064         needs: Needs,
1065         expr: &'tcx hir::Expr,
1066     ) -> Ty<'tcx> {
1067         let base_t = self.check_expr_with_needs(&base, needs);
1068         let idx_t = self.check_expr(&idx);
1069
1070         if base_t.references_error() {
1071             base_t
1072         } else if idx_t.references_error() {
1073             idx_t
1074         } else {
1075             let base_t = self.structurally_resolved_type(base.span, base_t);
1076             match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1077                 Some((index_ty, element_ty)) => {
1078                     // two-phase not needed because index_ty is never mutable
1079                     self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1080                     element_ty
1081                 }
1082                 None => {
1083                     let mut err =
1084                         type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1085                                             "cannot index into a value of type `{}`",
1086                                             base_t);
1087                     // Try to give some advice about indexing tuples.
1088                     if let ty::Tuple(..) = base_t.sty {
1089                         let mut needs_note = true;
1090                         // If the index is an integer, we can show the actual
1091                         // fixed expression:
1092                         if let ExprKind::Lit(ref lit) = idx.node {
1093                             if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1094                                 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1095                                 if let Ok(snip) = snip {
1096                                     err.span_suggestion(
1097                                         expr.span,
1098                                         "to access tuple elements, use",
1099                                         format!("{}.{}", snip, i),
1100                                         Applicability::MachineApplicable,
1101                                     );
1102                                     needs_note = false;
1103                                 }
1104                             }
1105                         }
1106                         if needs_note {
1107                             err.help("to access tuple elements, use tuple indexing \
1108                                         syntax (e.g., `tuple.0`)");
1109                         }
1110                     }
1111                     err.emit();
1112                     self.tcx.types.err
1113                 }
1114             }
1115         }
1116     }
1117
1118     fn check_expr_yield(&self, value: &'tcx hir::Expr, expr: &'tcx hir::Expr) -> Ty<'tcx> {
1119         match self.yield_ty {
1120             Some(ty) => {
1121                 self.check_expr_coercable_to_type(&value, ty);
1122             }
1123             None => {
1124                 struct_span_err!(self.tcx.sess, expr.span, E0627,
1125                                     "yield statement outside of generator literal").emit();
1126             }
1127         }
1128         self.tcx.mk_unit()
1129     }
1130 }