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;
18 use crate::util::nodemap::FxHashMap;
19 use crate::astconv::AstConv as _;
21 use errors::{Applicability, DiagnosticBuilder};
24 use syntax::symbol::{Symbol, LocalInternedString, kw, sym};
25 use syntax::source_map::Span;
26 use syntax::util::lev_distance::find_best_match_for_name;
28 use rustc::hir::{ExprKind, QPath};
29 use rustc::hir::def::{CtorKind, Res, DefKind};
31 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
32 use rustc::mir::interpret::GlobalId;
34 use rustc::ty::adjustment::{
35 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
37 use rustc::ty::{AdtKind, Visibility};
39 use rustc::ty::TypeFoldable;
40 use rustc::ty::subst::InternalSubsts;
41 use rustc::traits::{self, ObligationCauseCode};
43 use std::fmt::Display;
45 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
46 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
47 let ty = self.check_expr_with_hint(expr, expected);
48 self.demand_eqtype(expr.span, expected, ty);
51 pub fn check_expr_has_type_or_error(
53 expr: &'tcx hir::Expr,
56 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected))
59 fn check_expr_meets_expectation_or_error(
61 expr: &'tcx hir::Expr,
62 expected: Expectation<'tcx>,
64 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
65 let mut ty = self.check_expr_with_expectation(expr, expected);
67 // While we don't allow *arbitrary* coercions here, we *do* allow
68 // coercions from ! to `expected`.
70 assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
71 "expression with never type wound up being adjusted");
72 let adj_ty = self.next_diverging_ty_var(
74 kind: TypeVariableOriginKind::AdjustmentType,
78 self.apply_adjustments(expr, vec![Adjustment {
79 kind: Adjust::NeverToAny,
85 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
86 let expr = match &expr.node {
87 ExprKind::DropTemps(expr) => expr,
90 // Error possibly reported in `check_assign` so avoid emitting error again.
91 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
96 pub(super) fn check_expr_coercable_to_type(
98 expr: &'tcx hir::Expr,
101 let ty = self.check_expr_with_hint(expr, expected);
102 // checks don't need two phase
103 self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
106 pub(super) fn check_expr_with_hint(
108 expr: &'tcx hir::Expr,
111 self.check_expr_with_expectation(expr, ExpectHasType(expected))
114 pub(super) fn check_expr_with_expectation(
116 expr: &'tcx hir::Expr,
117 expected: Expectation<'tcx>,
119 self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
122 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
123 self.check_expr_with_expectation(expr, NoExpectation)
126 pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
127 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
131 /// If an expression has any sub-expressions that result in a type error,
132 /// inspecting that expression's type with `ty.references_error()` will return
133 /// true. Likewise, if an expression is known to diverge, inspecting its
134 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
135 /// strict, _|_ can appear in the type of an expression that does not,
136 /// itself, diverge: for example, fn() -> _|_.)
137 /// Note that inspecting a type's structure *directly* may expose the fact
138 /// that there are actually multiple representations for `Error`, so avoid
139 /// that when err needs to be handled differently.
140 fn check_expr_with_expectation_and_needs(
142 expr: &'tcx hir::Expr,
143 expected: Expectation<'tcx>,
146 debug!(">> type-checking: expr={:?} expected={:?}",
149 // Warn for expressions after diverging siblings.
150 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
152 // Hide the outer diverging and has_errors flags.
153 let old_diverges = self.diverges.get();
154 let old_has_errors = self.has_errors.get();
155 self.diverges.set(Diverges::Maybe);
156 self.has_errors.set(false);
158 let ty = self.check_expr_kind(expr, expected, needs);
160 // Warn for non-block expressions with diverging children.
162 ExprKind::Block(..) |
163 ExprKind::Loop(..) | ExprKind::While(..) |
164 ExprKind::Match(..) => {}
166 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression")
169 // Any expression that produces a value of type `!` must have diverged
171 self.diverges.set(self.diverges.get() | Diverges::Always);
174 // Record the type, which applies it effects.
175 // We need to do this after the warning above, so that
176 // we don't warn for the diverging expression itself.
177 self.write_ty(expr.hir_id, ty);
179 // Combine the diverging and has_error flags.
180 self.diverges.set(self.diverges.get() | old_diverges);
181 self.has_errors.set(self.has_errors.get() | old_has_errors);
183 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
184 debug!("... {:?}, expected is {:?}", ty, expected);
191 expr: &'tcx hir::Expr,
192 expected: Expectation<'tcx>,
196 "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
204 ExprKind::Box(ref subexpr) => {
205 self.check_expr_box(subexpr, expected)
207 ExprKind::Lit(ref lit) => {
208 self.check_lit(&lit, expected)
210 ExprKind::Binary(op, ref lhs, ref rhs) => {
211 self.check_binop(expr, op, lhs, rhs)
213 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
214 self.check_binop_assign(expr, op, lhs, rhs)
216 ExprKind::Unary(unop, ref oprnd) => {
217 self.check_expr_unary(unop, oprnd, expected, needs, expr)
219 ExprKind::AddrOf(mutbl, ref oprnd) => {
220 self.check_expr_addr_of(mutbl, oprnd, expected, expr)
222 ExprKind::Path(ref qpath) => {
223 self.check_expr_path(qpath, expr)
225 ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
226 for expr in outputs.iter().chain(inputs.iter()) {
227 self.check_expr(expr);
231 ExprKind::Break(destination, ref expr_opt) => {
232 self.check_expr_break(destination, expr_opt.deref(), expr)
234 ExprKind::Continue(destination) => {
235 if destination.target_id.is_ok() {
238 // There was an error; make type-check fail.
242 ExprKind::Ret(ref expr_opt) => {
243 self.check_expr_return(expr_opt.deref(), expr)
245 ExprKind::Assign(ref lhs, ref rhs) => {
246 self.check_expr_assign(expr, expected, lhs, rhs)
248 ExprKind::While(ref cond, ref body, _) => {
249 self.check_expr_while(cond, body, expr)
251 ExprKind::Loop(ref body, _, source) => {
252 self.check_expr_loop(body, source, expected, expr)
254 ExprKind::Match(ref discrim, ref arms, match_src) => {
255 self.check_match(expr, &discrim, arms, expected, match_src)
257 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
258 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
260 ExprKind::Block(ref body, _) => {
261 self.check_block_with_expected(&body, expected)
263 ExprKind::Call(ref callee, ref args) => {
264 self.check_call(expr, &callee, args, expected)
266 ExprKind::MethodCall(ref segment, span, ref args) => {
267 self.check_method_call(expr, segment, span, args, expected, needs)
269 ExprKind::Cast(ref e, ref t) => {
270 self.check_expr_cast(e, t, expr)
272 ExprKind::Type(ref e, ref t) => {
273 let ty = self.to_ty_saving_user_provided_ty(&t);
274 self.check_expr_eq_type(&e, ty);
277 ExprKind::DropTemps(ref e) => {
278 self.check_expr_with_expectation(e, expected)
280 ExprKind::Array(ref args) => {
281 self.check_expr_array(args, expected, expr)
283 ExprKind::Repeat(ref element, ref count) => {
284 self.check_expr_repeat(element, count, expected, expr)
286 ExprKind::Tup(ref elts) => {
287 self.check_expr_tuple(elts, expected, expr)
289 ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
290 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
292 ExprKind::Field(ref base, field) => {
293 self.check_field(expr, needs, &base, field)
295 ExprKind::Index(ref base, ref idx) => {
296 self.check_expr_index(base, idx, needs, expr)
298 ExprKind::Yield(ref value, _) => {
299 self.check_expr_yield(value, expr)
301 hir::ExprKind::Err => {
307 fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
308 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
310 ty::Adt(def, _) if def.is_box()
311 => Expectation::rvalue_hint(self, ty.boxed_ty()),
315 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
316 self.tcx.mk_box(referent_ty)
322 oprnd: &'tcx hir::Expr,
323 expected: Expectation<'tcx>,
325 expr: &'tcx hir::Expr,
328 let expected_inner = match unop {
329 hir::UnNot | hir::UnNeg => expected,
330 hir::UnDeref => NoExpectation,
332 let needs = match unop {
333 hir::UnDeref => needs,
336 let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
338 if !oprnd_t.references_error() {
339 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
342 if let Some(mt) = oprnd_t.builtin_deref(true) {
344 } else if let Some(ok) = self.try_overloaded_deref(
345 expr.span, oprnd_t, needs) {
346 let method = self.register_infer_ok_obligations(ok);
347 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].sty {
348 let mutbl = match mutbl {
349 hir::MutImmutable => AutoBorrowMutability::Immutable,
350 hir::MutMutable => AutoBorrowMutability::Mutable {
351 // (It shouldn't actually matter for unary ops whether
352 // we enable two-phase borrows or not, since a unary
353 // op has no additional operands.)
354 allow_two_phase_borrow: AllowTwoPhase::No,
357 self.apply_adjustments(oprnd, vec![Adjustment {
358 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
359 target: method.sig.inputs()[0]
362 oprnd_t = self.make_overloaded_place_return_type(method).ty;
363 self.write_method_call(expr.hir_id, method);
365 let mut err = type_error_struct!(
370 "type `{}` cannot be dereferenced",
373 let sp = tcx.sess.source_map().start_point(expr.span);
374 if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
377 tcx.sess.parse_sess.expr_parentheses_needed(
384 oprnd_t = tcx.types.err;
388 let result = self.check_user_unop(expr, oprnd_t, unop);
389 // If it's builtin, we can reuse the type, this helps inference.
390 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::Bool) {
395 let result = self.check_user_unop(expr, oprnd_t, unop);
396 // If it's builtin, we can reuse the type, this helps inference.
397 if !oprnd_t.is_numeric() {
406 fn check_expr_addr_of(
408 mutbl: hir::Mutability,
409 oprnd: &'tcx hir::Expr,
410 expected: Expectation<'tcx>,
411 expr: &'tcx hir::Expr,
413 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
415 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
416 if oprnd.is_place_expr() {
417 // Places may legitimately have unsized types.
418 // For example, dereferences of a fat pointer and
419 // the last field of a struct can be unsized.
422 Expectation::rvalue_hint(self, ty)
428 let needs = Needs::maybe_mut_place(mutbl);
429 let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
431 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
432 if tm.ty.references_error() {
435 // Note: at this point, we cannot say what the best lifetime
436 // is to use for resulting pointer. We want to use the
437 // shortest lifetime possible so as to avoid spurious borrowck
438 // errors. Moreover, the longest lifetime will depend on the
439 // precise details of the value whose address is being taken
440 // (and how long it is valid), which we don't know yet until type
441 // inference is complete.
443 // Therefore, here we simply generate a region variable. The
444 // region inferencer will then select the ultimate value.
445 // Finally, borrowck is charged with guaranteeing that the
446 // value whose address was taken can actually be made to live
447 // as long as it needs to live.
448 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
449 self.tcx.mk_ref(region, tm)
453 fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
455 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
458 self.set_tainted_by_errors();
461 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
462 report_unexpected_variant_res(tcx, res, expr.span, qpath);
465 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
468 if let ty::FnDef(..) = ty.sty {
469 let fn_sig = ty.fn_sig(tcx);
470 if !tcx.features().unsized_locals {
471 // We want to remove some Sized bounds from std functions,
472 // but don't want to expose the removal to stable Rust.
473 // i.e., we don't want to allow
479 // to work in stable even if the Sized bound on `drop` is relaxed.
480 for i in 0..fn_sig.inputs().skip_binder().len() {
481 // We just want to check sizedness, so instead of introducing
482 // placeholder lifetimes with probing, we just replace higher lifetimes
484 let input = self.replace_bound_vars_with_fresh_vars(
486 infer::LateBoundRegionConversionTime::FnCall,
488 self.require_type_is_sized_deferred(input, expr.span,
489 traits::SizedArgumentType);
492 // Here we want to prevent struct constructors from returning unsized types.
493 // There were two cases this happened: fn pointer coercion in stable
494 // and usual function call in presense of unsized_locals.
495 // Also, as we just want to check sizedness, instead of introducing
496 // placeholder lifetimes with probing, we just replace higher lifetimes
498 let output = self.replace_bound_vars_with_fresh_vars(
500 infer::LateBoundRegionConversionTime::FnCall,
502 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
505 // We always require that the type provided as the value for
506 // a type parameter outlives the moment of instantiation.
507 let substs = self.tables.borrow().node_substs(expr.hir_id);
508 self.add_wf_bounds(substs, expr);
515 destination: hir::Destination,
516 expr_opt: Option<&'tcx hir::Expr>,
517 expr: &'tcx hir::Expr,
520 if let Ok(target_id) = destination.target_id {
522 if let Some(ref e) = expr_opt {
523 // If this is a break with a value, we need to type-check
524 // the expression. Get an expected type from the loop context.
525 let opt_coerce_to = {
526 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
527 enclosing_breakables.find_breakable(target_id)
530 .map(|coerce| coerce.expected_ty())
533 // If the loop context is not a `loop { }`, then break with
534 // a value is illegal, and `opt_coerce_to` will be `None`.
535 // Just set expectation to error in that case.
536 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
538 // Recurse without `enclosing_breakables` borrowed.
539 e_ty = self.check_expr_with_hint(e, coerce_to);
540 cause = self.misc(e.span);
542 // Otherwise, this is a break *without* a value. That's
543 // always legal, and is equivalent to `break ()`.
544 e_ty = tcx.mk_unit();
545 cause = self.misc(expr.span);
548 // Now that we have type-checked `expr_opt`, borrow
549 // the `enclosing_loops` field and let's coerce the
550 // type of `expr_opt` into what is expected.
551 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
552 let ctxt = enclosing_breakables.find_breakable(target_id);
553 if let Some(ref mut coerce) = ctxt.coerce {
554 if let Some(ref e) = expr_opt {
555 coerce.coerce(self, &cause, e, e_ty);
557 assert!(e_ty.is_unit());
558 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
561 // If `ctxt.coerce` is `None`, we can just ignore
562 // the type of the expresison. This is because
563 // either this was a break *without* a value, in
564 // which case it is always a legal type (`()`), or
565 // else an error would have been flagged by the
566 // `loops` pass for using break with an expression
567 // where you are not supposed to.
568 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
571 ctxt.may_break = true;
573 // the type of a `break` is always `!`, since it diverges
576 // Otherwise, we failed to find the enclosing loop;
577 // this can only happen if the `break` was not
578 // inside a loop at all, which is caught by the
579 // loop-checking pass.
580 self.tcx.sess.delay_span_bug(expr.span,
581 "break was outside loop, but no error was emitted");
583 // We still need to assign a type to the inner expression to
584 // prevent the ICE in #43162.
585 if let Some(ref e) = expr_opt {
586 self.check_expr_with_hint(e, tcx.types.err);
588 // ... except when we try to 'break rust;'.
589 // ICE this expression in particular (see #43162).
590 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node {
591 if path.segments.len() == 1 &&
592 path.segments[0].ident.name == sym::rust {
593 fatally_break_rust(self.tcx.sess);
597 // There was an error; make type-check fail.
602 fn check_expr_return(
604 expr_opt: Option<&'tcx hir::Expr>,
605 expr: &'tcx hir::Expr
607 if self.ret_coercion.is_none() {
608 struct_span_err!(self.tcx.sess, expr.span, E0572,
609 "return statement outside of function body").emit();
610 } else if let Some(ref e) = expr_opt {
611 if self.ret_coercion_span.borrow().is_none() {
612 *self.ret_coercion_span.borrow_mut() = Some(e.span);
614 self.check_return_expr(e);
616 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
617 if self.ret_coercion_span.borrow().is_none() {
618 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
620 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
621 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
622 coercion.coerce_forced_unit(
627 fn_decl.output.span(),
629 "expected `{}` because of this return type",
637 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
643 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
647 .unwrap_or_else(|| span_bug!(return_expr.span,
648 "check_return_expr called outside fn body"));
650 let ret_ty = ret_coercion.borrow().expected_ty();
651 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
652 ret_coercion.borrow_mut()
654 &self.cause(return_expr.span,
655 ObligationCauseCode::ReturnType(return_expr.hir_id)),
660 /// Type check assignment expression `expr` of form `lhs = rhs`.
661 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
662 fn check_expr_assign(
664 expr: &'tcx hir::Expr,
665 expected: Expectation<'tcx>,
666 lhs: &'tcx hir::Expr,
667 rhs: &'tcx hir::Expr,
669 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
670 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
672 let expected_ty = expected.coercion_target_type(self, expr.span);
673 if expected_ty == self.tcx.types.bool {
674 // The expected type is `bool` but this will result in `()` so we can reasonably
675 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
676 // The likely cause of this is `if foo = bar { .. }`.
677 let actual_ty = self.tcx.mk_unit();
678 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
679 let msg = "try comparing for equality";
680 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
681 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
682 if let (Ok(left), Ok(right)) = (left, right) {
683 let help = format!("{} == {}", left, right);
684 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
689 } else if !lhs.is_place_expr() {
690 struct_span_err!(self.tcx.sess, expr.span, E0070,
691 "invalid left-hand side expression")
692 .span_label(expr.span, "left-hand of expression not valid")
696 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
698 if lhs_ty.references_error() || rhs_ty.references_error() {
707 cond: &'tcx hir::Expr,
708 body: &'tcx hir::Block,
709 expr: &'tcx hir::Expr
711 let ctxt = BreakableCtxt {
712 // Cannot use break with a value from a while loop.
714 may_break: false, // Will get updated if/when we find a `break`.
717 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
718 self.check_expr_has_type_or_error(&cond, self.tcx.types.bool);
719 let cond_diverging = self.diverges.get();
720 self.check_block_no_value(&body);
722 // We may never reach the body so it diverging means nothing.
723 self.diverges.set(cond_diverging);
727 // No way to know whether it's diverging because
728 // of a `break` or an outer `break` or `return`.
729 self.diverges.set(Diverges::Maybe);
737 body: &'tcx hir::Block,
738 source: hir::LoopSource,
739 expected: Expectation<'tcx>,
740 expr: &'tcx hir::Expr,
742 let coerce = match source {
743 // you can only use break with a value from a normal `loop { }`
744 hir::LoopSource::Loop => {
745 let coerce_to = expected.coercion_target_type(self, body.span);
746 Some(CoerceMany::new(coerce_to))
749 hir::LoopSource::WhileLet |
750 hir::LoopSource::ForLoop => {
755 let ctxt = BreakableCtxt {
757 may_break: false, // Will get updated if/when we find a `break`.
760 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
761 self.check_block_no_value(&body);
765 // No way to know whether it's diverging because
766 // of a `break` or an outer `break` or `return`.
767 self.diverges.set(Diverges::Maybe);
770 // If we permit break with a value, then result type is
771 // the LUB of the breaks (possibly ! if none); else, it
772 // is nil. This makes sense because infinite loops
773 // (which would have type !) are only possible iff we
774 // permit break with a value [1].
775 if ctxt.coerce.is_none() && !ctxt.may_break {
777 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
779 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
782 /// Checks a method call.
783 fn check_method_call(
785 expr: &'tcx hir::Expr,
786 segment: &hir::PathSegment,
788 args: &'tcx [hir::Expr],
789 expected: Expectation<'tcx>,
793 let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
794 // no need to check for bot/err -- callee does that
795 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
797 let method = match self.lookup_method(rcvr_t,
803 self.write_method_call(expr.hir_id, method);
807 if segment.ident.name != kw::Invalid {
808 self.report_method_error(span,
811 SelfSource::MethodCall(rcvr),
819 // Call the generic checker.
820 self.check_method_argument_types(span,
832 expr: &'tcx hir::Expr,
834 // Find the type of `e`. Supply hints based on the type we are casting to,
836 let t_cast = self.to_ty_saving_user_provided_ty(t);
837 let t_cast = self.resolve_vars_if_possible(&t_cast);
838 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
839 let t_cast = self.resolve_vars_if_possible(&t_cast);
841 // Eagerly check for some obvious errors.
842 if t_expr.references_error() || t_cast.references_error() {
845 // Defer other checks until we're done type checking.
846 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
847 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
849 deferred_cast_checks.push(cast_check);
852 Err(ErrorReported) => {
861 args: &'tcx [hir::Expr],
862 expected: Expectation<'tcx>,
863 expr: &'tcx hir::Expr
865 let uty = expected.to_option(self).and_then(|uty| {
867 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
872 let element_ty = if !args.is_empty() {
873 let coerce_to = uty.unwrap_or_else(|| {
874 self.next_ty_var(TypeVariableOrigin {
875 kind: TypeVariableOriginKind::TypeInference,
879 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
880 assert_eq!(self.diverges.get(), Diverges::Maybe);
882 let e_ty = self.check_expr_with_hint(e, coerce_to);
883 let cause = self.misc(e.span);
884 coerce.coerce(self, &cause, e, e_ty);
886 coerce.complete(self)
888 self.next_ty_var(TypeVariableOrigin {
889 kind: TypeVariableOriginKind::TypeInference,
893 self.tcx.mk_array(element_ty, args.len() as u64)
896 fn check_expr_repeat(
898 element: &'tcx hir::Expr,
899 count: &'tcx hir::AnonConst,
900 expected: Expectation<'tcx>,
901 expr: &'tcx hir::Expr,
904 let count_def_id = tcx.hir().local_def_id_from_hir_id(count.hir_id);
905 let count = if self.const_param_def_id(count).is_some() {
906 Ok(self.to_const(count, tcx.type_of(count_def_id)))
908 let param_env = ty::ParamEnv::empty();
909 let substs = InternalSubsts::identity_for_item(tcx.global_tcx(), count_def_id);
910 let instance = ty::Instance::resolve(
916 let global_id = GlobalId {
921 tcx.const_eval(param_env.and(global_id))
924 let uty = match expected {
925 ExpectHasType(uty) => {
927 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
934 let (element_ty, t) = match uty {
936 self.check_expr_coercable_to_type(&element, uty);
940 let ty = self.next_ty_var(TypeVariableOrigin {
941 kind: TypeVariableOriginKind::MiscVariable,
944 let element_ty = self.check_expr_has_type_or_error(&element, ty);
949 if let Ok(count) = count {
950 let zero_or_one = count.assert_usize(tcx).map_or(false, |count| count <= 1);
952 // For [foo, ..n] where n > 1, `foo` must have
954 let lang_item = tcx.require_lang_item(lang_items::CopyTraitLangItem);
955 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
959 if element_ty.references_error() {
961 } else if let Ok(count) = count {
962 tcx.mk_ty(ty::Array(t, count))
970 elts: &'tcx [hir::Expr],
971 expected: Expectation<'tcx>,
972 expr: &'tcx hir::Expr,
974 let flds = expected.only_has_type(self).and_then(|ty| {
975 let ty = self.resolve_type_vars_with_obligations(ty);
977 ty::Tuple(ref flds) => Some(&flds[..]),
982 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
984 Some(ref fs) if i < fs.len() => {
985 let ety = fs[i].expect_ty();
986 self.check_expr_coercable_to_type(&e, ety);
990 self.check_expr_with_expectation(&e, NoExpectation)
995 let tuple = self.tcx.mk_tup(elt_ts_iter);
996 if tuple.references_error() {
999 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1004 fn check_expr_struct(
1007 expected: Expectation<'tcx>,
1009 fields: &'tcx [hir::Field],
1010 base_expr: &'tcx Option<P<hir::Expr>>,
1012 // Find the relevant variant
1013 let (variant, adt_ty) =
1014 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1017 self.check_struct_fields_on_error(fields, base_expr);
1018 return self.tcx.types.err;
1021 let path_span = match *qpath {
1022 QPath::Resolved(_, ref path) => path.span,
1023 QPath::TypeRelative(ref qself, _) => qself.span
1026 // Prohibit struct expressions when non-exhaustive flag is set.
1027 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1028 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1029 span_err!(self.tcx.sess, expr.span, E0639,
1030 "cannot create non-exhaustive {} using struct expression",
1031 adt.variant_descr());
1034 let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1035 variant, fields, base_expr.is_none());
1036 if let &Some(ref base_expr) = base_expr {
1037 // If check_expr_struct_fields hit an error, do not attempt to populate
1038 // the fields with the base_expr. This could cause us to hit errors later
1039 // when certain fields are assumed to exist that in fact do not.
1040 if !error_happened {
1041 self.check_expr_has_type_or_error(base_expr, adt_ty);
1043 ty::Adt(adt, substs) if adt.is_struct() => {
1044 let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1045 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1050 .fru_field_types_mut()
1051 .insert(expr.hir_id, fru_field_types);
1054 span_err!(self.tcx.sess, base_expr.span, E0436,
1055 "functional record update syntax requires a struct");
1060 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1064 fn check_expr_struct_fields(
1067 expected: Expectation<'tcx>,
1068 expr_id: hir::HirId,
1070 variant: &'tcx ty::VariantDef,
1071 ast_fields: &'tcx [hir::Field],
1072 check_completeness: bool,
1077 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1078 .get(0).cloned().unwrap_or(adt_ty);
1079 // re-link the regions that EIfEO can erase.
1080 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1082 let (substs, adt_kind, kind_name) = match &adt_ty.sty {
1083 &ty::Adt(adt, substs) => {
1084 (substs, adt.adt_kind(), adt.variant_descr())
1086 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1089 let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1090 (field.ident.modern(), (i, field))
1091 ).collect::<FxHashMap<_, _>>();
1093 let mut seen_fields = FxHashMap::default();
1095 let mut error_happened = false;
1097 // Type-check each field.
1098 for field in ast_fields {
1099 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1100 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1101 seen_fields.insert(ident, field.span);
1102 self.write_field_index(field.hir_id, i);
1104 // We don't look at stability attributes on
1105 // struct-like enums (yet...), but it's definitely not
1106 // a bug to have constructed one.
1107 if adt_kind != AdtKind::Enum {
1108 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1111 self.field_ty(field.span, v_field, substs)
1113 error_happened = true;
1114 if let Some(prev_span) = seen_fields.get(&ident) {
1115 let mut err = struct_span_err!(self.tcx.sess,
1118 "field `{}` specified more than once",
1121 err.span_label(field.ident.span, "used more than once");
1122 err.span_label(*prev_span, format!("first use of `{}`", ident));
1126 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1132 // Make sure to give a type to the field even if there's
1133 // an error, so we can continue type-checking.
1134 self.check_expr_coercable_to_type(&field.expr, field_type);
1137 // Make sure the programmer specified correct number of fields.
1138 if kind_name == "union" {
1139 if ast_fields.len() != 1 {
1140 tcx.sess.span_err(span, "union expressions should have exactly one field");
1142 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1143 let len = remaining_fields.len();
1145 let mut displayable_field_names = remaining_fields
1147 .map(|ident| ident.as_str())
1148 .collect::<Vec<_>>();
1150 displayable_field_names.sort();
1152 let truncated_fields_error = if len <= 3 {
1155 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1158 let remaining_fields_names = displayable_field_names.iter().take(3)
1159 .map(|n| format!("`{}`", n))
1160 .collect::<Vec<_>>()
1163 struct_span_err!(tcx.sess, span, E0063,
1164 "missing field{} {}{} in initializer of `{}`",
1165 if remaining_fields.len() == 1 { "" } else { "s" },
1166 remaining_fields_names,
1167 truncated_fields_error,
1169 .span_label(span, format!("missing {}{}",
1170 remaining_fields_names,
1171 truncated_fields_error))
1177 fn check_struct_fields_on_error(
1179 fields: &'tcx [hir::Field],
1180 base_expr: &'tcx Option<P<hir::Expr>>,
1182 for field in fields {
1183 self.check_expr(&field.expr);
1185 if let Some(ref base) = *base_expr {
1186 self.check_expr(&base);
1190 fn report_unknown_field(
1193 variant: &'tcx ty::VariantDef,
1195 skip_fields: &[hir::Field],
1199 if variant.recovered {
1202 let mut err = self.type_error_struct_with_diag(
1204 |actual| match ty.sty {
1205 ty::Adt(adt, ..) if adt.is_enum() => {
1206 struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1207 "{} `{}::{}` has no field named `{}`",
1208 kind_name, actual, variant.ident, field.ident)
1211 struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1212 "{} `{}` has no field named `{}`",
1213 kind_name, actual, field.ident)
1217 match variant.ctor_kind {
1219 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1220 err.span_label(field.ident.span, "field does not exist");
1221 err.span_label(ty_span, format!(
1222 "`{adt}` is a tuple {kind_name}, \
1223 use the appropriate syntax: `{adt}(/* fields */)`",
1229 // prevent all specified fields from being suggested
1230 let skip_fields = skip_fields.iter().map(|ref x| x.ident.as_str());
1231 if let Some(field_name) = Self::suggest_field_name(
1233 &field.ident.as_str(),
1234 skip_fields.collect()
1236 err.span_suggestion(
1238 "a field with a similar name exists",
1239 field_name.to_string(),
1240 Applicability::MaybeIncorrect,
1244 ty::Adt(adt, ..) => {
1246 err.span_label(field.ident.span, format!(
1247 "`{}::{}` does not have this field",
1252 err.span_label(field.ident.span, format!(
1253 "`{}` does not have this field",
1257 let available_field_names = self.available_field_names(variant);
1258 if !available_field_names.is_empty() {
1259 err.note(&format!("available fields are: {}",
1260 self.name_series_display(available_field_names)));
1263 _ => bug!("non-ADT passed to report_unknown_field")
1271 // Return an hint about the closest match in field names
1272 fn suggest_field_name(variant: &'tcx ty::VariantDef,
1274 skip: Vec<LocalInternedString>)
1276 let names = variant.fields.iter().filter_map(|field| {
1277 // ignore already set fields and private fields from non-local crates
1278 if skip.iter().any(|x| *x == field.ident.as_str()) ||
1279 (!variant.def_id.is_local() && field.vis != Visibility::Public)
1283 Some(&field.ident.name)
1287 find_best_match_for_name(names, field, None)
1290 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1291 variant.fields.iter().filter(|field| {
1293 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1294 field.vis.is_accessible_from(def_scope, self.tcx)
1296 .map(|field| field.ident.name)
1300 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1301 // dynamic limit, to never omit just one field
1302 let limit = if names.len() == 6 { 6 } else { 5 };
1303 let mut display = names.iter().take(limit)
1304 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1305 if names.len() > limit {
1306 display = format!("{} ... and {} others", display, names.len() - limit);
1311 // Check field access expressions
1314 expr: &'tcx hir::Expr,
1316 base: &'tcx hir::Expr,
1319 let expr_t = self.check_expr_with_needs(base, needs);
1320 let expr_t = self.structurally_resolved_type(base.span,
1322 let mut private_candidate = None;
1323 let mut autoderef = self.autoderef(expr.span, expr_t);
1324 while let Some((base_t, _)) = autoderef.next() {
1326 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1327 debug!("struct named {:?}", base_t);
1328 let (ident, def_scope) =
1329 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1330 let fields = &base_def.non_enum_variant().fields;
1331 if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1332 let field = &fields[index];
1333 let field_ty = self.field_ty(expr.span, field, substs);
1334 // Save the index of all fields regardless of their visibility in case
1335 // of error recovery.
1336 self.write_field_index(expr.hir_id, index);
1337 if field.vis.is_accessible_from(def_scope, self.tcx) {
1338 let adjustments = autoderef.adjust_steps(self, needs);
1339 self.apply_adjustments(base, adjustments);
1340 autoderef.finalize(self);
1342 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1345 private_candidate = Some((base_def.did, field_ty));
1348 ty::Tuple(ref tys) => {
1349 let fstr = field.as_str();
1350 if let Ok(index) = fstr.parse::<usize>() {
1351 if fstr == index.to_string() {
1352 if let Some(field_ty) = tys.get(index) {
1353 let adjustments = autoderef.adjust_steps(self, needs);
1354 self.apply_adjustments(base, adjustments);
1355 autoderef.finalize(self);
1357 self.write_field_index(expr.hir_id, index);
1358 return field_ty.expect_ty();
1366 autoderef.unambiguous_final_ty(self);
1368 if let Some((did, field_ty)) = private_candidate {
1369 let struct_path = self.tcx().def_path_str(did);
1370 let mut err = struct_span_err!(self.tcx().sess, expr.span, E0616,
1371 "field `{}` of struct `{}` is private",
1372 field, struct_path);
1373 // Also check if an accessible method exists, which is often what is meant.
1374 if self.method_exists(field, expr_t, expr.hir_id, false)
1375 && !self.expr_in_place(expr.hir_id)
1377 self.suggest_method_call(
1379 &format!("a method `{}` also exists, call it with parentheses", field),
1387 } else if field.name == kw::Invalid {
1388 self.tcx().types.err
1389 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1390 let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
1391 "attempted to take value of method `{}` on type `{}`",
1394 if !self.expr_in_place(expr.hir_id) {
1395 self.suggest_method_call(
1397 "use parentheses to call the method",
1403 err.help("methods are immutable and cannot be assigned to");
1407 self.tcx().types.err
1409 if !expr_t.is_primitive_ty() {
1410 let mut err = self.no_such_field_err(field.span, field, expr_t);
1413 ty::Adt(def, _) if !def.is_enum() => {
1414 if let Some(suggested_field_name) =
1415 Self::suggest_field_name(def.non_enum_variant(),
1416 &field.as_str(), vec![]) {
1417 err.span_suggestion(
1419 "a field with a similar name exists",
1420 suggested_field_name.to_string(),
1421 Applicability::MaybeIncorrect,
1424 err.span_label(field.span, "unknown field");
1425 let struct_variant_def = def.non_enum_variant();
1426 let field_names = self.available_field_names(struct_variant_def);
1427 if !field_names.is_empty() {
1428 err.note(&format!("available fields are: {}",
1429 self.name_series_display(field_names)));
1433 ty::Array(_, len) => {
1434 if let (Some(len), Ok(user_index)) = (
1435 len.assert_usize(self.tcx),
1436 field.as_str().parse::<u64>()
1438 let base = self.tcx.sess.source_map()
1439 .span_to_snippet(base.span)
1441 self.tcx.hir().hir_to_pretty_string(base.hir_id));
1442 let help = "instead of using tuple indexing, use array indexing";
1443 let suggestion = format!("{}[{}]", base, field);
1444 let applicability = if len < user_index {
1445 Applicability::MachineApplicable
1447 Applicability::MaybeIncorrect
1449 err.span_suggestion(
1450 expr.span, help, suggestion, applicability
1455 let base = self.tcx.sess.source_map()
1456 .span_to_snippet(base.span)
1457 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1458 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1459 let suggestion = format!("(*{}).{}", base, field);
1460 err.span_suggestion(
1464 Applicability::MaybeIncorrect,
1471 type_error_struct!(self.tcx().sess, field.span, expr_t, E0610,
1472 "`{}` is a primitive type and therefore doesn't have fields",
1475 self.tcx().types.err
1479 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1480 -> DiagnosticBuilder<'_> {
1481 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1482 "no field `{}` on type `{}`",
1486 fn check_expr_index(
1488 base: &'tcx hir::Expr,
1489 idx: &'tcx hir::Expr,
1491 expr: &'tcx hir::Expr,
1493 let base_t = self.check_expr_with_needs(&base, needs);
1494 let idx_t = self.check_expr(&idx);
1496 if base_t.references_error() {
1498 } else if idx_t.references_error() {
1501 let base_t = self.structurally_resolved_type(base.span, base_t);
1502 match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1503 Some((index_ty, element_ty)) => {
1504 // two-phase not needed because index_ty is never mutable
1505 self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1510 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1511 "cannot index into a value of type `{}`",
1513 // Try to give some advice about indexing tuples.
1514 if let ty::Tuple(..) = base_t.sty {
1515 let mut needs_note = true;
1516 // If the index is an integer, we can show the actual
1517 // fixed expression:
1518 if let ExprKind::Lit(ref lit) = idx.node {
1519 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1520 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1521 if let Ok(snip) = snip {
1522 err.span_suggestion(
1524 "to access tuple elements, use",
1525 format!("{}.{}", snip, i),
1526 Applicability::MachineApplicable,
1533 err.help("to access tuple elements, use tuple indexing \
1534 syntax (e.g., `tuple.0`)");
1544 fn check_expr_yield(&self, value: &'tcx hir::Expr, expr: &'tcx hir::Expr) -> Ty<'tcx> {
1545 match self.yield_ty {
1547 self.check_expr_coercable_to_type(&value, ty);
1550 struct_span_err!(self.tcx.sess, expr.span, E0627,
1551 "yield statement outside of generator literal").emit();