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;
34 use rustc::mir::interpret::GlobalId;
36 use rustc::ty::adjustment::{
37 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
39 use rustc::ty::{AdtKind, Visibility};
41 use rustc::ty::TypeFoldable;
42 use rustc::ty::subst::InternalSubsts;
43 use rustc::traits::{self, ObligationCauseCode};
45 use rustc_error_codes::*;
47 use std::fmt::Display;
49 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
50 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
51 let ty = self.check_expr_with_hint(expr, expected);
52 self.demand_eqtype(expr.span, expected, ty);
55 pub fn check_expr_has_type_or_error(
57 expr: &'tcx hir::Expr,
59 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
61 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
64 fn check_expr_meets_expectation_or_error(
66 expr: &'tcx hir::Expr,
67 expected: Expectation<'tcx>,
68 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
70 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
71 let mut ty = self.check_expr_with_expectation(expr, expected);
73 // While we don't allow *arbitrary* coercions here, we *do* allow
74 // coercions from ! to `expected`.
76 assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
77 "expression with never type wound up being adjusted");
78 let adj_ty = self.next_diverging_ty_var(
80 kind: TypeVariableOriginKind::AdjustmentType,
84 self.apply_adjustments(expr, vec![Adjustment {
85 kind: Adjust::NeverToAny,
91 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
92 let expr = expr.peel_drop_temps();
93 self.suggest_ref_or_into(&mut err, expr, expected_ty, ty);
95 // Error possibly reported in `check_assign` so avoid emitting error again.
96 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
101 pub(super) fn check_expr_coercable_to_type(
103 expr: &'tcx hir::Expr,
106 let ty = self.check_expr_with_hint(expr, expected);
107 // checks don't need two phase
108 self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
111 pub(super) fn check_expr_with_hint(
113 expr: &'tcx hir::Expr,
116 self.check_expr_with_expectation(expr, ExpectHasType(expected))
119 pub(super) fn check_expr_with_expectation(
121 expr: &'tcx hir::Expr,
122 expected: Expectation<'tcx>,
124 self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
127 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
128 self.check_expr_with_expectation(expr, NoExpectation)
131 pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
132 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
136 /// If an expression has any sub-expressions that result in a type error,
137 /// inspecting that expression's type with `ty.references_error()` will return
138 /// true. Likewise, if an expression is known to diverge, inspecting its
139 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
140 /// strict, _|_ can appear in the type of an expression that does not,
141 /// itself, diverge: for example, fn() -> _|_.)
142 /// Note that inspecting a type's structure *directly* may expose the fact
143 /// that there are actually multiple representations for `Error`, so avoid
144 /// that when err needs to be handled differently.
145 fn check_expr_with_expectation_and_needs(
147 expr: &'tcx hir::Expr,
148 expected: Expectation<'tcx>,
151 debug!(">> type-checking: expr={:?} expected={:?}",
154 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
155 // without the final expr (e.g. `try { return; }`). We don't want to generate an
156 // unreachable_code lint for it since warnings for autogenerated code are confusing.
157 let is_try_block_generated_unit_expr = match expr.kind {
158 ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
159 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock),
164 // Warn for expressions after diverging siblings.
165 if !is_try_block_generated_unit_expr {
166 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
169 // Hide the outer diverging and has_errors flags.
170 let old_diverges = self.diverges.get();
171 let old_has_errors = self.has_errors.get();
172 self.diverges.set(Diverges::Maybe);
173 self.has_errors.set(false);
175 let ty = self.check_expr_kind(expr, expected, needs);
177 // Warn for non-block expressions with diverging children.
179 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {},
180 // If `expr` is a result of desugaring the try block and is an ok-wrapped
181 // diverging expression (e.g. it arose from desugaring of `try { return }`),
182 // we skip issuing a warning because it is autogenerated code.
183 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {},
184 ExprKind::Call(ref callee, _) =>
185 self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
186 ExprKind::MethodCall(_, ref span, _) =>
187 self.warn_if_unreachable(expr.hir_id, *span, "call"),
188 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
191 // Any expression that produces a value of type `!` must have diverged
193 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
196 // Record the type, which applies it effects.
197 // We need to do this after the warning above, so that
198 // we don't warn for the diverging expression itself.
199 self.write_ty(expr.hir_id, ty);
201 // Combine the diverging and has_error flags.
202 self.diverges.set(self.diverges.get() | old_diverges);
203 self.has_errors.set(self.has_errors.get() | old_has_errors);
205 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
206 debug!("... {:?}, expected is {:?}", ty, expected);
213 expr: &'tcx hir::Expr,
214 expected: Expectation<'tcx>,
218 "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
226 ExprKind::Box(ref subexpr) => {
227 self.check_expr_box(subexpr, expected)
229 ExprKind::Lit(ref lit) => {
230 self.check_lit(&lit, expected)
232 ExprKind::Binary(op, ref lhs, ref rhs) => {
233 self.check_binop(expr, op, lhs, rhs)
235 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
236 self.check_binop_assign(expr, op, lhs, rhs)
238 ExprKind::Unary(unop, ref oprnd) => {
239 self.check_expr_unary(unop, oprnd, expected, needs, expr)
241 ExprKind::AddrOf(kind, mutbl, ref oprnd) => {
242 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
244 ExprKind::Path(ref qpath) => {
245 self.check_expr_path(qpath, expr)
247 ExprKind::InlineAsm(ref asm) => {
248 for expr in asm.outputs_exprs.iter().chain(asm.inputs_exprs.iter()) {
249 self.check_expr(expr);
253 ExprKind::Break(destination, ref expr_opt) => {
254 self.check_expr_break(destination, expr_opt.as_deref(), expr)
256 ExprKind::Continue(destination) => {
257 if destination.target_id.is_ok() {
260 // There was an error; make type-check fail.
264 ExprKind::Ret(ref expr_opt) => {
265 self.check_expr_return(expr_opt.as_deref(), expr)
267 ExprKind::Assign(ref lhs, ref rhs) => {
268 self.check_expr_assign(expr, expected, lhs, rhs)
270 ExprKind::Loop(ref body, _, source) => {
271 self.check_expr_loop(body, source, expected, expr)
273 ExprKind::Match(ref discrim, ref arms, match_src) => {
274 self.check_match(expr, &discrim, arms, expected, match_src)
276 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
277 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
279 ExprKind::Block(ref body, _) => {
280 self.check_block_with_expected(&body, expected)
282 ExprKind::Call(ref callee, ref args) => {
283 self.check_call(expr, &callee, args, expected)
285 ExprKind::MethodCall(ref segment, span, ref args) => {
286 self.check_method_call(expr, segment, span, args, expected, needs)
288 ExprKind::Cast(ref e, ref t) => {
289 self.check_expr_cast(e, t, expr)
291 ExprKind::Type(ref e, ref t) => {
292 let ty = self.to_ty_saving_user_provided_ty(&t);
293 self.check_expr_eq_type(&e, ty);
296 ExprKind::DropTemps(ref e) => {
297 self.check_expr_with_expectation(e, expected)
299 ExprKind::Array(ref args) => {
300 self.check_expr_array(args, expected, expr)
302 ExprKind::Repeat(ref element, ref count) => {
303 self.check_expr_repeat(element, count, expected, expr)
305 ExprKind::Tup(ref elts) => {
306 self.check_expr_tuple(elts, expected, expr)
308 ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
309 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
311 ExprKind::Field(ref base, field) => {
312 self.check_field(expr, needs, &base, field)
314 ExprKind::Index(ref base, ref idx) => {
315 self.check_expr_index(base, idx, needs, expr)
317 ExprKind::Yield(ref value, ref src) => {
318 self.check_expr_yield(value, expr, src)
320 hir::ExprKind::Err => {
326 fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
327 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
329 ty::Adt(def, _) if def.is_box()
330 => Expectation::rvalue_hint(self, ty.boxed_ty()),
334 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
335 self.tcx.mk_box(referent_ty)
341 oprnd: &'tcx hir::Expr,
342 expected: Expectation<'tcx>,
344 expr: &'tcx hir::Expr,
347 let expected_inner = match unop {
348 hir::UnNot | hir::UnNeg => expected,
349 hir::UnDeref => NoExpectation,
351 let needs = match unop {
352 hir::UnDeref => needs,
355 let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
357 if !oprnd_t.references_error() {
358 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
361 if let Some(mt) = oprnd_t.builtin_deref(true) {
363 } else if let Some(ok) = self.try_overloaded_deref(
364 expr.span, oprnd_t, needs) {
365 let method = self.register_infer_ok_obligations(ok);
366 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
367 let mutbl = match mutbl {
368 hir::Mutability::Immutable => AutoBorrowMutability::Immutable,
369 hir::Mutability::Mutable => AutoBorrowMutability::Mutable {
370 // (It shouldn't actually matter for unary ops whether
371 // we enable two-phase borrows or not, since a unary
372 // op has no additional operands.)
373 allow_two_phase_borrow: AllowTwoPhase::No,
376 self.apply_adjustments(oprnd, vec![Adjustment {
377 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
378 target: method.sig.inputs()[0]
381 oprnd_t = self.make_overloaded_place_return_type(method).ty;
382 self.write_method_call(expr.hir_id, method);
384 let mut err = type_error_struct!(
389 "type `{}` cannot be dereferenced",
392 let sp = tcx.sess.source_map().start_point(expr.span);
393 if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
396 tcx.sess.parse_sess.expr_parentheses_needed(
403 oprnd_t = tcx.types.err;
407 let result = self.check_user_unop(expr, oprnd_t, unop);
408 // If it's builtin, we can reuse the type, this helps inference.
409 if !(oprnd_t.is_integral() || oprnd_t.kind == ty::Bool) {
414 let result = self.check_user_unop(expr, oprnd_t, unop);
415 // If it's builtin, we can reuse the type, this helps inference.
416 if !oprnd_t.is_numeric() {
425 fn check_expr_addr_of(
427 kind: hir::BorrowKind,
428 mutbl: hir::Mutability,
429 oprnd: &'tcx hir::Expr,
430 expected: Expectation<'tcx>,
431 expr: &'tcx hir::Expr,
433 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
435 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
436 if oprnd.is_syntactic_place_expr() {
437 // Places may legitimately have unsized types.
438 // For example, dereferences of a fat pointer and
439 // the last field of a struct can be unsized.
442 Expectation::rvalue_hint(self, ty)
448 let needs = Needs::maybe_mut_place(mutbl);
449 let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
451 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
453 _ if tm.ty.references_error() => self.tcx.types.err,
454 hir::BorrowKind::Raw => {
455 self.check_named_place_expr(oprnd);
458 hir::BorrowKind::Ref => {
459 // Note: at this point, we cannot say what the best lifetime
460 // is to use for resulting pointer. We want to use the
461 // shortest lifetime possible so as to avoid spurious borrowck
462 // errors. Moreover, the longest lifetime will depend on the
463 // precise details of the value whose address is being taken
464 // (and how long it is valid), which we don't know yet until
465 // type inference is complete.
467 // Therefore, here we simply generate a region variable. The
468 // region inferencer will then select a suitable value.
469 // Finally, borrowck will infer the value of the region again,
470 // this time with enough precision to check that the value
471 // whose address was taken can actually be made to live as long
472 // as it needs to live.
473 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
474 self.tcx.mk_ref(region, tm)
479 /// Does this expression refer to a place that either:
480 /// * Is based on a local or static.
481 /// * Contains a dereference
482 /// Note that the adjustments for the children of `expr` should already
483 /// have been resolved.
484 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr) {
485 let is_named = oprnd.is_place_expr(|base| {
486 // Allow raw borrows if there are any deref adjustments.
488 // const VAL: (i32,) = (0,);
489 // const REF: &(i32,) = &(0,);
491 // &raw const VAL.0; // ERROR
492 // &raw const REF.0; // OK, same as &raw const (*REF).0;
494 // This is maybe too permissive, since it allows
495 // `let u = &raw const Box::new((1,)).0`, which creates an
496 // immediately dangling raw pointer.
497 self.tables.borrow().adjustments().get(base.hir_id).map_or(false, |x| {
498 x.iter().any(|adj| if let Adjust::Deref(_) = adj.kind {
506 struct_span_err!(self.tcx.sess, oprnd.span, E0745, "cannot take address of a temporary")
507 .span_label(oprnd.span, "temporary value")
512 fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
514 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
517 self.set_tainted_by_errors();
520 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
521 report_unexpected_variant_res(tcx, res, expr.span, qpath);
524 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
527 if let ty::FnDef(..) = ty.kind {
528 let fn_sig = ty.fn_sig(tcx);
529 if !tcx.features().unsized_locals {
530 // We want to remove some Sized bounds from std functions,
531 // but don't want to expose the removal to stable Rust.
532 // i.e., we don't want to allow
538 // to work in stable even if the Sized bound on `drop` is relaxed.
539 for i in 0..fn_sig.inputs().skip_binder().len() {
540 // We just want to check sizedness, so instead of introducing
541 // placeholder lifetimes with probing, we just replace higher lifetimes
543 let input = self.replace_bound_vars_with_fresh_vars(
545 infer::LateBoundRegionConversionTime::FnCall,
547 self.require_type_is_sized_deferred(input, expr.span,
548 traits::SizedArgumentType);
551 // Here we want to prevent struct constructors from returning unsized types.
552 // There were two cases this happened: fn pointer coercion in stable
553 // and usual function call in presence of unsized_locals.
554 // Also, as we just want to check sizedness, instead of introducing
555 // placeholder lifetimes with probing, we just replace higher lifetimes
557 let output = self.replace_bound_vars_with_fresh_vars(
559 infer::LateBoundRegionConversionTime::FnCall,
561 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
564 // We always require that the type provided as the value for
565 // a type parameter outlives the moment of instantiation.
566 let substs = self.tables.borrow().node_substs(expr.hir_id);
567 self.add_wf_bounds(substs, expr);
574 destination: hir::Destination,
575 expr_opt: Option<&'tcx hir::Expr>,
576 expr: &'tcx hir::Expr,
579 if let Ok(target_id) = destination.target_id {
581 if let Some(ref e) = expr_opt {
582 // If this is a break with a value, we need to type-check
583 // the expression. Get an expected type from the loop context.
584 let opt_coerce_to = {
585 // We should release `enclosing_breakables` before the `check_expr_with_hint`
586 // below, so can't move this block of code to the enclosing scope and share
587 // `ctxt` with the second `encloding_breakables` borrow below.
588 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
589 match enclosing_breakables.opt_find_breakable(target_id) {
591 ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
592 None => { // Avoid ICE when `break` is inside a closure (#65383).
593 self.tcx.sess.delay_span_bug(
595 "break was outside loop, but no error was emitted",
597 return tcx.types.err;
602 // If the loop context is not a `loop { }`, then break with
603 // a value is illegal, and `opt_coerce_to` will be `None`.
604 // Just set expectation to error in that case.
605 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
607 // Recurse without `enclosing_breakables` borrowed.
608 e_ty = self.check_expr_with_hint(e, coerce_to);
609 cause = self.misc(e.span);
611 // Otherwise, this is a break *without* a value. That's
612 // always legal, and is equivalent to `break ()`.
613 e_ty = tcx.mk_unit();
614 cause = self.misc(expr.span);
617 // Now that we have type-checked `expr_opt`, borrow
618 // the `enclosing_loops` field and let's coerce the
619 // type of `expr_opt` into what is expected.
620 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
621 let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
623 None => { // Avoid ICE when `break` is inside a closure (#65383).
624 self.tcx.sess.delay_span_bug(
626 "break was outside loop, but no error was emitted",
628 return tcx.types.err;
632 if let Some(ref mut coerce) = ctxt.coerce {
633 if let Some(ref e) = expr_opt {
634 coerce.coerce(self, &cause, e, e_ty);
636 assert!(e_ty.is_unit());
637 let ty = coerce.expected_ty();
638 coerce.coerce_forced_unit(self, &cause, &mut |mut err| {
639 self.suggest_mismatched_types_on_tail(
647 if let Some(val) = ty_kind_suggestion(ty) {
648 let label = destination.label
649 .map(|l| format!(" {}", l.ident))
650 .unwrap_or_else(String::new);
653 "give it a value of the expected type",
654 format!("break{} {}", label, val),
655 Applicability::HasPlaceholders,
661 // If `ctxt.coerce` is `None`, we can just ignore
662 // the type of the expression. This is because
663 // either this was a break *without* a value, in
664 // which case it is always a legal type (`()`), or
665 // else an error would have been flagged by the
666 // `loops` pass for using break with an expression
667 // where you are not supposed to.
668 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
671 ctxt.may_break = true;
673 // the type of a `break` is always `!`, since it diverges
676 // Otherwise, we failed to find the enclosing loop;
677 // this can only happen if the `break` was not
678 // inside a loop at all, which is caught by the
679 // loop-checking pass.
680 self.tcx.sess.delay_span_bug(expr.span,
681 "break was outside loop, but no error was emitted");
683 // We still need to assign a type to the inner expression to
684 // prevent the ICE in #43162.
685 if let Some(ref e) = expr_opt {
686 self.check_expr_with_hint(e, tcx.types.err);
688 // ... except when we try to 'break rust;'.
689 // ICE this expression in particular (see #43162).
690 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
691 if path.segments.len() == 1 &&
692 path.segments[0].ident.name == sym::rust {
693 fatally_break_rust(self.tcx.sess);
697 // There was an error; make type-check fail.
702 fn check_expr_return(
704 expr_opt: Option<&'tcx hir::Expr>,
705 expr: &'tcx hir::Expr
707 if self.ret_coercion.is_none() {
712 "return statement outside of function body",
714 } else if let Some(ref e) = expr_opt {
715 if self.ret_coercion_span.borrow().is_none() {
716 *self.ret_coercion_span.borrow_mut() = Some(e.span);
718 self.check_return_expr(e);
720 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
721 if self.ret_coercion_span.borrow().is_none() {
722 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
724 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
725 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
726 coercion.coerce_forced_unit(
731 fn_decl.output.span(),
733 "expected `{}` because of this return type",
741 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
747 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
751 .unwrap_or_else(|| span_bug!(return_expr.span,
752 "check_return_expr called outside fn body"));
754 let ret_ty = ret_coercion.borrow().expected_ty();
755 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
756 ret_coercion.borrow_mut().coerce(
758 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
764 /// Type check assignment expression `expr` of form `lhs = rhs`.
765 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
766 fn check_expr_assign(
768 expr: &'tcx hir::Expr,
769 expected: Expectation<'tcx>,
770 lhs: &'tcx hir::Expr,
771 rhs: &'tcx hir::Expr,
773 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
774 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
776 let expected_ty = expected.coercion_target_type(self, expr.span);
777 if expected_ty == self.tcx.types.bool {
778 // The expected type is `bool` but this will result in `()` so we can reasonably
779 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
780 // The likely cause of this is `if foo = bar { .. }`.
781 let actual_ty = self.tcx.mk_unit();
782 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
783 let msg = "try comparing for equality";
784 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
785 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
786 if let (Ok(left), Ok(right)) = (left, right) {
787 let help = format!("{} == {}", left, right);
788 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
793 } else if !lhs.is_syntactic_place_expr() {
794 struct_span_err!(self.tcx.sess, expr.span, E0070,
795 "invalid left-hand side expression")
796 .span_label(expr.span, "left-hand of expression not valid")
800 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
802 if lhs_ty.references_error() || rhs_ty.references_error() {
811 body: &'tcx hir::Block,
812 source: hir::LoopSource,
813 expected: Expectation<'tcx>,
814 expr: &'tcx hir::Expr,
816 let coerce = match source {
817 // you can only use break with a value from a normal `loop { }`
818 hir::LoopSource::Loop => {
819 let coerce_to = expected.coercion_target_type(self, body.span);
820 Some(CoerceMany::new(coerce_to))
823 hir::LoopSource::While |
824 hir::LoopSource::WhileLet |
825 hir::LoopSource::ForLoop => {
830 let ctxt = BreakableCtxt {
832 may_break: false, // Will get updated if/when we find a `break`.
835 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
836 self.check_block_no_value(&body);
840 // No way to know whether it's diverging because
841 // of a `break` or an outer `break` or `return`.
842 self.diverges.set(Diverges::Maybe);
845 // If we permit break with a value, then result type is
846 // the LUB of the breaks (possibly ! if none); else, it
847 // is nil. This makes sense because infinite loops
848 // (which would have type !) are only possible iff we
849 // permit break with a value [1].
850 if ctxt.coerce.is_none() && !ctxt.may_break {
852 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
854 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
857 /// Checks a method call.
858 fn check_method_call(
860 expr: &'tcx hir::Expr,
861 segment: &hir::PathSegment,
863 args: &'tcx [hir::Expr],
864 expected: Expectation<'tcx>,
868 let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
869 // no need to check for bot/err -- callee does that
870 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
872 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
874 let sig = self.tcx.fn_sig(method.def_id);
875 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
876 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
878 // We could do this only when type params are present in the method to reducte
879 // memory usage, but doing it unconditionally lets us also point at the method
880 // expression and state the resolved return value:
882 // error[E0282]: type annotations needed
883 // --> $DIR/issue-65611.rs:59:20
885 // LL | let x = buffer.last().unwrap().0.clone();
888 // | | cannot infer type for `T`
889 // | this method call resolves to `std::option::Option<&T>`
891 // = note: type must be known at this point
893 self.tables.borrow_mut().node_method_sig_mut().insert(expr.hir_id, sig);
895 self.write_method_call(expr.hir_id, method);
899 if segment.ident.name != kw::Invalid {
900 self.report_extended_method_error(segment, span, args, rcvr_t, error);
906 // Call the generic checker.
907 self.check_method_argument_types(
917 fn report_extended_method_error(
919 segment: &hir::PathSegment,
921 args: &'tcx [hir::Expr],
923 error: MethodError<'tcx>
926 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, rcvr_t, lang_item| {
927 if let Some(new_rcvr_t) = self.tcx.mk_lang_item(rcvr_t, lang_item) {
928 if let Ok(pick) = self.lookup_probe(
933 probe::ProbeScope::AllTraits,
936 pick.item.ident.span,
937 &format!("the method is available for `{}` here", new_rcvr_t),
943 if let Some(mut err) = self.report_method_error(
947 SelfSource::MethodCall(rcvr),
951 if let ty::Adt(..) = rcvr_t.kind {
952 // Try alternative arbitrary self types that could fulfill this call.
953 // FIXME: probe for all types that *could* be arbitrary self-types, not
954 // just this whitelist.
955 try_alt_rcvr(&mut err, rcvr_t, lang_items::OwnedBoxLangItem);
956 try_alt_rcvr(&mut err, rcvr_t, lang_items::PinTypeLangItem);
957 try_alt_rcvr(&mut err, rcvr_t, lang_items::Arc);
958 try_alt_rcvr(&mut err, rcvr_t, lang_items::Rc);
968 expr: &'tcx hir::Expr,
970 // Find the type of `e`. Supply hints based on the type we are casting to,
972 let t_cast = self.to_ty_saving_user_provided_ty(t);
973 let t_cast = self.resolve_vars_if_possible(&t_cast);
974 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
975 let t_cast = self.resolve_vars_if_possible(&t_cast);
977 // Eagerly check for some obvious errors.
978 if t_expr.references_error() || t_cast.references_error() {
981 // Defer other checks until we're done type checking.
982 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
983 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
985 deferred_cast_checks.push(cast_check);
988 Err(ErrorReported) => {
997 args: &'tcx [hir::Expr],
998 expected: Expectation<'tcx>,
999 expr: &'tcx hir::Expr
1001 let uty = expected.to_option(self).and_then(|uty| {
1003 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1008 let element_ty = if !args.is_empty() {
1009 let coerce_to = uty.unwrap_or_else(|| {
1010 self.next_ty_var(TypeVariableOrigin {
1011 kind: TypeVariableOriginKind::TypeInference,
1015 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1016 assert_eq!(self.diverges.get(), Diverges::Maybe);
1018 let e_ty = self.check_expr_with_hint(e, coerce_to);
1019 let cause = self.misc(e.span);
1020 coerce.coerce(self, &cause, e, e_ty);
1022 coerce.complete(self)
1024 self.next_ty_var(TypeVariableOrigin {
1025 kind: TypeVariableOriginKind::TypeInference,
1029 self.tcx.mk_array(element_ty, args.len() as u64)
1032 fn check_expr_repeat(
1034 element: &'tcx hir::Expr,
1035 count: &'tcx hir::AnonConst,
1036 expected: Expectation<'tcx>,
1037 _expr: &'tcx hir::Expr,
1040 let count_def_id = tcx.hir().local_def_id(count.hir_id);
1041 let count = if self.const_param_def_id(count).is_some() {
1042 Ok(self.to_const(count, tcx.type_of(count_def_id)))
1044 let param_env = ty::ParamEnv::empty();
1045 let substs = InternalSubsts::identity_for_item(tcx, count_def_id);
1046 let instance = ty::Instance::resolve(
1052 let global_id = GlobalId {
1057 tcx.const_eval(param_env.and(global_id))
1060 let uty = match expected {
1061 ExpectHasType(uty) => {
1063 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1070 let (element_ty, t) = match uty {
1072 self.check_expr_coercable_to_type(&element, uty);
1076 let ty = self.next_ty_var(TypeVariableOrigin {
1077 kind: TypeVariableOriginKind::MiscVariable,
1080 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1085 if element_ty.references_error() {
1087 } else if let Ok(count) = count {
1088 tcx.mk_ty(ty::Array(t, count))
1094 fn check_expr_tuple(
1096 elts: &'tcx [hir::Expr],
1097 expected: Expectation<'tcx>,
1098 expr: &'tcx hir::Expr,
1100 let flds = expected.only_has_type(self).and_then(|ty| {
1101 let ty = self.resolve_vars_with_obligations(ty);
1103 ty::Tuple(ref flds) => Some(&flds[..]),
1108 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
1109 let t = match flds {
1110 Some(ref fs) if i < fs.len() => {
1111 let ety = fs[i].expect_ty();
1112 self.check_expr_coercable_to_type(&e, ety);
1116 self.check_expr_with_expectation(&e, NoExpectation)
1121 let tuple = self.tcx.mk_tup(elt_ts_iter);
1122 if tuple.references_error() {
1125 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1130 fn check_expr_struct(
1133 expected: Expectation<'tcx>,
1135 fields: &'tcx [hir::Field],
1136 base_expr: &'tcx Option<P<hir::Expr>>,
1138 // Find the relevant variant
1139 let (variant, adt_ty) =
1140 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1143 self.check_struct_fields_on_error(fields, base_expr);
1144 return self.tcx.types.err;
1147 let path_span = match *qpath {
1148 QPath::Resolved(_, ref path) => path.span,
1149 QPath::TypeRelative(ref qself, _) => qself.span
1152 // Prohibit struct expressions when non-exhaustive flag is set.
1153 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1154 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1155 span_err!(self.tcx.sess, expr.span, E0639,
1156 "cannot create non-exhaustive {} using struct expression",
1157 adt.variant_descr());
1160 let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1161 variant, fields, base_expr.is_none());
1162 if let &Some(ref base_expr) = base_expr {
1163 // If check_expr_struct_fields hit an error, do not attempt to populate
1164 // the fields with the base_expr. This could cause us to hit errors later
1165 // when certain fields are assumed to exist that in fact do not.
1166 if !error_happened {
1167 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1169 ty::Adt(adt, substs) if adt.is_struct() => {
1170 let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1171 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1176 .fru_field_types_mut()
1177 .insert(expr.hir_id, fru_field_types);
1180 span_err!(self.tcx.sess, base_expr.span, E0436,
1181 "functional record update syntax requires a struct");
1186 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1190 fn check_expr_struct_fields(
1193 expected: Expectation<'tcx>,
1194 expr_id: hir::HirId,
1196 variant: &'tcx ty::VariantDef,
1197 ast_fields: &'tcx [hir::Field],
1198 check_completeness: bool,
1203 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1204 .get(0).cloned().unwrap_or(adt_ty);
1205 // re-link the regions that EIfEO can erase.
1206 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1208 let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1209 &ty::Adt(adt, substs) => {
1210 (substs, adt.adt_kind(), adt.variant_descr())
1212 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1215 let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1216 (field.ident.modern(), (i, field))
1217 ).collect::<FxHashMap<_, _>>();
1219 let mut seen_fields = FxHashMap::default();
1221 let mut error_happened = false;
1223 // Type-check each field.
1224 for field in ast_fields {
1225 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1226 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1227 seen_fields.insert(ident, field.span);
1228 self.write_field_index(field.hir_id, i);
1230 // We don't look at stability attributes on
1231 // struct-like enums (yet...), but it's definitely not
1232 // a bug to have constructed one.
1233 if adt_kind != AdtKind::Enum {
1234 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1237 self.field_ty(field.span, v_field, substs)
1239 error_happened = true;
1240 if let Some(prev_span) = seen_fields.get(&ident) {
1241 let mut err = struct_span_err!(self.tcx.sess,
1244 "field `{}` specified more than once",
1247 err.span_label(field.ident.span, "used more than once");
1248 err.span_label(*prev_span, format!("first use of `{}`", ident));
1252 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1258 // Make sure to give a type to the field even if there's
1259 // an error, so we can continue type-checking.
1260 self.check_expr_coercable_to_type(&field.expr, field_type);
1263 // Make sure the programmer specified correct number of fields.
1264 if kind_name == "union" {
1265 if ast_fields.len() != 1 {
1266 tcx.sess.span_err(span, "union expressions should have exactly one field");
1268 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1269 let len = remaining_fields.len();
1271 let mut displayable_field_names = remaining_fields
1273 .map(|ident| ident.as_str())
1274 .collect::<Vec<_>>();
1276 displayable_field_names.sort();
1278 let truncated_fields_error = if len <= 3 {
1281 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1284 let remaining_fields_names = displayable_field_names.iter().take(3)
1285 .map(|n| format!("`{}`", n))
1286 .collect::<Vec<_>>()
1289 struct_span_err!(tcx.sess, span, E0063,
1290 "missing field{} {}{} in initializer of `{}`",
1291 pluralize!(remaining_fields.len()),
1292 remaining_fields_names,
1293 truncated_fields_error,
1295 .span_label(span, format!("missing {}{}",
1296 remaining_fields_names,
1297 truncated_fields_error))
1303 fn check_struct_fields_on_error(
1305 fields: &'tcx [hir::Field],
1306 base_expr: &'tcx Option<P<hir::Expr>>,
1308 for field in fields {
1309 self.check_expr(&field.expr);
1311 if let Some(ref base) = *base_expr {
1312 self.check_expr(&base);
1316 fn report_unknown_field(
1319 variant: &'tcx ty::VariantDef,
1321 skip_fields: &[hir::Field],
1325 if variant.recovered {
1328 let mut err = self.type_error_struct_with_diag(
1330 |actual| match ty.kind {
1331 ty::Adt(adt, ..) if adt.is_enum() => {
1332 struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1333 "{} `{}::{}` has no field named `{}`",
1334 kind_name, actual, variant.ident, field.ident)
1337 struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1338 "{} `{}` has no field named `{}`",
1339 kind_name, actual, field.ident)
1343 match variant.ctor_kind {
1345 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1346 err.span_label(field.ident.span, "field does not exist");
1347 err.span_label(ty_span, format!(
1348 "`{adt}` is a tuple {kind_name}, \
1349 use the appropriate syntax: `{adt}(/* fields */)`",
1355 // prevent all specified fields from being suggested
1356 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1357 if let Some(field_name) = Self::suggest_field_name(
1359 &field.ident.as_str(),
1360 skip_fields.collect()
1362 err.span_suggestion(
1364 "a field with a similar name exists",
1365 field_name.to_string(),
1366 Applicability::MaybeIncorrect,
1370 ty::Adt(adt, ..) => {
1372 err.span_label(field.ident.span, format!(
1373 "`{}::{}` does not have this field",
1378 err.span_label(field.ident.span, format!(
1379 "`{}` does not have this field",
1383 let available_field_names = self.available_field_names(variant);
1384 if !available_field_names.is_empty() {
1385 err.note(&format!("available fields are: {}",
1386 self.name_series_display(available_field_names)));
1389 _ => bug!("non-ADT passed to report_unknown_field")
1397 // Return an hint about the closest match in field names
1398 fn suggest_field_name(variant: &'tcx ty::VariantDef,
1402 let names = variant.fields.iter().filter_map(|field| {
1403 // ignore already set fields and private fields from non-local crates
1404 if skip.iter().any(|&x| x == field.ident.name) ||
1405 (!variant.def_id.is_local() && field.vis != Visibility::Public)
1409 Some(&field.ident.name)
1413 find_best_match_for_name(names, field, None)
1416 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1417 variant.fields.iter().filter(|field| {
1419 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1420 field.vis.is_accessible_from(def_scope, self.tcx)
1422 .map(|field| field.ident.name)
1426 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1427 // dynamic limit, to never omit just one field
1428 let limit = if names.len() == 6 { 6 } else { 5 };
1429 let mut display = names.iter().take(limit)
1430 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1431 if names.len() > limit {
1432 display = format!("{} ... and {} others", display, names.len() - limit);
1437 // Check field access expressions
1440 expr: &'tcx hir::Expr,
1442 base: &'tcx hir::Expr,
1445 let expr_t = self.check_expr_with_needs(base, needs);
1446 let expr_t = self.structurally_resolved_type(base.span,
1448 let mut private_candidate = None;
1449 let mut autoderef = self.autoderef(expr.span, expr_t);
1450 while let Some((base_t, _)) = autoderef.next() {
1452 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1453 debug!("struct named {:?}", base_t);
1454 let (ident, def_scope) =
1455 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1456 let fields = &base_def.non_enum_variant().fields;
1457 if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1458 let field = &fields[index];
1459 let field_ty = self.field_ty(expr.span, field, substs);
1460 // Save the index of all fields regardless of their visibility in case
1461 // of error recovery.
1462 self.write_field_index(expr.hir_id, index);
1463 if field.vis.is_accessible_from(def_scope, self.tcx) {
1464 let adjustments = autoderef.adjust_steps(self, needs);
1465 self.apply_adjustments(base, adjustments);
1466 autoderef.finalize(self);
1468 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1471 private_candidate = Some((base_def.did, field_ty));
1474 ty::Tuple(ref tys) => {
1475 let fstr = field.as_str();
1476 if let Ok(index) = fstr.parse::<usize>() {
1477 if fstr == index.to_string() {
1478 if let Some(field_ty) = tys.get(index) {
1479 let adjustments = autoderef.adjust_steps(self, needs);
1480 self.apply_adjustments(base, adjustments);
1481 autoderef.finalize(self);
1483 self.write_field_index(expr.hir_id, index);
1484 return field_ty.expect_ty();
1492 autoderef.unambiguous_final_ty(self);
1494 if let Some((did, field_ty)) = private_candidate {
1495 self.ban_private_field_access(expr, expr_t, field, did);
1499 if field.name == kw::Invalid {
1500 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1501 self.ban_take_value_of_method(expr, expr_t, field);
1502 } else if !expr_t.is_primitive_ty() {
1503 self.ban_nonexisting_field(field, base, expr, expr_t);
1510 "`{}` is a primitive type and therefore doesn't have fields",
1516 self.tcx().types.err
1519 fn ban_nonexisting_field(
1522 base: &'tcx hir::Expr,
1523 expr: &'tcx hir::Expr,
1526 let mut err = self.no_such_field_err(field.span, field, expr_t);
1528 match expr_t.peel_refs().kind {
1529 ty::Array(_, len) => {
1530 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1533 self.suggest_first_deref_field(&mut err, expr, base, field);
1535 ty::Adt(def, _) if !def.is_enum() => {
1536 self.suggest_fields_on_recordish(&mut err, def, field);
1538 ty::Param(param_ty) => {
1539 self.point_at_param_definition(&mut err, param_ty);
1544 if field.name == kw::Await {
1545 // We know by construction that `<expr>.await` is either on Rust 2015
1546 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1547 err.note("to `.await` a `Future`, switch to Rust 2018");
1548 err.help("set `edition = \"2018\"` in `Cargo.toml`");
1549 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1555 fn ban_private_field_access(
1562 let struct_path = self.tcx().def_path_str(base_did);
1563 let kind_name = match self.tcx().def_kind(base_did) {
1564 Some(def_kind) => def_kind.descr(base_did),
1567 let mut err = struct_span_err!(
1571 "field `{}` of {} `{}` is private",
1576 // Also check if an accessible method exists, which is often what is meant.
1577 if self.method_exists(field, expr_t, expr.hir_id, false)
1578 && !self.expr_in_place(expr.hir_id)
1580 self.suggest_method_call(
1582 &format!("a method `{}` also exists, call it with parentheses", field),
1591 fn ban_take_value_of_method(&self, expr: &hir::Expr, expr_t: Ty<'tcx>, field: ast::Ident) {
1592 let mut err = type_error_struct!(
1597 "attempted to take value of method `{}` on type `{}`",
1602 if !self.expr_in_place(expr.hir_id) {
1603 self.suggest_method_call(
1605 "use parentheses to call the method",
1611 err.help("methods are immutable and cannot be assigned to");
1617 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1618 let generics = self.tcx.generics_of(self.body_id.owner_def_id());
1619 let generic_param = generics.type_param(¶m, self.tcx);
1620 if let ty::GenericParamDefKind::Type{synthetic: Some(..), ..} = generic_param.kind {
1623 let param_def_id = generic_param.def_id;
1624 let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
1628 let param_span = self.tcx.hir().span(param_hir_id);
1629 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1631 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1634 fn suggest_fields_on_recordish(
1636 err: &mut DiagnosticBuilder<'_>,
1637 def: &'tcx ty::AdtDef,
1640 if let Some(suggested_field_name) =
1641 Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
1643 err.span_suggestion(
1645 "a field with a similar name exists",
1646 suggested_field_name.to_string(),
1647 Applicability::MaybeIncorrect,
1650 err.span_label(field.span, "unknown field");
1651 let struct_variant_def = def.non_enum_variant();
1652 let field_names = self.available_field_names(struct_variant_def);
1653 if !field_names.is_empty() {
1655 "available fields are: {}",
1656 self.name_series_display(field_names),
1662 fn maybe_suggest_array_indexing(
1664 err: &mut DiagnosticBuilder<'_>,
1668 len: &ty::Const<'tcx>,
1670 if let (Some(len), Ok(user_index)) = (
1671 len.try_eval_usize(self.tcx, self.param_env),
1672 field.as_str().parse::<u64>()
1674 let base = self.tcx.sess.source_map()
1675 .span_to_snippet(base.span)
1676 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1677 let help = "instead of using tuple indexing, use array indexing";
1678 let suggestion = format!("{}[{}]", base, field);
1679 let applicability = if len < user_index {
1680 Applicability::MachineApplicable
1682 Applicability::MaybeIncorrect
1684 err.span_suggestion(expr.span, help, suggestion, applicability);
1688 fn suggest_first_deref_field(
1690 err: &mut DiagnosticBuilder<'_>,
1695 let base = self.tcx.sess.source_map()
1696 .span_to_snippet(base.span)
1697 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1698 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1699 let suggestion = format!("(*{}).{}", base, field);
1700 err.span_suggestion(
1704 Applicability::MaybeIncorrect,
1708 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1709 -> DiagnosticBuilder<'_> {
1710 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1711 "no field `{}` on type `{}`",
1715 fn check_expr_index(
1717 base: &'tcx hir::Expr,
1718 idx: &'tcx hir::Expr,
1720 expr: &'tcx hir::Expr,
1722 let base_t = self.check_expr_with_needs(&base, needs);
1723 let idx_t = self.check_expr(&idx);
1725 if base_t.references_error() {
1727 } else if idx_t.references_error() {
1730 let base_t = self.structurally_resolved_type(base.span, base_t);
1731 match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1732 Some((index_ty, element_ty)) => {
1733 // two-phase not needed because index_ty is never mutable
1734 self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1739 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1740 "cannot index into a value of type `{}`",
1742 // Try to give some advice about indexing tuples.
1743 if let ty::Tuple(..) = base_t.kind {
1744 let mut needs_note = true;
1745 // If the index is an integer, we can show the actual
1746 // fixed expression:
1747 if let ExprKind::Lit(ref lit) = idx.kind {
1748 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1749 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1750 if let Ok(snip) = snip {
1751 err.span_suggestion(
1753 "to access tuple elements, use",
1754 format!("{}.{}", snip, i),
1755 Applicability::MachineApplicable,
1762 err.help("to access tuple elements, use tuple indexing \
1763 syntax (e.g., `tuple.0`)");
1773 fn check_expr_yield(
1775 value: &'tcx hir::Expr,
1776 expr: &'tcx hir::Expr,
1777 src: &'tcx hir::YieldSource
1779 match self.yield_ty {
1781 self.check_expr_coercable_to_type(&value, ty);
1783 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1784 // we know that the yield type must be `()`; however, the context won't contain this
1785 // information. Hence, we check the source of the yield expression here and check its
1786 // value's type against `()` (this check should always hold).
1787 None if src == &hir::YieldSource::Await => {
1788 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1791 struct_span_err!(self.tcx.sess, expr.span, E0627,
1792 "yield statement outside of generator literal").emit();
1799 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1800 Some(match ty.kind {
1803 ty::Int(_) | ty::Uint(_) => "42",
1804 ty::Float(_) => "3.14159",
1805 ty::Error | ty::Never => return None,