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::util::common::ErrorReported;
17 use crate::util::nodemap::FxHashMap;
18 use crate::astconv::AstConv as _;
20 use errors::{Applicability, DiagnosticBuilder};
22 use syntax::symbol::{Symbol, LocalInternedString, kw, sym};
23 use syntax::source_map::Span;
24 use syntax::util::lev_distance::find_best_match_for_name;
26 use rustc::hir::{ExprKind, QPath};
27 use rustc::hir::def::{CtorKind, Res, DefKind};
28 use rustc::hir::ptr::P;
30 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
31 use rustc::mir::interpret::GlobalId;
33 use rustc::ty::adjustment::{
34 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
36 use rustc::ty::{AdtKind, Visibility};
38 use rustc::ty::TypeFoldable;
39 use rustc::ty::subst::InternalSubsts;
40 use rustc::traits::{self, ObligationCauseCode};
42 use std::fmt::Display;
44 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
45 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
46 let ty = self.check_expr_with_hint(expr, expected);
47 self.demand_eqtype(expr.span, expected, ty);
50 pub fn check_expr_has_type_or_error(
52 expr: &'tcx hir::Expr,
55 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected))
58 fn check_expr_meets_expectation_or_error(
60 expr: &'tcx hir::Expr,
61 expected: Expectation<'tcx>,
63 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
64 let mut ty = self.check_expr_with_expectation(expr, expected);
66 // While we don't allow *arbitrary* coercions here, we *do* allow
67 // coercions from ! to `expected`.
69 assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
70 "expression with never type wound up being adjusted");
71 let adj_ty = self.next_diverging_ty_var(
73 kind: TypeVariableOriginKind::AdjustmentType,
77 self.apply_adjustments(expr, vec![Adjustment {
78 kind: Adjust::NeverToAny,
84 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
85 let expr = match &expr.node {
86 ExprKind::DropTemps(expr) => expr,
89 // Error possibly reported in `check_assign` so avoid emitting error again.
90 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
95 pub(super) fn check_expr_coercable_to_type(
97 expr: &'tcx hir::Expr,
100 let ty = self.check_expr_with_hint(expr, expected);
101 // checks don't need two phase
102 self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
105 pub(super) fn check_expr_with_hint(
107 expr: &'tcx hir::Expr,
110 self.check_expr_with_expectation(expr, ExpectHasType(expected))
113 pub(super) fn check_expr_with_expectation(
115 expr: &'tcx hir::Expr,
116 expected: Expectation<'tcx>,
118 self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
121 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
122 self.check_expr_with_expectation(expr, NoExpectation)
125 pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
126 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
130 /// If an expression has any sub-expressions that result in a type error,
131 /// inspecting that expression's type with `ty.references_error()` will return
132 /// true. Likewise, if an expression is known to diverge, inspecting its
133 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
134 /// strict, _|_ can appear in the type of an expression that does not,
135 /// itself, diverge: for example, fn() -> _|_.)
136 /// Note that inspecting a type's structure *directly* may expose the fact
137 /// that there are actually multiple representations for `Error`, so avoid
138 /// that when err needs to be handled differently.
139 fn check_expr_with_expectation_and_needs(
141 expr: &'tcx hir::Expr,
142 expected: Expectation<'tcx>,
145 debug!(">> type-checking: expr={:?} expected={:?}",
148 // Warn for expressions after diverging siblings.
149 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
151 // Hide the outer diverging and has_errors flags.
152 let old_diverges = self.diverges.get();
153 let old_has_errors = self.has_errors.get();
154 self.diverges.set(Diverges::Maybe);
155 self.has_errors.set(false);
157 let ty = self.check_expr_kind(expr, expected, needs);
159 // Warn for non-block expressions with diverging children.
161 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {},
162 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
165 // Any expression that produces a value of type `!` must have diverged
167 self.diverges.set(self.diverges.get() | Diverges::Always);
170 // Record the type, which applies it effects.
171 // We need to do this after the warning above, so that
172 // we don't warn for the diverging expression itself.
173 self.write_ty(expr.hir_id, ty);
175 // Combine the diverging and has_error flags.
176 self.diverges.set(self.diverges.get() | old_diverges);
177 self.has_errors.set(self.has_errors.get() | old_has_errors);
179 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
180 debug!("... {:?}, expected is {:?}", ty, expected);
187 expr: &'tcx hir::Expr,
188 expected: Expectation<'tcx>,
192 "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
200 ExprKind::Box(ref subexpr) => {
201 self.check_expr_box(subexpr, expected)
203 ExprKind::Lit(ref lit) => {
204 self.check_lit(&lit, expected)
206 ExprKind::Binary(op, ref lhs, ref rhs) => {
207 self.check_binop(expr, op, lhs, rhs)
209 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
210 self.check_binop_assign(expr, op, lhs, rhs)
212 ExprKind::Unary(unop, ref oprnd) => {
213 self.check_expr_unary(unop, oprnd, expected, needs, expr)
215 ExprKind::AddrOf(mutbl, ref oprnd) => {
216 self.check_expr_addr_of(mutbl, oprnd, expected, expr)
218 ExprKind::Path(ref qpath) => {
219 self.check_expr_path(qpath, expr)
221 ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
222 for expr in outputs.iter().chain(inputs.iter()) {
223 self.check_expr(expr);
227 ExprKind::Break(destination, ref expr_opt) => {
228 self.check_expr_break(destination, expr_opt.as_deref(), expr)
230 ExprKind::Continue(destination) => {
231 if destination.target_id.is_ok() {
234 // There was an error; make type-check fail.
238 ExprKind::Ret(ref expr_opt) => {
239 self.check_expr_return(expr_opt.as_deref(), expr)
241 ExprKind::Assign(ref lhs, ref rhs) => {
242 self.check_expr_assign(expr, expected, lhs, rhs)
244 ExprKind::Loop(ref body, _, source) => {
245 self.check_expr_loop(body, source, expected, expr)
247 ExprKind::Match(ref discrim, ref arms, match_src) => {
248 self.check_match(expr, &discrim, arms, expected, match_src)
250 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
251 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
253 ExprKind::Block(ref body, _) => {
254 self.check_block_with_expected(&body, expected)
256 ExprKind::Call(ref callee, ref args) => {
257 self.check_call(expr, &callee, args, expected)
259 ExprKind::MethodCall(ref segment, span, ref args) => {
260 self.check_method_call(expr, segment, span, args, expected, needs)
262 ExprKind::Cast(ref e, ref t) => {
263 self.check_expr_cast(e, t, expr)
265 ExprKind::Type(ref e, ref t) => {
266 let ty = self.to_ty_saving_user_provided_ty(&t);
267 self.check_expr_eq_type(&e, ty);
270 ExprKind::DropTemps(ref e) => {
271 self.check_expr_with_expectation(e, expected)
273 ExprKind::Array(ref args) => {
274 self.check_expr_array(args, expected, expr)
276 ExprKind::Repeat(ref element, ref count) => {
277 self.check_expr_repeat(element, count, expected, expr)
279 ExprKind::Tup(ref elts) => {
280 self.check_expr_tuple(elts, expected, expr)
282 ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
283 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
285 ExprKind::Field(ref base, field) => {
286 self.check_field(expr, needs, &base, field)
288 ExprKind::Index(ref base, ref idx) => {
289 self.check_expr_index(base, idx, needs, expr)
291 ExprKind::Yield(ref value, ref src) => {
292 self.check_expr_yield(value, expr, src)
294 hir::ExprKind::Err => {
300 fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
301 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
303 ty::Adt(def, _) if def.is_box()
304 => Expectation::rvalue_hint(self, ty.boxed_ty()),
308 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
309 self.tcx.mk_box(referent_ty)
315 oprnd: &'tcx hir::Expr,
316 expected: Expectation<'tcx>,
318 expr: &'tcx hir::Expr,
321 let expected_inner = match unop {
322 hir::UnNot | hir::UnNeg => expected,
323 hir::UnDeref => NoExpectation,
325 let needs = match unop {
326 hir::UnDeref => needs,
329 let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
331 if !oprnd_t.references_error() {
332 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
335 if let Some(mt) = oprnd_t.builtin_deref(true) {
337 } else if let Some(ok) = self.try_overloaded_deref(
338 expr.span, oprnd_t, needs) {
339 let method = self.register_infer_ok_obligations(ok);
340 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].sty {
341 let mutbl = match mutbl {
342 hir::MutImmutable => AutoBorrowMutability::Immutable,
343 hir::MutMutable => AutoBorrowMutability::Mutable {
344 // (It shouldn't actually matter for unary ops whether
345 // we enable two-phase borrows or not, since a unary
346 // op has no additional operands.)
347 allow_two_phase_borrow: AllowTwoPhase::No,
350 self.apply_adjustments(oprnd, vec![Adjustment {
351 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
352 target: method.sig.inputs()[0]
355 oprnd_t = self.make_overloaded_place_return_type(method).ty;
356 self.write_method_call(expr.hir_id, method);
358 let mut err = type_error_struct!(
363 "type `{}` cannot be dereferenced",
366 let sp = tcx.sess.source_map().start_point(expr.span);
367 if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
370 tcx.sess.parse_sess.expr_parentheses_needed(
377 oprnd_t = tcx.types.err;
381 let result = self.check_user_unop(expr, oprnd_t, unop);
382 // If it's builtin, we can reuse the type, this helps inference.
383 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::Bool) {
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_numeric() {
399 fn check_expr_addr_of(
401 mutbl: hir::Mutability,
402 oprnd: &'tcx hir::Expr,
403 expected: Expectation<'tcx>,
404 expr: &'tcx hir::Expr,
406 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
408 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
409 if oprnd.is_place_expr() {
410 // Places may legitimately have unsized types.
411 // For example, dereferences of a fat pointer and
412 // the last field of a struct can be unsized.
415 Expectation::rvalue_hint(self, ty)
421 let needs = Needs::maybe_mut_place(mutbl);
422 let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
424 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
425 if tm.ty.references_error() {
428 // Note: at this point, we cannot say what the best lifetime
429 // is to use for resulting pointer. We want to use the
430 // shortest lifetime possible so as to avoid spurious borrowck
431 // errors. Moreover, the longest lifetime will depend on the
432 // precise details of the value whose address is being taken
433 // (and how long it is valid), which we don't know yet until type
434 // inference is complete.
436 // Therefore, here we simply generate a region variable. The
437 // region inferencer will then select the ultimate value.
438 // Finally, borrowck is charged with guaranteeing that the
439 // value whose address was taken can actually be made to live
440 // as long as it needs to live.
441 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
442 self.tcx.mk_ref(region, tm)
446 fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
448 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
451 self.set_tainted_by_errors();
454 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
455 report_unexpected_variant_res(tcx, res, expr.span, qpath);
458 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
461 if let ty::FnDef(..) = ty.sty {
462 let fn_sig = ty.fn_sig(tcx);
463 if !tcx.features().unsized_locals {
464 // We want to remove some Sized bounds from std functions,
465 // but don't want to expose the removal to stable Rust.
466 // i.e., we don't want to allow
472 // to work in stable even if the Sized bound on `drop` is relaxed.
473 for i in 0..fn_sig.inputs().skip_binder().len() {
474 // We just want to check sizedness, so instead of introducing
475 // placeholder lifetimes with probing, we just replace higher lifetimes
477 let input = self.replace_bound_vars_with_fresh_vars(
479 infer::LateBoundRegionConversionTime::FnCall,
481 self.require_type_is_sized_deferred(input, expr.span,
482 traits::SizedArgumentType);
485 // Here we want to prevent struct constructors from returning unsized types.
486 // There were two cases this happened: fn pointer coercion in stable
487 // and usual function call in presense of unsized_locals.
488 // Also, as we just want to check sizedness, instead of introducing
489 // placeholder lifetimes with probing, we just replace higher lifetimes
491 let output = self.replace_bound_vars_with_fresh_vars(
493 infer::LateBoundRegionConversionTime::FnCall,
495 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
498 // We always require that the type provided as the value for
499 // a type parameter outlives the moment of instantiation.
500 let substs = self.tables.borrow().node_substs(expr.hir_id);
501 self.add_wf_bounds(substs, expr);
508 destination: hir::Destination,
509 expr_opt: Option<&'tcx hir::Expr>,
510 expr: &'tcx hir::Expr,
513 if let Ok(target_id) = destination.target_id {
515 if let Some(ref e) = expr_opt {
516 // If this is a break with a value, we need to type-check
517 // the expression. Get an expected type from the loop context.
518 let opt_coerce_to = {
519 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
520 enclosing_breakables.find_breakable(target_id)
523 .map(|coerce| coerce.expected_ty())
526 // If the loop context is not a `loop { }`, then break with
527 // a value is illegal, and `opt_coerce_to` will be `None`.
528 // Just set expectation to error in that case.
529 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
531 // Recurse without `enclosing_breakables` borrowed.
532 e_ty = self.check_expr_with_hint(e, coerce_to);
533 cause = self.misc(e.span);
535 // Otherwise, this is a break *without* a value. That's
536 // always legal, and is equivalent to `break ()`.
537 e_ty = tcx.mk_unit();
538 cause = self.misc(expr.span);
541 // Now that we have type-checked `expr_opt`, borrow
542 // the `enclosing_loops` field and let's coerce the
543 // type of `expr_opt` into what is expected.
544 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
545 let ctxt = enclosing_breakables.find_breakable(target_id);
546 if let Some(ref mut coerce) = ctxt.coerce {
547 if let Some(ref e) = expr_opt {
548 coerce.coerce(self, &cause, e, e_ty);
550 assert!(e_ty.is_unit());
551 coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
554 // If `ctxt.coerce` is `None`, we can just ignore
555 // the type of the expresison. This is because
556 // either this was a break *without* a value, in
557 // which case it is always a legal type (`()`), or
558 // else an error would have been flagged by the
559 // `loops` pass for using break with an expression
560 // where you are not supposed to.
561 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
564 ctxt.may_break = true;
566 // the type of a `break` is always `!`, since it diverges
569 // Otherwise, we failed to find the enclosing loop;
570 // this can only happen if the `break` was not
571 // inside a loop at all, which is caught by the
572 // loop-checking pass.
573 self.tcx.sess.delay_span_bug(expr.span,
574 "break was outside loop, but no error was emitted");
576 // We still need to assign a type to the inner expression to
577 // prevent the ICE in #43162.
578 if let Some(ref e) = expr_opt {
579 self.check_expr_with_hint(e, tcx.types.err);
581 // ... except when we try to 'break rust;'.
582 // ICE this expression in particular (see #43162).
583 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node {
584 if path.segments.len() == 1 &&
585 path.segments[0].ident.name == sym::rust {
586 fatally_break_rust(self.tcx.sess);
590 // There was an error; make type-check fail.
595 fn check_expr_return(
597 expr_opt: Option<&'tcx hir::Expr>,
598 expr: &'tcx hir::Expr
600 if self.ret_coercion.is_none() {
601 struct_span_err!(self.tcx.sess, expr.span, E0572,
602 "return statement outside of function body").emit();
603 } else if let Some(ref e) = expr_opt {
604 if self.ret_coercion_span.borrow().is_none() {
605 *self.ret_coercion_span.borrow_mut() = Some(e.span);
607 self.check_return_expr(e);
609 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
610 if self.ret_coercion_span.borrow().is_none() {
611 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
613 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
614 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
615 coercion.coerce_forced_unit(
620 fn_decl.output.span(),
622 "expected `{}` because of this return type",
630 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
636 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
640 .unwrap_or_else(|| span_bug!(return_expr.span,
641 "check_return_expr called outside fn body"));
643 let ret_ty = ret_coercion.borrow().expected_ty();
644 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
645 ret_coercion.borrow_mut()
647 &self.cause(return_expr.span,
648 ObligationCauseCode::ReturnType(return_expr.hir_id)),
653 /// Type check assignment expression `expr` of form `lhs = rhs`.
654 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
655 fn check_expr_assign(
657 expr: &'tcx hir::Expr,
658 expected: Expectation<'tcx>,
659 lhs: &'tcx hir::Expr,
660 rhs: &'tcx hir::Expr,
662 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
663 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
665 let expected_ty = expected.coercion_target_type(self, expr.span);
666 if expected_ty == self.tcx.types.bool {
667 // The expected type is `bool` but this will result in `()` so we can reasonably
668 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
669 // The likely cause of this is `if foo = bar { .. }`.
670 let actual_ty = self.tcx.mk_unit();
671 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
672 let msg = "try comparing for equality";
673 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
674 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
675 if let (Ok(left), Ok(right)) = (left, right) {
676 let help = format!("{} == {}", left, right);
677 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
682 } else if !lhs.is_place_expr() {
683 struct_span_err!(self.tcx.sess, expr.span, E0070,
684 "invalid left-hand side expression")
685 .span_label(expr.span, "left-hand of expression not valid")
689 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
691 if lhs_ty.references_error() || rhs_ty.references_error() {
700 body: &'tcx hir::Block,
701 source: hir::LoopSource,
702 expected: Expectation<'tcx>,
703 expr: &'tcx hir::Expr,
705 let coerce = match source {
706 // you can only use break with a value from a normal `loop { }`
707 hir::LoopSource::Loop => {
708 let coerce_to = expected.coercion_target_type(self, body.span);
709 Some(CoerceMany::new(coerce_to))
712 hir::LoopSource::While |
713 hir::LoopSource::WhileLet |
714 hir::LoopSource::ForLoop => {
719 let ctxt = BreakableCtxt {
721 may_break: false, // Will get updated if/when we find a `break`.
724 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
725 self.check_block_no_value(&body);
729 // No way to know whether it's diverging because
730 // of a `break` or an outer `break` or `return`.
731 self.diverges.set(Diverges::Maybe);
734 // If we permit break with a value, then result type is
735 // the LUB of the breaks (possibly ! if none); else, it
736 // is nil. This makes sense because infinite loops
737 // (which would have type !) are only possible iff we
738 // permit break with a value [1].
739 if ctxt.coerce.is_none() && !ctxt.may_break {
741 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
743 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
746 /// Checks a method call.
747 fn check_method_call(
749 expr: &'tcx hir::Expr,
750 segment: &hir::PathSegment,
752 args: &'tcx [hir::Expr],
753 expected: Expectation<'tcx>,
757 let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
758 // no need to check for bot/err -- callee does that
759 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
761 let method = match self.lookup_method(rcvr_t,
767 self.write_method_call(expr.hir_id, method);
771 if segment.ident.name != kw::Invalid {
772 self.report_method_error(span,
775 SelfSource::MethodCall(rcvr),
783 // Call the generic checker.
784 self.check_method_argument_types(span,
796 expr: &'tcx hir::Expr,
798 // Find the type of `e`. Supply hints based on the type we are casting to,
800 let t_cast = self.to_ty_saving_user_provided_ty(t);
801 let t_cast = self.resolve_vars_if_possible(&t_cast);
802 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
803 let t_cast = self.resolve_vars_if_possible(&t_cast);
805 // Eagerly check for some obvious errors.
806 if t_expr.references_error() || t_cast.references_error() {
809 // Defer other checks until we're done type checking.
810 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
811 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
813 deferred_cast_checks.push(cast_check);
816 Err(ErrorReported) => {
825 args: &'tcx [hir::Expr],
826 expected: Expectation<'tcx>,
827 expr: &'tcx hir::Expr
829 let uty = expected.to_option(self).and_then(|uty| {
831 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
836 let element_ty = if !args.is_empty() {
837 let coerce_to = uty.unwrap_or_else(|| {
838 self.next_ty_var(TypeVariableOrigin {
839 kind: TypeVariableOriginKind::TypeInference,
843 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
844 assert_eq!(self.diverges.get(), Diverges::Maybe);
846 let e_ty = self.check_expr_with_hint(e, coerce_to);
847 let cause = self.misc(e.span);
848 coerce.coerce(self, &cause, e, e_ty);
850 coerce.complete(self)
852 self.next_ty_var(TypeVariableOrigin {
853 kind: TypeVariableOriginKind::TypeInference,
857 self.tcx.mk_array(element_ty, args.len() as u64)
860 fn check_expr_repeat(
862 element: &'tcx hir::Expr,
863 count: &'tcx hir::AnonConst,
864 expected: Expectation<'tcx>,
865 _expr: &'tcx hir::Expr,
868 let count_def_id = tcx.hir().local_def_id(count.hir_id);
869 let count = if self.const_param_def_id(count).is_some() {
870 Ok(self.to_const(count, tcx.type_of(count_def_id)))
872 let param_env = ty::ParamEnv::empty();
873 let substs = InternalSubsts::identity_for_item(tcx.global_tcx(), count_def_id);
874 let instance = ty::Instance::resolve(
880 let global_id = GlobalId {
885 tcx.const_eval(param_env.and(global_id))
888 let uty = match expected {
889 ExpectHasType(uty) => {
891 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
898 let (element_ty, t) = match uty {
900 self.check_expr_coercable_to_type(&element, uty);
904 let ty = self.next_ty_var(TypeVariableOrigin {
905 kind: TypeVariableOriginKind::MiscVariable,
908 let element_ty = self.check_expr_has_type_or_error(&element, ty);
913 if element_ty.references_error() {
915 } else if let Ok(count) = count {
916 tcx.mk_ty(ty::Array(t, count))
924 elts: &'tcx [hir::Expr],
925 expected: Expectation<'tcx>,
926 expr: &'tcx hir::Expr,
928 let flds = expected.only_has_type(self).and_then(|ty| {
929 let ty = self.resolve_type_vars_with_obligations(ty);
931 ty::Tuple(ref flds) => Some(&flds[..]),
936 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
938 Some(ref fs) if i < fs.len() => {
939 let ety = fs[i].expect_ty();
940 self.check_expr_coercable_to_type(&e, ety);
944 self.check_expr_with_expectation(&e, NoExpectation)
949 let tuple = self.tcx.mk_tup(elt_ts_iter);
950 if tuple.references_error() {
953 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
958 fn check_expr_struct(
961 expected: Expectation<'tcx>,
963 fields: &'tcx [hir::Field],
964 base_expr: &'tcx Option<P<hir::Expr>>,
966 // Find the relevant variant
967 let (variant, adt_ty) =
968 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
971 self.check_struct_fields_on_error(fields, base_expr);
972 return self.tcx.types.err;
975 let path_span = match *qpath {
976 QPath::Resolved(_, ref path) => path.span,
977 QPath::TypeRelative(ref qself, _) => qself.span
980 // Prohibit struct expressions when non-exhaustive flag is set.
981 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
982 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
983 span_err!(self.tcx.sess, expr.span, E0639,
984 "cannot create non-exhaustive {} using struct expression",
985 adt.variant_descr());
988 let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
989 variant, fields, base_expr.is_none());
990 if let &Some(ref base_expr) = base_expr {
991 // If check_expr_struct_fields hit an error, do not attempt to populate
992 // the fields with the base_expr. This could cause us to hit errors later
993 // when certain fields are assumed to exist that in fact do not.
995 self.check_expr_has_type_or_error(base_expr, adt_ty);
997 ty::Adt(adt, substs) if adt.is_struct() => {
998 let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
999 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1004 .fru_field_types_mut()
1005 .insert(expr.hir_id, fru_field_types);
1008 span_err!(self.tcx.sess, base_expr.span, E0436,
1009 "functional record update syntax requires a struct");
1014 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1018 fn check_expr_struct_fields(
1021 expected: Expectation<'tcx>,
1022 expr_id: hir::HirId,
1024 variant: &'tcx ty::VariantDef,
1025 ast_fields: &'tcx [hir::Field],
1026 check_completeness: bool,
1031 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1032 .get(0).cloned().unwrap_or(adt_ty);
1033 // re-link the regions that EIfEO can erase.
1034 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1036 let (substs, adt_kind, kind_name) = match &adt_ty.sty {
1037 &ty::Adt(adt, substs) => {
1038 (substs, adt.adt_kind(), adt.variant_descr())
1040 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1043 let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1044 (field.ident.modern(), (i, field))
1045 ).collect::<FxHashMap<_, _>>();
1047 let mut seen_fields = FxHashMap::default();
1049 let mut error_happened = false;
1051 // Type-check each field.
1052 for field in ast_fields {
1053 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1054 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1055 seen_fields.insert(ident, field.span);
1056 self.write_field_index(field.hir_id, i);
1058 // We don't look at stability attributes on
1059 // struct-like enums (yet...), but it's definitely not
1060 // a bug to have constructed one.
1061 if adt_kind != AdtKind::Enum {
1062 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1065 self.field_ty(field.span, v_field, substs)
1067 error_happened = true;
1068 if let Some(prev_span) = seen_fields.get(&ident) {
1069 let mut err = struct_span_err!(self.tcx.sess,
1072 "field `{}` specified more than once",
1075 err.span_label(field.ident.span, "used more than once");
1076 err.span_label(*prev_span, format!("first use of `{}`", ident));
1080 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1086 // Make sure to give a type to the field even if there's
1087 // an error, so we can continue type-checking.
1088 self.check_expr_coercable_to_type(&field.expr, field_type);
1091 // Make sure the programmer specified correct number of fields.
1092 if kind_name == "union" {
1093 if ast_fields.len() != 1 {
1094 tcx.sess.span_err(span, "union expressions should have exactly one field");
1096 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1097 let len = remaining_fields.len();
1099 let mut displayable_field_names = remaining_fields
1101 .map(|ident| ident.as_str())
1102 .collect::<Vec<_>>();
1104 displayable_field_names.sort();
1106 let truncated_fields_error = if len <= 3 {
1109 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1112 let remaining_fields_names = displayable_field_names.iter().take(3)
1113 .map(|n| format!("`{}`", n))
1114 .collect::<Vec<_>>()
1117 struct_span_err!(tcx.sess, span, E0063,
1118 "missing field{} {}{} in initializer of `{}`",
1119 if remaining_fields.len() == 1 { "" } else { "s" },
1120 remaining_fields_names,
1121 truncated_fields_error,
1123 .span_label(span, format!("missing {}{}",
1124 remaining_fields_names,
1125 truncated_fields_error))
1131 fn check_struct_fields_on_error(
1133 fields: &'tcx [hir::Field],
1134 base_expr: &'tcx Option<P<hir::Expr>>,
1136 for field in fields {
1137 self.check_expr(&field.expr);
1139 if let Some(ref base) = *base_expr {
1140 self.check_expr(&base);
1144 fn report_unknown_field(
1147 variant: &'tcx ty::VariantDef,
1149 skip_fields: &[hir::Field],
1153 if variant.recovered {
1156 let mut err = self.type_error_struct_with_diag(
1158 |actual| match ty.sty {
1159 ty::Adt(adt, ..) if adt.is_enum() => {
1160 struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1161 "{} `{}::{}` has no field named `{}`",
1162 kind_name, actual, variant.ident, field.ident)
1165 struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1166 "{} `{}` has no field named `{}`",
1167 kind_name, actual, field.ident)
1171 match variant.ctor_kind {
1173 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1174 err.span_label(field.ident.span, "field does not exist");
1175 err.span_label(ty_span, format!(
1176 "`{adt}` is a tuple {kind_name}, \
1177 use the appropriate syntax: `{adt}(/* fields */)`",
1183 // prevent all specified fields from being suggested
1184 let skip_fields = skip_fields.iter().map(|ref x| x.ident.as_str());
1185 if let Some(field_name) = Self::suggest_field_name(
1187 &field.ident.as_str(),
1188 skip_fields.collect()
1190 err.span_suggestion(
1192 "a field with a similar name exists",
1193 field_name.to_string(),
1194 Applicability::MaybeIncorrect,
1198 ty::Adt(adt, ..) => {
1200 err.span_label(field.ident.span, format!(
1201 "`{}::{}` does not have this field",
1206 err.span_label(field.ident.span, format!(
1207 "`{}` does not have this field",
1211 let available_field_names = self.available_field_names(variant);
1212 if !available_field_names.is_empty() {
1213 err.note(&format!("available fields are: {}",
1214 self.name_series_display(available_field_names)));
1217 _ => bug!("non-ADT passed to report_unknown_field")
1225 // Return an hint about the closest match in field names
1226 fn suggest_field_name(variant: &'tcx ty::VariantDef,
1228 skip: Vec<LocalInternedString>)
1230 let names = variant.fields.iter().filter_map(|field| {
1231 // ignore already set fields and private fields from non-local crates
1232 if skip.iter().any(|x| *x == field.ident.as_str()) ||
1233 (!variant.def_id.is_local() && field.vis != Visibility::Public)
1237 Some(&field.ident.name)
1241 find_best_match_for_name(names, field, None)
1244 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1245 variant.fields.iter().filter(|field| {
1247 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1248 field.vis.is_accessible_from(def_scope, self.tcx)
1250 .map(|field| field.ident.name)
1254 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1255 // dynamic limit, to never omit just one field
1256 let limit = if names.len() == 6 { 6 } else { 5 };
1257 let mut display = names.iter().take(limit)
1258 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1259 if names.len() > limit {
1260 display = format!("{} ... and {} others", display, names.len() - limit);
1265 // Check field access expressions
1268 expr: &'tcx hir::Expr,
1270 base: &'tcx hir::Expr,
1273 let expr_t = self.check_expr_with_needs(base, needs);
1274 let expr_t = self.structurally_resolved_type(base.span,
1276 let mut private_candidate = None;
1277 let mut autoderef = self.autoderef(expr.span, expr_t);
1278 while let Some((base_t, _)) = autoderef.next() {
1280 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1281 debug!("struct named {:?}", base_t);
1282 let (ident, def_scope) =
1283 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1284 let fields = &base_def.non_enum_variant().fields;
1285 if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1286 let field = &fields[index];
1287 let field_ty = self.field_ty(expr.span, field, substs);
1288 // Save the index of all fields regardless of their visibility in case
1289 // of error recovery.
1290 self.write_field_index(expr.hir_id, index);
1291 if field.vis.is_accessible_from(def_scope, self.tcx) {
1292 let adjustments = autoderef.adjust_steps(self, needs);
1293 self.apply_adjustments(base, adjustments);
1294 autoderef.finalize(self);
1296 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1299 private_candidate = Some((base_def.did, field_ty));
1302 ty::Tuple(ref tys) => {
1303 let fstr = field.as_str();
1304 if let Ok(index) = fstr.parse::<usize>() {
1305 if fstr == index.to_string() {
1306 if let Some(field_ty) = tys.get(index) {
1307 let adjustments = autoderef.adjust_steps(self, needs);
1308 self.apply_adjustments(base, adjustments);
1309 autoderef.finalize(self);
1311 self.write_field_index(expr.hir_id, index);
1312 return field_ty.expect_ty();
1320 autoderef.unambiguous_final_ty(self);
1322 if let Some((did, field_ty)) = private_candidate {
1323 let struct_path = self.tcx().def_path_str(did);
1324 let mut err = struct_span_err!(self.tcx().sess, expr.span, E0616,
1325 "field `{}` of struct `{}` is private",
1326 field, struct_path);
1327 // Also check if an accessible method exists, which is often what is meant.
1328 if self.method_exists(field, expr_t, expr.hir_id, false)
1329 && !self.expr_in_place(expr.hir_id)
1331 self.suggest_method_call(
1333 &format!("a method `{}` also exists, call it with parentheses", field),
1341 } else if field.name == kw::Invalid {
1342 self.tcx().types.err
1343 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1344 let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
1345 "attempted to take value of method `{}` on type `{}`",
1348 if !self.expr_in_place(expr.hir_id) {
1349 self.suggest_method_call(
1351 "use parentheses to call the method",
1357 err.help("methods are immutable and cannot be assigned to");
1361 self.tcx().types.err
1363 if !expr_t.is_primitive_ty() {
1364 let mut err = self.no_such_field_err(field.span, field, expr_t);
1367 ty::Adt(def, _) if !def.is_enum() => {
1368 if let Some(suggested_field_name) =
1369 Self::suggest_field_name(def.non_enum_variant(),
1370 &field.as_str(), vec![]) {
1371 err.span_suggestion(
1373 "a field with a similar name exists",
1374 suggested_field_name.to_string(),
1375 Applicability::MaybeIncorrect,
1378 err.span_label(field.span, "unknown field");
1379 let struct_variant_def = def.non_enum_variant();
1380 let field_names = self.available_field_names(struct_variant_def);
1381 if !field_names.is_empty() {
1382 err.note(&format!("available fields are: {}",
1383 self.name_series_display(field_names)));
1387 ty::Array(_, len) => {
1388 if let (Some(len), Ok(user_index)) = (
1389 len.assert_usize(self.tcx),
1390 field.as_str().parse::<u64>()
1392 let base = self.tcx.sess.source_map()
1393 .span_to_snippet(base.span)
1395 self.tcx.hir().hir_to_pretty_string(base.hir_id));
1396 let help = "instead of using tuple indexing, use array indexing";
1397 let suggestion = format!("{}[{}]", base, field);
1398 let applicability = if len < user_index {
1399 Applicability::MachineApplicable
1401 Applicability::MaybeIncorrect
1403 err.span_suggestion(
1404 expr.span, help, suggestion, applicability
1409 let base = self.tcx.sess.source_map()
1410 .span_to_snippet(base.span)
1411 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1412 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1413 let suggestion = format!("(*{}).{}", base, field);
1414 err.span_suggestion(
1418 Applicability::MaybeIncorrect,
1425 type_error_struct!(self.tcx().sess, field.span, expr_t, E0610,
1426 "`{}` is a primitive type and therefore doesn't have fields",
1429 self.tcx().types.err
1433 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1434 -> DiagnosticBuilder<'_> {
1435 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1436 "no field `{}` on type `{}`",
1440 fn check_expr_index(
1442 base: &'tcx hir::Expr,
1443 idx: &'tcx hir::Expr,
1445 expr: &'tcx hir::Expr,
1447 let base_t = self.check_expr_with_needs(&base, needs);
1448 let idx_t = self.check_expr(&idx);
1450 if base_t.references_error() {
1452 } else if idx_t.references_error() {
1455 let base_t = self.structurally_resolved_type(base.span, base_t);
1456 match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1457 Some((index_ty, element_ty)) => {
1458 // two-phase not needed because index_ty is never mutable
1459 self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1464 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1465 "cannot index into a value of type `{}`",
1467 // Try to give some advice about indexing tuples.
1468 if let ty::Tuple(..) = base_t.sty {
1469 let mut needs_note = true;
1470 // If the index is an integer, we can show the actual
1471 // fixed expression:
1472 if let ExprKind::Lit(ref lit) = idx.node {
1473 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1474 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1475 if let Ok(snip) = snip {
1476 err.span_suggestion(
1478 "to access tuple elements, use",
1479 format!("{}.{}", snip, i),
1480 Applicability::MachineApplicable,
1487 err.help("to access tuple elements, use tuple indexing \
1488 syntax (e.g., `tuple.0`)");
1498 fn check_expr_yield(
1500 value: &'tcx hir::Expr,
1501 expr: &'tcx hir::Expr,
1502 src: &'tcx hir::YieldSource
1504 match self.yield_ty {
1506 self.check_expr_coercable_to_type(&value, ty);
1508 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1509 // we know that the yield type must be `()`; however, the context won't contain this
1510 // information. Hence, we check the source of the yield expression here and check its
1511 // value's type against `()` (this check should always hold).
1512 None if src == &hir::YieldSource::Await => {
1513 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1516 struct_span_err!(self.tcx.sess, expr.span, E0627,
1517 "yield statement outside of generator literal").emit();