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::{probe, SelfSource, MethodError};
16 use crate::util::common::ErrorReported;
17 use crate::util::nodemap::FxHashMap;
18 use crate::astconv::AstConv as _;
20 use errors::{Applicability, DiagnosticBuilder, pluralize};
21 use syntax_pos::hygiene::DesugaringKind;
23 use syntax::symbol::{Symbol, kw, sym};
24 use syntax::source_map::Span;
25 use syntax::util::lev_distance::find_best_match_for_name;
27 use rustc::hir::{ExprKind, QPath};
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::def::{CtorKind, Res, DefKind};
30 use rustc::hir::ptr::P;
32 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
33 use rustc::middle::lang_items;
35 use rustc::ty::adjustment::{
36 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
38 use rustc::ty::{AdtKind, Visibility};
40 use rustc::ty::TypeFoldable;
41 use rustc::traits::{self, ObligationCauseCode};
43 use rustc_error_codes::*;
45 use std::fmt::Display;
47 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
49 let ty = self.check_expr_with_hint(expr, expected);
50 self.demand_eqtype(expr.span, expected, ty);
53 pub fn check_expr_has_type_or_error(
55 expr: &'tcx hir::Expr,
57 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
59 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
62 fn check_expr_meets_expectation_or_error(
64 expr: &'tcx hir::Expr,
65 expected: Expectation<'tcx>,
66 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
68 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
69 let mut ty = self.check_expr_with_expectation(expr, expected);
71 // While we don't allow *arbitrary* coercions here, we *do* allow
72 // coercions from ! to `expected`.
74 assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
75 "expression with never type wound up being adjusted");
76 let adj_ty = self.next_diverging_ty_var(
78 kind: TypeVariableOriginKind::AdjustmentType,
82 self.apply_adjustments(expr, vec![Adjustment {
83 kind: Adjust::NeverToAny,
89 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
90 let expr = expr.peel_drop_temps();
91 self.suggest_ref_or_into(&mut err, expr, expected_ty, ty);
93 // Error possibly reported in `check_assign` so avoid emitting error again.
94 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
99 pub(super) fn check_expr_coercable_to_type(
101 expr: &'tcx hir::Expr,
104 let ty = self.check_expr_with_hint(expr, expected);
105 // checks don't need two phase
106 self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
109 pub(super) fn check_expr_with_hint(
111 expr: &'tcx hir::Expr,
114 self.check_expr_with_expectation(expr, ExpectHasType(expected))
117 pub(super) fn check_expr_with_expectation(
119 expr: &'tcx hir::Expr,
120 expected: Expectation<'tcx>,
122 self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
125 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
126 self.check_expr_with_expectation(expr, NoExpectation)
129 pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
130 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
134 /// If an expression has any sub-expressions that result in a type error,
135 /// inspecting that expression's type with `ty.references_error()` will return
136 /// true. Likewise, if an expression is known to diverge, inspecting its
137 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
138 /// strict, _|_ can appear in the type of an expression that does not,
139 /// itself, diverge: for example, fn() -> _|_.)
140 /// Note that inspecting a type's structure *directly* may expose the fact
141 /// that there are actually multiple representations for `Error`, so avoid
142 /// that when err needs to be handled differently.
143 fn check_expr_with_expectation_and_needs(
145 expr: &'tcx hir::Expr,
146 expected: Expectation<'tcx>,
149 debug!(">> type-checking: expr={:?} expected={:?}",
152 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
153 // without the final expr (e.g. `try { return; }`). We don't want to generate an
154 // unreachable_code lint for it since warnings for autogenerated code are confusing.
155 let is_try_block_generated_unit_expr = match expr.kind {
156 ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
157 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock),
162 // Warn for expressions after diverging siblings.
163 if !is_try_block_generated_unit_expr {
164 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
167 // Hide the outer diverging and has_errors flags.
168 let old_diverges = self.diverges.get();
169 let old_has_errors = self.has_errors.get();
170 self.diverges.set(Diverges::Maybe);
171 self.has_errors.set(false);
173 let ty = self.check_expr_kind(expr, expected, needs);
175 // Warn for non-block expressions with diverging children.
177 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {},
178 // If `expr` is a result of desugaring the try block and is an ok-wrapped
179 // diverging expression (e.g. it arose from desugaring of `try { return }`),
180 // we skip issuing a warning because it is autogenerated code.
181 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {},
182 ExprKind::Call(ref callee, _) =>
183 self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
184 ExprKind::MethodCall(_, ref span, _) =>
185 self.warn_if_unreachable(expr.hir_id, *span, "call"),
186 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
189 // Any expression that produces a value of type `!` must have diverged
191 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
194 // Record the type, which applies it effects.
195 // We need to do this after the warning above, so that
196 // we don't warn for the diverging expression itself.
197 self.write_ty(expr.hir_id, ty);
199 // Combine the diverging and has_error flags.
200 self.diverges.set(self.diverges.get() | old_diverges);
201 self.has_errors.set(self.has_errors.get() | old_has_errors);
203 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
204 debug!("... {:?}, expected is {:?}", ty, expected);
211 expr: &'tcx hir::Expr,
212 expected: Expectation<'tcx>,
216 "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
224 ExprKind::Box(ref subexpr) => {
225 self.check_expr_box(subexpr, expected)
227 ExprKind::Lit(ref lit) => {
228 self.check_lit(&lit, expected)
230 ExprKind::Binary(op, ref lhs, ref rhs) => {
231 self.check_binop(expr, op, lhs, rhs)
233 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
234 self.check_binop_assign(expr, op, lhs, rhs)
236 ExprKind::Unary(unop, ref oprnd) => {
237 self.check_expr_unary(unop, oprnd, expected, needs, expr)
239 ExprKind::AddrOf(kind, mutbl, ref oprnd) => {
240 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
242 ExprKind::Path(ref qpath) => {
243 self.check_expr_path(qpath, expr)
245 ExprKind::InlineAsm(ref asm) => {
246 for expr in asm.outputs_exprs.iter().chain(asm.inputs_exprs.iter()) {
247 self.check_expr(expr);
251 ExprKind::Break(destination, ref expr_opt) => {
252 self.check_expr_break(destination, expr_opt.as_deref(), expr)
254 ExprKind::Continue(destination) => {
255 if destination.target_id.is_ok() {
258 // There was an error; make type-check fail.
262 ExprKind::Ret(ref expr_opt) => {
263 self.check_expr_return(expr_opt.as_deref(), expr)
265 ExprKind::Assign(ref lhs, ref rhs) => {
266 self.check_expr_assign(expr, expected, lhs, rhs)
268 ExprKind::Loop(ref body, _, source) => {
269 self.check_expr_loop(body, source, expected, expr)
271 ExprKind::Match(ref discrim, ref arms, match_src) => {
272 self.check_match(expr, &discrim, arms, expected, match_src)
274 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
275 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
277 ExprKind::Block(ref body, _) => {
278 self.check_block_with_expected(&body, expected)
280 ExprKind::Call(ref callee, ref args) => {
281 self.check_call(expr, &callee, args, expected)
283 ExprKind::MethodCall(ref segment, span, ref args) => {
284 self.check_method_call(expr, segment, span, args, expected, needs)
286 ExprKind::Cast(ref e, ref t) => {
287 self.check_expr_cast(e, t, expr)
289 ExprKind::Type(ref e, ref t) => {
290 let ty = self.to_ty_saving_user_provided_ty(&t);
291 self.check_expr_eq_type(&e, ty);
294 ExprKind::DropTemps(ref e) => {
295 self.check_expr_with_expectation(e, expected)
297 ExprKind::Array(ref args) => {
298 self.check_expr_array(args, expected, expr)
300 ExprKind::Repeat(ref element, ref count) => {
301 self.check_expr_repeat(element, count, expected, expr)
303 ExprKind::Tup(ref elts) => {
304 self.check_expr_tuple(elts, expected, expr)
306 ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
307 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
309 ExprKind::Field(ref base, field) => {
310 self.check_field(expr, needs, &base, field)
312 ExprKind::Index(ref base, ref idx) => {
313 self.check_expr_index(base, idx, needs, expr)
315 ExprKind::Yield(ref value, ref src) => {
316 self.check_expr_yield(value, expr, src)
318 hir::ExprKind::Err => {
324 fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
325 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
327 ty::Adt(def, _) if def.is_box()
328 => Expectation::rvalue_hint(self, ty.boxed_ty()),
332 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
333 self.tcx.mk_box(referent_ty)
339 oprnd: &'tcx hir::Expr,
340 expected: Expectation<'tcx>,
342 expr: &'tcx hir::Expr,
345 let expected_inner = match unop {
346 hir::UnNot | hir::UnNeg => expected,
347 hir::UnDeref => NoExpectation,
349 let needs = match unop {
350 hir::UnDeref => needs,
353 let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
355 if !oprnd_t.references_error() {
356 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
359 if let Some(mt) = oprnd_t.builtin_deref(true) {
361 } else if let Some(ok) = self.try_overloaded_deref(
362 expr.span, oprnd_t, needs) {
363 let method = self.register_infer_ok_obligations(ok);
364 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
365 let mutbl = match mutbl {
366 hir::Mutability::Immutable => AutoBorrowMutability::Immutable,
367 hir::Mutability::Mutable => AutoBorrowMutability::Mutable {
368 // (It shouldn't actually matter for unary ops whether
369 // we enable two-phase borrows or not, since a unary
370 // op has no additional operands.)
371 allow_two_phase_borrow: AllowTwoPhase::No,
374 self.apply_adjustments(oprnd, vec![Adjustment {
375 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
376 target: method.sig.inputs()[0]
379 oprnd_t = self.make_overloaded_place_return_type(method).ty;
380 self.write_method_call(expr.hir_id, method);
382 let mut err = type_error_struct!(
387 "type `{}` cannot be dereferenced",
390 let sp = tcx.sess.source_map().start_point(expr.span);
391 if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
394 tcx.sess.parse_sess.expr_parentheses_needed(
401 oprnd_t = tcx.types.err;
405 let result = self.check_user_unop(expr, oprnd_t, unop);
406 // If it's builtin, we can reuse the type, this helps inference.
407 if !(oprnd_t.is_integral() || oprnd_t.kind == ty::Bool) {
412 let result = self.check_user_unop(expr, oprnd_t, unop);
413 // If it's builtin, we can reuse the type, this helps inference.
414 if !oprnd_t.is_numeric() {
423 fn check_expr_addr_of(
425 kind: hir::BorrowKind,
426 mutbl: hir::Mutability,
427 oprnd: &'tcx hir::Expr,
428 expected: Expectation<'tcx>,
429 expr: &'tcx hir::Expr,
431 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
433 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
434 if oprnd.is_syntactic_place_expr() {
435 // Places may legitimately have unsized types.
436 // For example, dereferences of a fat pointer and
437 // the last field of a struct can be unsized.
440 Expectation::rvalue_hint(self, ty)
446 let needs = Needs::maybe_mut_place(mutbl);
447 let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
449 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
451 _ if tm.ty.references_error() => self.tcx.types.err,
452 hir::BorrowKind::Raw => {
453 self.check_named_place_expr(oprnd);
456 hir::BorrowKind::Ref => {
457 // Note: at this point, we cannot say what the best lifetime
458 // is to use for resulting pointer. We want to use the
459 // shortest lifetime possible so as to avoid spurious borrowck
460 // errors. Moreover, the longest lifetime will depend on the
461 // precise details of the value whose address is being taken
462 // (and how long it is valid), which we don't know yet until
463 // type inference is complete.
465 // Therefore, here we simply generate a region variable. The
466 // region inferencer will then select a suitable value.
467 // Finally, borrowck will infer the value of the region again,
468 // this time with enough precision to check that the value
469 // whose address was taken can actually be made to live as long
470 // as it needs to live.
471 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
472 self.tcx.mk_ref(region, tm)
477 /// Does this expression refer to a place that either:
478 /// * Is based on a local or static.
479 /// * Contains a dereference
480 /// Note that the adjustments for the children of `expr` should already
481 /// have been resolved.
482 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr) {
483 let is_named = oprnd.is_place_expr(|base| {
484 // Allow raw borrows if there are any deref adjustments.
486 // const VAL: (i32,) = (0,);
487 // const REF: &(i32,) = &(0,);
489 // &raw const VAL.0; // ERROR
490 // &raw const REF.0; // OK, same as &raw const (*REF).0;
492 // This is maybe too permissive, since it allows
493 // `let u = &raw const Box::new((1,)).0`, which creates an
494 // immediately dangling raw pointer.
495 self.tables.borrow().adjustments().get(base.hir_id).map_or(false, |x| {
496 x.iter().any(|adj| if let Adjust::Deref(_) = adj.kind {
504 struct_span_err!(self.tcx.sess, oprnd.span, E0745, "cannot take address of a temporary")
505 .span_label(oprnd.span, "temporary value")
510 fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
512 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
515 self.set_tainted_by_errors();
518 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
519 report_unexpected_variant_res(tcx, res, expr.span, qpath);
522 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
525 if let ty::FnDef(..) = ty.kind {
526 let fn_sig = ty.fn_sig(tcx);
527 if !tcx.features().unsized_locals {
528 // We want to remove some Sized bounds from std functions,
529 // but don't want to expose the removal to stable Rust.
530 // i.e., we don't want to allow
536 // to work in stable even if the Sized bound on `drop` is relaxed.
537 for i in 0..fn_sig.inputs().skip_binder().len() {
538 // We just want to check sizedness, so instead of introducing
539 // placeholder lifetimes with probing, we just replace higher lifetimes
541 let input = self.replace_bound_vars_with_fresh_vars(
543 infer::LateBoundRegionConversionTime::FnCall,
545 self.require_type_is_sized_deferred(input, expr.span,
546 traits::SizedArgumentType);
549 // Here we want to prevent struct constructors from returning unsized types.
550 // There were two cases this happened: fn pointer coercion in stable
551 // and usual function call in presence of unsized_locals.
552 // Also, as we just want to check sizedness, instead of introducing
553 // placeholder lifetimes with probing, we just replace higher lifetimes
555 let output = self.replace_bound_vars_with_fresh_vars(
557 infer::LateBoundRegionConversionTime::FnCall,
559 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
562 // We always require that the type provided as the value for
563 // a type parameter outlives the moment of instantiation.
564 let substs = self.tables.borrow().node_substs(expr.hir_id);
565 self.add_wf_bounds(substs, expr);
572 destination: hir::Destination,
573 expr_opt: Option<&'tcx hir::Expr>,
574 expr: &'tcx hir::Expr,
577 if let Ok(target_id) = destination.target_id {
579 if let Some(ref e) = expr_opt {
580 // If this is a break with a value, we need to type-check
581 // the expression. Get an expected type from the loop context.
582 let opt_coerce_to = {
583 // We should release `enclosing_breakables` before the `check_expr_with_hint`
584 // below, so can't move this block of code to the enclosing scope and share
585 // `ctxt` with the second `encloding_breakables` borrow below.
586 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
587 match enclosing_breakables.opt_find_breakable(target_id) {
589 ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
590 None => { // Avoid ICE when `break` is inside a closure (#65383).
591 self.tcx.sess.delay_span_bug(
593 "break was outside loop, but no error was emitted",
595 return tcx.types.err;
600 // If the loop context is not a `loop { }`, then break with
601 // a value is illegal, and `opt_coerce_to` will be `None`.
602 // Just set expectation to error in that case.
603 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
605 // Recurse without `enclosing_breakables` borrowed.
606 e_ty = self.check_expr_with_hint(e, coerce_to);
607 cause = self.misc(e.span);
609 // Otherwise, this is a break *without* a value. That's
610 // always legal, and is equivalent to `break ()`.
611 e_ty = tcx.mk_unit();
612 cause = self.misc(expr.span);
615 // Now that we have type-checked `expr_opt`, borrow
616 // the `enclosing_loops` field and let's coerce the
617 // type of `expr_opt` into what is expected.
618 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
619 let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
621 None => { // Avoid ICE when `break` is inside a closure (#65383).
622 self.tcx.sess.delay_span_bug(
624 "break was outside loop, but no error was emitted",
626 return tcx.types.err;
630 if let Some(ref mut coerce) = ctxt.coerce {
631 if let Some(ref e) = expr_opt {
632 coerce.coerce(self, &cause, e, e_ty);
634 assert!(e_ty.is_unit());
635 let ty = coerce.expected_ty();
636 coerce.coerce_forced_unit(self, &cause, &mut |mut err| {
637 self.suggest_mismatched_types_on_tail(
645 if let Some(val) = ty_kind_suggestion(ty) {
646 let label = destination.label
647 .map(|l| format!(" {}", l.ident))
648 .unwrap_or_else(String::new);
651 "give it a value of the expected type",
652 format!("break{} {}", label, val),
653 Applicability::HasPlaceholders,
659 // If `ctxt.coerce` is `None`, we can just ignore
660 // the type of the expression. This is because
661 // either this was a break *without* a value, in
662 // which case it is always a legal type (`()`), or
663 // else an error would have been flagged by the
664 // `loops` pass for using break with an expression
665 // where you are not supposed to.
666 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
669 ctxt.may_break = true;
671 // the type of a `break` is always `!`, since it diverges
674 // Otherwise, we failed to find the enclosing loop;
675 // this can only happen if the `break` was not
676 // inside a loop at all, which is caught by the
677 // loop-checking pass.
678 self.tcx.sess.delay_span_bug(expr.span,
679 "break was outside loop, but no error was emitted");
681 // We still need to assign a type to the inner expression to
682 // prevent the ICE in #43162.
683 if let Some(ref e) = expr_opt {
684 self.check_expr_with_hint(e, tcx.types.err);
686 // ... except when we try to 'break rust;'.
687 // ICE this expression in particular (see #43162).
688 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
689 if path.segments.len() == 1 &&
690 path.segments[0].ident.name == sym::rust {
691 fatally_break_rust(self.tcx.sess);
695 // There was an error; make type-check fail.
700 fn check_expr_return(
702 expr_opt: Option<&'tcx hir::Expr>,
703 expr: &'tcx hir::Expr
705 if self.ret_coercion.is_none() {
710 "return statement outside of function body",
712 } else if let Some(ref e) = expr_opt {
713 if self.ret_coercion_span.borrow().is_none() {
714 *self.ret_coercion_span.borrow_mut() = Some(e.span);
716 self.check_return_expr(e);
718 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
719 if self.ret_coercion_span.borrow().is_none() {
720 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
722 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
723 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
724 coercion.coerce_forced_unit(
729 fn_decl.output.span(),
731 "expected `{}` because of this return type",
739 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
745 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
749 .unwrap_or_else(|| span_bug!(return_expr.span,
750 "check_return_expr called outside fn body"));
752 let ret_ty = ret_coercion.borrow().expected_ty();
753 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
754 ret_coercion.borrow_mut().coerce(
756 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
762 /// Type check assignment expression `expr` of form `lhs = rhs`.
763 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
764 fn check_expr_assign(
766 expr: &'tcx hir::Expr,
767 expected: Expectation<'tcx>,
768 lhs: &'tcx hir::Expr,
769 rhs: &'tcx hir::Expr,
771 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
772 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
774 let expected_ty = expected.coercion_target_type(self, expr.span);
775 if expected_ty == self.tcx.types.bool {
776 // The expected type is `bool` but this will result in `()` so we can reasonably
777 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
778 // The likely cause of this is `if foo = bar { .. }`.
779 let actual_ty = self.tcx.mk_unit();
780 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
781 let msg = "try comparing for equality";
782 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
783 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
784 if let (Ok(left), Ok(right)) = (left, right) {
785 let help = format!("{} == {}", left, right);
786 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
791 } else if !lhs.is_syntactic_place_expr() {
792 struct_span_err!(self.tcx.sess, expr.span, E0070,
793 "invalid left-hand side expression")
794 .span_label(expr.span, "left-hand of expression not valid")
798 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
800 if lhs_ty.references_error() || rhs_ty.references_error() {
809 body: &'tcx hir::Block,
810 source: hir::LoopSource,
811 expected: Expectation<'tcx>,
812 expr: &'tcx hir::Expr,
814 let coerce = match source {
815 // you can only use break with a value from a normal `loop { }`
816 hir::LoopSource::Loop => {
817 let coerce_to = expected.coercion_target_type(self, body.span);
818 Some(CoerceMany::new(coerce_to))
821 hir::LoopSource::While |
822 hir::LoopSource::WhileLet |
823 hir::LoopSource::ForLoop => {
828 let ctxt = BreakableCtxt {
830 may_break: false, // Will get updated if/when we find a `break`.
833 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
834 self.check_block_no_value(&body);
838 // No way to know whether it's diverging because
839 // of a `break` or an outer `break` or `return`.
840 self.diverges.set(Diverges::Maybe);
843 // If we permit break with a value, then result type is
844 // the LUB of the breaks (possibly ! if none); else, it
845 // is nil. This makes sense because infinite loops
846 // (which would have type !) are only possible iff we
847 // permit break with a value [1].
848 if ctxt.coerce.is_none() && !ctxt.may_break {
850 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
852 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
855 /// Checks a method call.
856 fn check_method_call(
858 expr: &'tcx hir::Expr,
859 segment: &hir::PathSegment,
861 args: &'tcx [hir::Expr],
862 expected: Expectation<'tcx>,
866 let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
867 // no need to check for bot/err -- callee does that
868 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
870 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
872 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
873 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
875 self.write_method_call(expr.hir_id, method);
879 if segment.ident.name != kw::Invalid {
880 self.report_extended_method_error(segment, span, args, rcvr_t, error);
886 // Call the generic checker.
887 self.check_method_argument_types(
897 fn report_extended_method_error(
899 segment: &hir::PathSegment,
901 args: &'tcx [hir::Expr],
903 error: MethodError<'tcx>
906 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, rcvr_t, lang_item| {
907 if let Some(new_rcvr_t) = self.tcx.mk_lang_item(rcvr_t, lang_item) {
908 if let Ok(pick) = self.lookup_probe(
913 probe::ProbeScope::AllTraits,
916 pick.item.ident.span,
917 &format!("the method is available for `{}` here", new_rcvr_t),
923 if let Some(mut err) = self.report_method_error(
927 SelfSource::MethodCall(rcvr),
931 if let ty::Adt(..) = rcvr_t.kind {
932 // Try alternative arbitrary self types that could fulfill this call.
933 // FIXME: probe for all types that *could* be arbitrary self-types, not
934 // just this whitelist.
935 try_alt_rcvr(&mut err, rcvr_t, lang_items::OwnedBoxLangItem);
936 try_alt_rcvr(&mut err, rcvr_t, lang_items::PinTypeLangItem);
937 try_alt_rcvr(&mut err, rcvr_t, lang_items::Arc);
938 try_alt_rcvr(&mut err, rcvr_t, lang_items::Rc);
948 expr: &'tcx hir::Expr,
950 // Find the type of `e`. Supply hints based on the type we are casting to,
952 let t_cast = self.to_ty_saving_user_provided_ty(t);
953 let t_cast = self.resolve_vars_if_possible(&t_cast);
954 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
955 let t_cast = self.resolve_vars_if_possible(&t_cast);
957 // Eagerly check for some obvious errors.
958 if t_expr.references_error() || t_cast.references_error() {
961 // Defer other checks until we're done type checking.
962 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
963 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
965 deferred_cast_checks.push(cast_check);
968 Err(ErrorReported) => {
977 args: &'tcx [hir::Expr],
978 expected: Expectation<'tcx>,
979 expr: &'tcx hir::Expr
981 let uty = expected.to_option(self).and_then(|uty| {
983 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
988 let element_ty = if !args.is_empty() {
989 let coerce_to = uty.unwrap_or_else(|| {
990 self.next_ty_var(TypeVariableOrigin {
991 kind: TypeVariableOriginKind::TypeInference,
995 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
996 assert_eq!(self.diverges.get(), Diverges::Maybe);
998 let e_ty = self.check_expr_with_hint(e, coerce_to);
999 let cause = self.misc(e.span);
1000 coerce.coerce(self, &cause, e, e_ty);
1002 coerce.complete(self)
1004 self.next_ty_var(TypeVariableOrigin {
1005 kind: TypeVariableOriginKind::TypeInference,
1009 self.tcx.mk_array(element_ty, args.len() as u64)
1012 fn check_expr_repeat(
1014 element: &'tcx hir::Expr,
1015 count: &'tcx hir::AnonConst,
1016 expected: Expectation<'tcx>,
1017 _expr: &'tcx hir::Expr,
1020 let count_def_id = tcx.hir().local_def_id(count.hir_id);
1021 let count = if self.const_param_def_id(count).is_some() {
1022 Ok(self.to_const(count, tcx.type_of(count_def_id)))
1024 tcx.const_eval_poly(count_def_id)
1027 let uty = match expected {
1028 ExpectHasType(uty) => {
1030 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1037 let (element_ty, t) = match uty {
1039 self.check_expr_coercable_to_type(&element, uty);
1043 let ty = self.next_ty_var(TypeVariableOrigin {
1044 kind: TypeVariableOriginKind::MiscVariable,
1047 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1052 if element_ty.references_error() {
1054 } else if let Ok(count) = count {
1055 tcx.mk_ty(ty::Array(t, count))
1061 fn check_expr_tuple(
1063 elts: &'tcx [hir::Expr],
1064 expected: Expectation<'tcx>,
1065 expr: &'tcx hir::Expr,
1067 let flds = expected.only_has_type(self).and_then(|ty| {
1068 let ty = self.resolve_vars_with_obligations(ty);
1070 ty::Tuple(ref flds) => Some(&flds[..]),
1075 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
1076 let t = match flds {
1077 Some(ref fs) if i < fs.len() => {
1078 let ety = fs[i].expect_ty();
1079 self.check_expr_coercable_to_type(&e, ety);
1083 self.check_expr_with_expectation(&e, NoExpectation)
1088 let tuple = self.tcx.mk_tup(elt_ts_iter);
1089 if tuple.references_error() {
1092 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1097 fn check_expr_struct(
1100 expected: Expectation<'tcx>,
1102 fields: &'tcx [hir::Field],
1103 base_expr: &'tcx Option<P<hir::Expr>>,
1105 // Find the relevant variant
1106 let (variant, adt_ty) =
1107 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1110 self.check_struct_fields_on_error(fields, base_expr);
1111 return self.tcx.types.err;
1114 let path_span = match *qpath {
1115 QPath::Resolved(_, ref path) => path.span,
1116 QPath::TypeRelative(ref qself, _) => qself.span
1119 // Prohibit struct expressions when non-exhaustive flag is set.
1120 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1121 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1122 span_err!(self.tcx.sess, expr.span, E0639,
1123 "cannot create non-exhaustive {} using struct expression",
1124 adt.variant_descr());
1127 let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1128 variant, fields, base_expr.is_none());
1129 if let &Some(ref base_expr) = base_expr {
1130 // If check_expr_struct_fields hit an error, do not attempt to populate
1131 // the fields with the base_expr. This could cause us to hit errors later
1132 // when certain fields are assumed to exist that in fact do not.
1133 if !error_happened {
1134 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1136 ty::Adt(adt, substs) if adt.is_struct() => {
1137 let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1138 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1143 .fru_field_types_mut()
1144 .insert(expr.hir_id, fru_field_types);
1147 span_err!(self.tcx.sess, base_expr.span, E0436,
1148 "functional record update syntax requires a struct");
1153 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1157 fn check_expr_struct_fields(
1160 expected: Expectation<'tcx>,
1161 expr_id: hir::HirId,
1163 variant: &'tcx ty::VariantDef,
1164 ast_fields: &'tcx [hir::Field],
1165 check_completeness: bool,
1170 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1171 .get(0).cloned().unwrap_or(adt_ty);
1172 // re-link the regions that EIfEO can erase.
1173 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1175 let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1176 &ty::Adt(adt, substs) => {
1177 (substs, adt.adt_kind(), adt.variant_descr())
1179 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1182 let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1183 (field.ident.modern(), (i, field))
1184 ).collect::<FxHashMap<_, _>>();
1186 let mut seen_fields = FxHashMap::default();
1188 let mut error_happened = false;
1190 // Type-check each field.
1191 for field in ast_fields {
1192 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1193 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1194 seen_fields.insert(ident, field.span);
1195 self.write_field_index(field.hir_id, i);
1197 // We don't look at stability attributes on
1198 // struct-like enums (yet...), but it's definitely not
1199 // a bug to have constructed one.
1200 if adt_kind != AdtKind::Enum {
1201 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1204 self.field_ty(field.span, v_field, substs)
1206 error_happened = true;
1207 if let Some(prev_span) = seen_fields.get(&ident) {
1208 let mut err = struct_span_err!(self.tcx.sess,
1211 "field `{}` specified more than once",
1214 err.span_label(field.ident.span, "used more than once");
1215 err.span_label(*prev_span, format!("first use of `{}`", ident));
1219 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1225 // Make sure to give a type to the field even if there's
1226 // an error, so we can continue type-checking.
1227 self.check_expr_coercable_to_type(&field.expr, field_type);
1230 // Make sure the programmer specified correct number of fields.
1231 if kind_name == "union" {
1232 if ast_fields.len() != 1 {
1233 tcx.sess.span_err(span, "union expressions should have exactly one field");
1235 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1236 let len = remaining_fields.len();
1238 let mut displayable_field_names = remaining_fields
1240 .map(|ident| ident.as_str())
1241 .collect::<Vec<_>>();
1243 displayable_field_names.sort();
1245 let truncated_fields_error = if len <= 3 {
1248 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1251 let remaining_fields_names = displayable_field_names.iter().take(3)
1252 .map(|n| format!("`{}`", n))
1253 .collect::<Vec<_>>()
1256 struct_span_err!(tcx.sess, span, E0063,
1257 "missing field{} {}{} in initializer of `{}`",
1258 pluralize!(remaining_fields.len()),
1259 remaining_fields_names,
1260 truncated_fields_error,
1262 .span_label(span, format!("missing {}{}",
1263 remaining_fields_names,
1264 truncated_fields_error))
1270 fn check_struct_fields_on_error(
1272 fields: &'tcx [hir::Field],
1273 base_expr: &'tcx Option<P<hir::Expr>>,
1275 for field in fields {
1276 self.check_expr(&field.expr);
1278 if let Some(ref base) = *base_expr {
1279 self.check_expr(&base);
1283 fn report_unknown_field(
1286 variant: &'tcx ty::VariantDef,
1288 skip_fields: &[hir::Field],
1292 if variant.recovered {
1295 let mut err = self.type_error_struct_with_diag(
1297 |actual| match ty.kind {
1298 ty::Adt(adt, ..) if adt.is_enum() => {
1299 struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1300 "{} `{}::{}` has no field named `{}`",
1301 kind_name, actual, variant.ident, field.ident)
1304 struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1305 "{} `{}` has no field named `{}`",
1306 kind_name, actual, field.ident)
1310 match variant.ctor_kind {
1312 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1313 err.span_label(field.ident.span, "field does not exist");
1314 err.span_label(ty_span, format!(
1315 "`{adt}` is a tuple {kind_name}, \
1316 use the appropriate syntax: `{adt}(/* fields */)`",
1322 // prevent all specified fields from being suggested
1323 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1324 if let Some(field_name) = Self::suggest_field_name(
1326 &field.ident.as_str(),
1327 skip_fields.collect()
1329 err.span_suggestion(
1331 "a field with a similar name exists",
1332 field_name.to_string(),
1333 Applicability::MaybeIncorrect,
1337 ty::Adt(adt, ..) => {
1339 err.span_label(field.ident.span, format!(
1340 "`{}::{}` does not have this field",
1345 err.span_label(field.ident.span, format!(
1346 "`{}` does not have this field",
1350 let available_field_names = self.available_field_names(variant);
1351 if !available_field_names.is_empty() {
1352 err.note(&format!("available fields are: {}",
1353 self.name_series_display(available_field_names)));
1356 _ => bug!("non-ADT passed to report_unknown_field")
1364 // Return an hint about the closest match in field names
1365 fn suggest_field_name(variant: &'tcx ty::VariantDef,
1369 let names = variant.fields.iter().filter_map(|field| {
1370 // ignore already set fields and private fields from non-local crates
1371 if skip.iter().any(|&x| x == field.ident.name) ||
1372 (!variant.def_id.is_local() && field.vis != Visibility::Public)
1376 Some(&field.ident.name)
1380 find_best_match_for_name(names, field, None)
1383 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1384 variant.fields.iter().filter(|field| {
1386 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1387 field.vis.is_accessible_from(def_scope, self.tcx)
1389 .map(|field| field.ident.name)
1393 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1394 // dynamic limit, to never omit just one field
1395 let limit = if names.len() == 6 { 6 } else { 5 };
1396 let mut display = names.iter().take(limit)
1397 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1398 if names.len() > limit {
1399 display = format!("{} ... and {} others", display, names.len() - limit);
1404 // Check field access expressions
1407 expr: &'tcx hir::Expr,
1409 base: &'tcx hir::Expr,
1412 let expr_t = self.check_expr_with_needs(base, needs);
1413 let expr_t = self.structurally_resolved_type(base.span, expr_t);
1414 let mut private_candidate = None;
1415 let mut autoderef = self.autoderef(expr.span, expr_t);
1416 while let Some((base_t, _)) = autoderef.next() {
1418 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1419 debug!("struct named {:?}", base_t);
1420 let (ident, def_scope) =
1421 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1422 let fields = &base_def.non_enum_variant().fields;
1423 if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1424 let field = &fields[index];
1425 let field_ty = self.field_ty(expr.span, field, substs);
1426 // Save the index of all fields regardless of their visibility in case
1427 // of error recovery.
1428 self.write_field_index(expr.hir_id, index);
1429 if field.vis.is_accessible_from(def_scope, self.tcx) {
1430 let adjustments = autoderef.adjust_steps(self, needs);
1431 self.apply_adjustments(base, adjustments);
1432 autoderef.finalize(self);
1434 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1437 private_candidate = Some((base_def.did, field_ty));
1440 ty::Tuple(ref tys) => {
1441 let fstr = field.as_str();
1442 if let Ok(index) = fstr.parse::<usize>() {
1443 if fstr == index.to_string() {
1444 if let Some(field_ty) = tys.get(index) {
1445 let adjustments = autoderef.adjust_steps(self, needs);
1446 self.apply_adjustments(base, adjustments);
1447 autoderef.finalize(self);
1449 self.write_field_index(expr.hir_id, index);
1450 return field_ty.expect_ty();
1458 autoderef.unambiguous_final_ty(self);
1460 if let Some((did, field_ty)) = private_candidate {
1461 self.ban_private_field_access(expr, expr_t, field, did);
1465 if field.name == kw::Invalid {
1466 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1467 self.ban_take_value_of_method(expr, expr_t, field);
1468 } else if !expr_t.is_primitive_ty() {
1469 self.ban_nonexisting_field(field, base, expr, expr_t);
1476 "`{}` is a primitive type and therefore doesn't have fields",
1482 self.tcx().types.err
1485 fn ban_nonexisting_field(
1488 base: &'tcx hir::Expr,
1489 expr: &'tcx hir::Expr,
1492 let mut err = self.no_such_field_err(field.span, field, expr_t);
1494 match expr_t.peel_refs().kind {
1495 ty::Array(_, len) => {
1496 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1499 self.suggest_first_deref_field(&mut err, expr, base, field);
1501 ty::Adt(def, _) if !def.is_enum() => {
1502 self.suggest_fields_on_recordish(&mut err, def, field);
1504 ty::Param(param_ty) => {
1505 self.point_at_param_definition(&mut err, param_ty);
1510 if field.name == kw::Await {
1511 // We know by construction that `<expr>.await` is either on Rust 2015
1512 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1513 err.note("to `.await` a `Future`, switch to Rust 2018");
1514 err.help("set `edition = \"2018\"` in `Cargo.toml`");
1515 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1521 fn ban_private_field_access(
1528 let struct_path = self.tcx().def_path_str(base_did);
1529 let kind_name = match self.tcx().def_kind(base_did) {
1530 Some(def_kind) => def_kind.descr(base_did),
1533 let mut err = struct_span_err!(
1537 "field `{}` of {} `{}` is private",
1542 // Also check if an accessible method exists, which is often what is meant.
1543 if self.method_exists(field, expr_t, expr.hir_id, false)
1544 && !self.expr_in_place(expr.hir_id)
1546 self.suggest_method_call(
1548 &format!("a method `{}` also exists, call it with parentheses", field),
1557 fn ban_take_value_of_method(&self, expr: &hir::Expr, expr_t: Ty<'tcx>, field: ast::Ident) {
1558 let mut err = type_error_struct!(
1563 "attempted to take value of method `{}` on type `{}`",
1568 if !self.expr_in_place(expr.hir_id) {
1569 self.suggest_method_call(
1571 "use parentheses to call the method",
1577 err.help("methods are immutable and cannot be assigned to");
1583 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1584 let generics = self.tcx.generics_of(self.body_id.owner_def_id());
1585 let generic_param = generics.type_param(¶m, self.tcx);
1586 if let ty::GenericParamDefKind::Type{synthetic: Some(..), ..} = generic_param.kind {
1589 let param_def_id = generic_param.def_id;
1590 let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
1594 let param_span = self.tcx.hir().span(param_hir_id);
1595 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1597 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1600 fn suggest_fields_on_recordish(
1602 err: &mut DiagnosticBuilder<'_>,
1603 def: &'tcx ty::AdtDef,
1606 if let Some(suggested_field_name) =
1607 Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
1609 err.span_suggestion(
1611 "a field with a similar name exists",
1612 suggested_field_name.to_string(),
1613 Applicability::MaybeIncorrect,
1616 err.span_label(field.span, "unknown field");
1617 let struct_variant_def = def.non_enum_variant();
1618 let field_names = self.available_field_names(struct_variant_def);
1619 if !field_names.is_empty() {
1621 "available fields are: {}",
1622 self.name_series_display(field_names),
1628 fn maybe_suggest_array_indexing(
1630 err: &mut DiagnosticBuilder<'_>,
1634 len: &ty::Const<'tcx>,
1636 if let (Some(len), Ok(user_index)) = (
1637 len.try_eval_usize(self.tcx, self.param_env),
1638 field.as_str().parse::<u64>()
1640 let base = self.tcx.sess.source_map()
1641 .span_to_snippet(base.span)
1642 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1643 let help = "instead of using tuple indexing, use array indexing";
1644 let suggestion = format!("{}[{}]", base, field);
1645 let applicability = if len < user_index {
1646 Applicability::MachineApplicable
1648 Applicability::MaybeIncorrect
1650 err.span_suggestion(expr.span, help, suggestion, applicability);
1654 fn suggest_first_deref_field(
1656 err: &mut DiagnosticBuilder<'_>,
1661 let base = self.tcx.sess.source_map()
1662 .span_to_snippet(base.span)
1663 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1664 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1665 let suggestion = format!("(*{}).{}", base, field);
1666 err.span_suggestion(
1670 Applicability::MaybeIncorrect,
1674 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1675 -> DiagnosticBuilder<'_> {
1676 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1677 "no field `{}` on type `{}`",
1681 fn check_expr_index(
1683 base: &'tcx hir::Expr,
1684 idx: &'tcx hir::Expr,
1686 expr: &'tcx hir::Expr,
1688 let base_t = self.check_expr_with_needs(&base, needs);
1689 let idx_t = self.check_expr(&idx);
1691 if base_t.references_error() {
1693 } else if idx_t.references_error() {
1696 let base_t = self.structurally_resolved_type(base.span, base_t);
1697 match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1698 Some((index_ty, element_ty)) => {
1699 // two-phase not needed because index_ty is never mutable
1700 self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1705 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1706 "cannot index into a value of type `{}`",
1708 // Try to give some advice about indexing tuples.
1709 if let ty::Tuple(..) = base_t.kind {
1710 let mut needs_note = true;
1711 // If the index is an integer, we can show the actual
1712 // fixed expression:
1713 if let ExprKind::Lit(ref lit) = idx.kind {
1714 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1715 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1716 if let Ok(snip) = snip {
1717 err.span_suggestion(
1719 "to access tuple elements, use",
1720 format!("{}.{}", snip, i),
1721 Applicability::MachineApplicable,
1728 err.help("to access tuple elements, use tuple indexing \
1729 syntax (e.g., `tuple.0`)");
1739 fn check_expr_yield(
1741 value: &'tcx hir::Expr,
1742 expr: &'tcx hir::Expr,
1743 src: &'tcx hir::YieldSource
1745 match self.yield_ty {
1747 self.check_expr_coercable_to_type(&value, ty);
1749 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1750 // we know that the yield type must be `()`; however, the context won't contain this
1751 // information. Hence, we check the source of the yield expression here and check its
1752 // value's type against `()` (this check should always hold).
1753 None if src == &hir::YieldSource::Await => {
1754 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1757 struct_span_err!(self.tcx.sess, expr.span, E0627,
1758 "yield statement outside of generator literal").emit();
1765 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1766 Some(match ty.kind {
1769 ty::Int(_) | ty::Uint(_) => "42",
1770 ty::Float(_) => "3.14159",
1771 ty::Error | ty::Never => return None,