1 //! Type checking expressions.
3 //! See `mod.rs` for more context on type checking in general.
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;
19 use errors::Applicability;
22 use syntax::symbol::{kw, sym};
23 use syntax::source_map::Span;
25 use rustc::hir::{ExprKind, QPath};
26 use rustc::hir::def::{CtorKind, Res, DefKind};
28 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
29 use rustc::mir::interpret::GlobalId;
31 use rustc::ty::adjustment::{
32 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
35 use rustc::ty::TypeFoldable;
36 use rustc::ty::subst::InternalSubsts;
37 use rustc::traits::{self, ObligationCauseCode};
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);
45 pub fn check_expr_has_type_or_error(
47 expr: &'tcx hir::Expr,
50 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected))
53 fn check_expr_meets_expectation_or_error(
55 expr: &'tcx hir::Expr,
56 expected: Expectation<'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);
61 // While we don't allow *arbitrary* coercions here, we *do* allow
62 // coercions from ! to `expected`.
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(
68 kind: TypeVariableOriginKind::AdjustmentType,
72 self.apply_adjustments(expr, vec![Adjustment {
73 kind: Adjust::NeverToAny,
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,
84 // Error possibly reported in `check_assign` so avoid emitting error again.
85 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
90 pub(super) fn check_expr_coercable_to_type(
92 expr: &'tcx hir::Expr,
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)
100 pub(super) fn check_expr_with_hint(
102 expr: &'tcx hir::Expr,
105 self.check_expr_with_expectation(expr, ExpectHasType(expected))
108 pub(super) fn check_expr_with_expectation(
110 expr: &'tcx hir::Expr,
111 expected: Expectation<'tcx>,
113 self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
116 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
117 self.check_expr_with_expectation(expr, NoExpectation)
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)
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(
136 expr: &'tcx hir::Expr,
137 expected: Expectation<'tcx>,
140 debug!(">> type-checking: expr={:?} expected={:?}",
143 // Warn for expressions after diverging siblings.
144 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
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);
152 let ty = self.check_expr_kind(expr, expected, needs);
154 // Warn for non-block expressions with diverging children.
156 ExprKind::Block(..) |
157 ExprKind::Loop(..) | ExprKind::While(..) |
158 ExprKind::Match(..) => {}
160 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression")
163 // Any expression that produces a value of type `!` must have diverged
165 self.diverges.set(self.diverges.get() | Diverges::Always);
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);
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);
177 debug!("type of {} is...", self.tcx.hir().hir_to_string(expr.hir_id));
178 debug!("... {:?}, expected is {:?}", ty, expected);
185 expr: &'tcx hir::Expr,
186 expected: Expectation<'tcx>,
190 "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
198 ExprKind::Box(ref subexpr) => {
199 self.check_expr_box(subexpr, expected)
201 ExprKind::Lit(ref lit) => {
202 self.check_lit(&lit, expected)
204 ExprKind::Binary(op, ref lhs, ref rhs) => {
205 self.check_binop(expr, op, lhs, rhs)
207 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
208 self.check_binop_assign(expr, op, lhs, rhs)
210 ExprKind::Unary(unop, ref oprnd) => {
211 self.check_expr_unary(unop, oprnd, expected, needs, expr)
213 ExprKind::AddrOf(mutbl, ref oprnd) => {
214 self.check_expr_addr_of(mutbl, oprnd, expected, expr)
216 ExprKind::Path(ref qpath) => {
217 self.check_expr_path(qpath, expr)
219 ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
220 for expr in outputs.iter().chain(inputs.iter()) {
221 self.check_expr(expr);
225 ExprKind::Break(destination, ref expr_opt) => {
226 self.check_expr_break(destination, expr_opt.deref(), expr)
228 ExprKind::Continue(destination) => {
229 if destination.target_id.is_ok() {
232 // There was an error; make type-check fail.
236 ExprKind::Ret(ref expr_opt) => {
237 self.check_expr_return(expr_opt.deref(), expr)
239 ExprKind::Assign(ref lhs, ref rhs) => {
240 self.check_expr_assign(expr, expected, lhs, rhs)
242 ExprKind::While(ref cond, ref body, _) => {
243 self.check_expr_while(cond, body, expr)
245 ExprKind::Loop(ref body, _, source) => {
246 self.check_expr_loop(body, source, expected, expr)
248 ExprKind::Match(ref discrim, ref arms, match_src) => {
249 self.check_match(expr, &discrim, arms, expected, match_src)
251 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
252 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
254 ExprKind::Block(ref body, _) => {
255 self.check_block_with_expected(&body, expected)
257 ExprKind::Call(ref callee, ref args) => {
258 self.check_call(expr, &callee, args, expected)
260 ExprKind::MethodCall(ref segment, span, ref args) => {
261 self.check_method_call(expr, segment, span, args, expected, needs)
263 ExprKind::Cast(ref e, ref t) => {
264 self.check_expr_cast(e, t, expr)
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);
271 ExprKind::DropTemps(ref e) => {
272 self.check_expr_with_expectation(e, expected)
274 ExprKind::Array(ref args) => {
275 self.check_expr_array(args, expected, expr)
277 ExprKind::Repeat(ref element, ref count) => {
278 self.check_expr_repeat(element, count, expected, expr)
280 ExprKind::Tup(ref elts) => {
281 self.check_expr_tuple(elts, expected, expr)
283 ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
284 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
286 ExprKind::Field(ref base, field) => {
287 self.check_field(expr, needs, &base, field)
289 ExprKind::Index(ref base, ref idx) => {
290 self.check_expr_index(base, idx, needs, expr)
292 ExprKind::Yield(ref value) => {
293 self.check_expr_yield(value, expr)
295 hir::ExprKind::Err => {
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| {
304 ty::Adt(def, _) if def.is_box()
305 => Expectation::rvalue_hint(self, ty.boxed_ty()),
309 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
310 self.tcx.mk_box(referent_ty)
316 oprnd: &'tcx hir::Expr,
317 expected: Expectation<'tcx>,
319 expr: &'tcx hir::Expr,
322 let expected_inner = match unop {
323 hir::UnNot | hir::UnNeg => expected,
324 hir::UnDeref => NoExpectation,
326 let needs = match unop {
327 hir::UnDeref => needs,
330 let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
332 if !oprnd_t.references_error() {
333 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
336 if let Some(mt) = oprnd_t.builtin_deref(true) {
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,
351 self.apply_adjustments(oprnd, vec![Adjustment {
352 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
353 target: method.sig.inputs()[0]
356 oprnd_t = self.make_overloaded_place_return_type(method).ty;
357 self.write_method_call(expr.hir_id, method);
359 let mut err = type_error_struct!(
364 "type `{}` cannot be dereferenced",
367 let sp = tcx.sess.source_map().start_point(expr.span);
368 if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
371 tcx.sess.parse_sess.expr_parentheses_needed(
378 oprnd_t = tcx.types.err;
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) {
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() {
400 fn check_expr_addr_of(
402 mutbl: hir::Mutability,
403 oprnd: &'tcx hir::Expr,
404 expected: Expectation<'tcx>,
405 expr: &'tcx hir::Expr,
407 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
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.
416 Expectation::rvalue_hint(self, ty)
422 let needs = Needs::maybe_mut_place(mutbl);
423 let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
425 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
426 if tm.ty.references_error() {
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.
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)
447 fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
449 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
452 self.set_tainted_by_errors();
455 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
456 report_unexpected_variant_res(tcx, res, expr.span, qpath);
459 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
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
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
478 let input = self.replace_bound_vars_with_fresh_vars(
480 infer::LateBoundRegionConversionTime::FnCall,
482 self.require_type_is_sized_deferred(input, expr.span,
483 traits::SizedArgumentType);
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
492 let output = self.replace_bound_vars_with_fresh_vars(
494 infer::LateBoundRegionConversionTime::FnCall,
496 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
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);
509 destination: hir::Destination,
510 expr_opt: Option<&'tcx hir::Expr>,
511 expr: &'tcx hir::Expr,
514 if let Ok(target_id) = destination.target_id {
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)
524 .map(|coerce| coerce.expected_ty())
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);
532 // Recurse without `enclosing_breakables` borrowed.
533 e_ty = self.check_expr_with_hint(e, coerce_to);
534 cause = self.misc(e.span);
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);
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);
551 assert!(e_ty.is_unit());
552 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
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);
565 ctxt.may_break = true;
567 // the type of a `break` is always `!`, since it diverges
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");
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);
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);
593 // There was an error; make type-check fail.
598 fn check_expr_return(
600 expr_opt: Option<&'tcx hir::Expr>,
601 expr: &'tcx hir::Expr
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);
610 self.check_return_expr(e);
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);
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(
623 fn_decl.output.span(),
625 "expected `{}` because of this return type",
633 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
639 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
643 .unwrap_or_else(|| span_bug!(return_expr.span,
644 "check_return_expr called outside fn body"));
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()
650 &self.cause(return_expr.span,
651 ObligationCauseCode::ReturnType(return_expr.hir_id)),
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(
660 expr: &'tcx hir::Expr,
661 expected: Expectation<'tcx>,
662 lhs: &'tcx hir::Expr,
663 rhs: &'tcx hir::Expr,
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);
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);
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")
692 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
694 if lhs_ty.references_error() || rhs_ty.references_error() {
703 cond: &'tcx hir::Expr,
704 body: &'tcx hir::Block,
705 expr: &'tcx hir::Expr
707 let ctxt = BreakableCtxt {
708 // Cannot use break with a value from a while loop.
710 may_break: false, // Will get updated if/when we find a `break`.
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);
718 // We may never reach the body so it diverging means nothing.
719 self.diverges.set(cond_diverging);
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);
733 body: &'tcx hir::Block,
734 source: hir::LoopSource,
735 expected: Expectation<'tcx>,
736 expr: &'tcx hir::Expr,
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))
745 hir::LoopSource::WhileLet |
746 hir::LoopSource::ForLoop => {
751 let ctxt = BreakableCtxt {
753 may_break: false, // Will get updated if/when we find a `break`.
756 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
757 self.check_block_no_value(&body);
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);
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 {
773 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
775 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
778 /// Checks a method call.
779 fn check_method_call(
781 expr: &'tcx hir::Expr,
782 segment: &hir::PathSegment,
784 args: &'tcx [hir::Expr],
785 expected: Expectation<'tcx>,
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);
793 let method = match self.lookup_method(rcvr_t,
799 self.write_method_call(expr.hir_id, method);
803 if segment.ident.name != kw::Invalid {
804 self.report_method_error(span,
807 SelfSource::MethodCall(rcvr),
815 // Call the generic checker.
816 self.check_method_argument_types(span,
828 expr: &'tcx hir::Expr,
830 // Find the type of `e`. Supply hints based on the type we are casting to,
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);
837 // Eagerly check for some obvious errors.
838 if t_expr.references_error() || t_cast.references_error() {
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) {
845 deferred_cast_checks.push(cast_check);
848 Err(ErrorReported) => {
857 args: &'tcx [hir::Expr],
858 expected: Expectation<'tcx>,
859 expr: &'tcx hir::Expr
861 let uty = expected.to_option(self).and_then(|uty| {
863 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
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,
875 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
876 assert_eq!(self.diverges.get(), Diverges::Maybe);
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);
882 coerce.complete(self)
884 self.next_ty_var(TypeVariableOrigin {
885 kind: TypeVariableOriginKind::TypeInference,
889 self.tcx.mk_array(element_ty, args.len() as u64)
892 fn check_expr_repeat(
894 element: &'tcx hir::Expr,
895 count: &'tcx hir::AnonConst,
896 expected: Expectation<'tcx>,
897 expr: &'tcx hir::Expr,
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)))
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(
912 let global_id = GlobalId {
917 tcx.const_eval(param_env.and(global_id))
920 let uty = match expected {
921 ExpectHasType(uty) => {
923 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
930 let (element_ty, t) = match uty {
932 self.check_expr_coercable_to_type(&element, uty);
936 let ty = self.next_ty_var(TypeVariableOrigin {
937 kind: TypeVariableOriginKind::MiscVariable,
940 let element_ty = self.check_expr_has_type_or_error(&element, ty);
945 if let Ok(count) = count {
946 let zero_or_one = count.assert_usize(tcx).map_or(false, |count| count <= 1);
948 // For [foo, ..n] where n > 1, `foo` must have
950 let lang_item = tcx.require_lang_item(lang_items::CopyTraitLangItem);
951 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
955 if element_ty.references_error() {
957 } else if let Ok(count) = count {
958 tcx.mk_ty(ty::Array(t, count))
966 elts: &'tcx [hir::Expr],
967 expected: Expectation<'tcx>,
968 expr: &'tcx hir::Expr,
970 let flds = expected.only_has_type(self).and_then(|ty| {
971 let ty = self.resolve_type_vars_with_obligations(ty);
973 ty::Tuple(ref flds) => Some(&flds[..]),
978 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
980 Some(ref fs) if i < fs.len() => {
981 let ety = fs[i].expect_ty();
982 self.check_expr_coercable_to_type(&e, ety);
986 self.check_expr_with_expectation(&e, NoExpectation)
991 let tuple = self.tcx.mk_tup(elt_ts_iter);
992 if tuple.references_error() {
995 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1000 fn check_expr_struct(
1003 expected: Expectation<'tcx>,
1005 fields: &'tcx [hir::Field],
1006 base_expr: &'tcx Option<P<hir::Expr>>,
1008 // Find the relevant variant
1009 let (variant, adt_ty) =
1010 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1013 self.check_struct_fields_on_error(fields, base_expr);
1014 return self.tcx.types.err;
1017 let path_span = match *qpath {
1018 QPath::Resolved(_, ref path) => path.span,
1019 QPath::TypeRelative(ref qself, _) => qself.span
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());
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);
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))
1046 .fru_field_types_mut()
1047 .insert(expr.hir_id, fru_field_types);
1050 span_err!(self.tcx.sess, base_expr.span, E0436,
1051 "functional record update syntax requires a struct");
1056 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1060 fn check_expr_index(
1062 base: &'tcx hir::Expr,
1063 idx: &'tcx hir::Expr,
1065 expr: &'tcx hir::Expr,
1067 let base_t = self.check_expr_with_needs(&base, needs);
1068 let idx_t = self.check_expr(&idx);
1070 if base_t.references_error() {
1072 } else if idx_t.references_error() {
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);
1084 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1085 "cannot index into a value of type `{}`",
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(
1098 "to access tuple elements, use",
1099 format!("{}.{}", snip, i),
1100 Applicability::MachineApplicable,
1107 err.help("to access tuple elements, use tuple indexing \
1108 syntax (e.g., `tuple.0`)");
1118 fn check_expr_yield(&self, value: &'tcx hir::Expr, expr: &'tcx hir::Expr) -> Ty<'tcx> {
1119 match self.yield_ty {
1121 self.check_expr_coercable_to_type(&value, ty);
1124 struct_span_err!(self.tcx.sess, expr.span, E0627,
1125 "yield statement outside of generator literal").emit();