1 //! Type checking expressions.
3 //! See `mod.rs` for more context on type checking in general.
5 use crate::astconv::AstConv as _;
6 use crate::check::cast;
7 use crate::check::coercion::CoerceMany;
8 use crate::check::fatally_break_rust;
9 use crate::check::method::{probe, MethodError, SelfSource};
10 use crate::check::report_unexpected_variant_res;
11 use crate::check::BreakableCtxt;
12 use crate::check::Diverges;
13 use crate::check::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
14 use crate::check::FnCtxt;
15 use crate::check::Needs;
16 use crate::check::TupleArgumentsFlag::DontTupleArguments;
18 FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
19 YieldExprOutsideOfGenerator,
21 use crate::type_error_struct;
23 use crate::errors::{AddressOfTemporaryTaken, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive};
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::stack::ensure_sufficient_stack;
27 use rustc_errors::ErrorReported;
28 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId};
30 use rustc_hir::def::{CtorKind, DefKind, Res};
31 use rustc_hir::def_id::DefId;
32 use rustc_hir::lang_items::LangItem;
33 use rustc_hir::{ExprKind, QPath};
34 use rustc_infer::infer;
35 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
37 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
38 use rustc_middle::ty::Ty;
39 use rustc_middle::ty::TypeFoldable;
40 use rustc_middle::ty::{AdtKind, Visibility};
41 use rustc_span::edition::LATEST_STABLE_EDITION;
42 use rustc_span::hygiene::DesugaringKind;
43 use rustc_span::lev_distance::find_best_match_for_name;
44 use rustc_span::source_map::Span;
45 use rustc_span::symbol::{kw, sym, Ident, Symbol};
46 use rustc_trait_selection::traits::{self, ObligationCauseCode};
48 use std::fmt::Display;
50 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
51 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
52 let ty = self.check_expr_with_hint(expr, expected);
53 self.demand_eqtype(expr.span, expected, ty);
56 pub fn check_expr_has_type_or_error(
58 expr: &'tcx hir::Expr<'tcx>,
60 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
62 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
65 fn check_expr_meets_expectation_or_error(
67 expr: &'tcx hir::Expr<'tcx>,
68 expected: Expectation<'tcx>,
69 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
71 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
72 let mut ty = self.check_expr_with_expectation(expr, expected);
74 // While we don't allow *arbitrary* coercions here, we *do* allow
75 // coercions from ! to `expected`.
78 !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id),
79 "expression with never type wound up being adjusted"
81 let adj_ty = self.next_diverging_ty_var(TypeVariableOrigin {
82 kind: TypeVariableOriginKind::AdjustmentType,
85 self.apply_adjustments(
87 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
92 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
93 let expr = expr.peel_drop_temps();
94 self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None);
96 // Error possibly reported in `check_assign` so avoid emitting error again.
97 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
102 pub(super) fn check_expr_coercable_to_type(
104 expr: &'tcx hir::Expr<'tcx>,
106 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
108 let ty = self.check_expr_with_hint(expr, expected);
109 // checks don't need two phase
110 self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No)
113 pub(super) fn check_expr_with_hint(
115 expr: &'tcx hir::Expr<'tcx>,
118 self.check_expr_with_expectation(expr, ExpectHasType(expected))
121 fn check_expr_with_expectation_and_needs(
123 expr: &'tcx hir::Expr<'tcx>,
124 expected: Expectation<'tcx>,
127 let ty = self.check_expr_with_expectation(expr, expected);
129 // If the expression is used in a place whether mutable place is required
130 // e.g. LHS of assignment, perform the conversion.
131 if let Needs::MutPlace = needs {
132 self.convert_place_derefs_to_mutable(expr);
138 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
139 self.check_expr_with_expectation(expr, NoExpectation)
142 pub(super) fn check_expr_with_needs(
144 expr: &'tcx hir::Expr<'tcx>,
147 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
151 /// If an expression has any sub-expressions that result in a type error,
152 /// inspecting that expression's type with `ty.references_error()` will return
153 /// true. Likewise, if an expression is known to diverge, inspecting its
154 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
155 /// strict, _|_ can appear in the type of an expression that does not,
156 /// itself, diverge: for example, fn() -> _|_.)
157 /// Note that inspecting a type's structure *directly* may expose the fact
158 /// that there are actually multiple representations for `Error`, so avoid
159 /// that when err needs to be handled differently.
160 pub(super) fn check_expr_with_expectation(
162 expr: &'tcx hir::Expr<'tcx>,
163 expected: Expectation<'tcx>,
165 debug!(">> type-checking: expr={:?} expected={:?}", expr, expected);
167 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
168 // without the final expr (e.g. `try { return; }`). We don't want to generate an
169 // unreachable_code lint for it since warnings for autogenerated code are confusing.
170 let is_try_block_generated_unit_expr = match expr.kind {
171 ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
172 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
178 // Warn for expressions after diverging siblings.
179 if !is_try_block_generated_unit_expr {
180 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
183 // Hide the outer diverging and has_errors flags.
184 let old_diverges = self.diverges.replace(Diverges::Maybe);
185 let old_has_errors = self.has_errors.replace(false);
187 let ty = ensure_sufficient_stack(|| self.check_expr_kind(expr, expected));
189 // Warn for non-block expressions with diverging children.
191 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {}
192 // If `expr` is a result of desugaring the try block and is an ok-wrapped
193 // diverging expression (e.g. it arose from desugaring of `try { return }`),
194 // we skip issuing a warning because it is autogenerated code.
195 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
196 ExprKind::Call(ref callee, _) => {
197 self.warn_if_unreachable(expr.hir_id, callee.span, "call")
199 ExprKind::MethodCall(_, ref span, _, _) => {
200 self.warn_if_unreachable(expr.hir_id, *span, "call")
202 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
205 // Any expression that produces a value of type `!` must have diverged
207 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
210 // Record the type, which applies it effects.
211 // We need to do this after the warning above, so that
212 // we don't warn for the diverging expression itself.
213 self.write_ty(expr.hir_id, ty);
215 // Combine the diverging and has_error flags.
216 self.diverges.set(self.diverges.get() | old_diverges);
217 self.has_errors.set(self.has_errors.get() | old_has_errors);
219 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
220 debug!("... {:?}, expected is {:?}", ty, expected);
227 expr: &'tcx hir::Expr<'tcx>,
228 expected: Expectation<'tcx>,
230 debug!("check_expr_kind(expr={:?}, expected={:?})", expr, expected);
234 ExprKind::Box(ref subexpr) => self.check_expr_box(subexpr, expected),
235 ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
236 ExprKind::Binary(op, ref lhs, ref rhs) => self.check_binop(expr, op, lhs, rhs),
237 ExprKind::Assign(ref lhs, ref rhs, ref span) => {
238 self.check_expr_assign(expr, expected, lhs, rhs, span)
240 ExprKind::AssignOp(op, ref lhs, ref rhs) => self.check_binop_assign(expr, op, lhs, rhs),
241 ExprKind::Unary(unop, ref oprnd) => self.check_expr_unary(unop, oprnd, expected, expr),
242 ExprKind::AddrOf(kind, mutbl, ref oprnd) => {
243 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
245 ExprKind::Path(QPath::LangItem(lang_item, _)) => {
246 self.check_lang_item_path(lang_item, expr)
248 ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr),
249 ExprKind::InlineAsm(asm) => self.check_expr_asm(asm),
250 ExprKind::LlvmInlineAsm(ref asm) => {
251 for expr in asm.outputs_exprs.iter().chain(asm.inputs_exprs.iter()) {
252 self.check_expr(expr);
256 ExprKind::Break(destination, ref expr_opt) => {
257 self.check_expr_break(destination, expr_opt.as_deref(), expr)
259 ExprKind::Continue(destination) => {
260 if destination.target_id.is_ok() {
263 // There was an error; make type-check fail.
267 ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
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, _) => self.check_block_with_expected(&body, expected),
278 ExprKind::Call(ref callee, ref args) => self.check_call(expr, &callee, args, expected),
279 ExprKind::MethodCall(ref segment, span, ref args, _) => {
280 self.check_method_call(expr, segment, span, args, expected)
282 ExprKind::Cast(ref e, ref t) => self.check_expr_cast(e, t, expr),
283 ExprKind::Type(ref e, ref t) => {
284 let ty = self.to_ty_saving_user_provided_ty(&t);
285 self.check_expr_eq_type(&e, ty);
288 ExprKind::DropTemps(ref e) => self.check_expr_with_expectation(e, expected),
289 ExprKind::Array(ref args) => self.check_expr_array(args, expected, expr),
290 ExprKind::ConstBlock(ref anon_const) => self.to_const(anon_const).ty,
291 ExprKind::Repeat(ref element, ref count) => {
292 self.check_expr_repeat(element, count, expected, expr)
294 ExprKind::Tup(ref elts) => self.check_expr_tuple(elts, expected, expr),
295 ExprKind::Struct(ref qpath, fields, ref base_expr) => {
296 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
298 ExprKind::Field(ref base, field) => self.check_field(expr, &base, field),
299 ExprKind::Index(ref base, ref idx) => self.check_expr_index(base, idx, expr),
300 ExprKind::Yield(ref value, ref src) => self.check_expr_yield(value, expr, src),
301 hir::ExprKind::Err => tcx.ty_error(),
305 fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
306 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind() {
307 ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
310 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
311 self.tcx.mk_box(referent_ty)
317 oprnd: &'tcx hir::Expr<'tcx>,
318 expected: Expectation<'tcx>,
319 expr: &'tcx hir::Expr<'tcx>,
322 let expected_inner = match unop {
323 hir::UnOp::UnNot | hir::UnOp::UnNeg => expected,
324 hir::UnOp::UnDeref => NoExpectation,
326 let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner);
328 if !oprnd_t.references_error() {
329 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
331 hir::UnOp::UnDeref => {
332 if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
335 let mut err = type_error_struct!(
340 "type `{}` cannot be dereferenced",
343 let sp = tcx.sess.source_map().start_point(expr.span);
345 tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
347 tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp, None);
350 oprnd_t = tcx.ty_error();
353 hir::UnOp::UnNot => {
354 let result = self.check_user_unop(expr, oprnd_t, unop);
355 // If it's builtin, we can reuse the type, this helps inference.
356 if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) {
360 hir::UnOp::UnNeg => {
361 let result = self.check_user_unop(expr, oprnd_t, unop);
362 // If it's builtin, we can reuse the type, this helps inference.
363 if !oprnd_t.is_numeric() {
372 fn check_expr_addr_of(
374 kind: hir::BorrowKind,
375 mutbl: hir::Mutability,
376 oprnd: &'tcx hir::Expr<'tcx>,
377 expected: Expectation<'tcx>,
378 expr: &'tcx hir::Expr<'tcx>,
380 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
382 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
383 if oprnd.is_syntactic_place_expr() {
384 // Places may legitimately have unsized types.
385 // For example, dereferences of a fat pointer and
386 // the last field of a struct can be unsized.
389 Expectation::rvalue_hint(self, ty)
396 self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl));
398 let tm = ty::TypeAndMut { ty, mutbl };
400 _ if tm.ty.references_error() => self.tcx.ty_error(),
401 hir::BorrowKind::Raw => {
402 self.check_named_place_expr(oprnd);
405 hir::BorrowKind::Ref => {
406 // Note: at this point, we cannot say what the best lifetime
407 // is to use for resulting pointer. We want to use the
408 // shortest lifetime possible so as to avoid spurious borrowck
409 // errors. Moreover, the longest lifetime will depend on the
410 // precise details of the value whose address is being taken
411 // (and how long it is valid), which we don't know yet until
412 // type inference is complete.
414 // Therefore, here we simply generate a region variable. The
415 // region inferencer will then select a suitable value.
416 // Finally, borrowck will infer the value of the region again,
417 // this time with enough precision to check that the value
418 // whose address was taken can actually be made to live as long
419 // as it needs to live.
420 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
421 self.tcx.mk_ref(region, tm)
426 /// Does this expression refer to a place that either:
427 /// * Is based on a local or static.
428 /// * Contains a dereference
429 /// Note that the adjustments for the children of `expr` should already
430 /// have been resolved.
431 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
432 let is_named = oprnd.is_place_expr(|base| {
433 // Allow raw borrows if there are any deref adjustments.
435 // const VAL: (i32,) = (0,);
436 // const REF: &(i32,) = &(0,);
438 // &raw const VAL.0; // ERROR
439 // &raw const REF.0; // OK, same as &raw const (*REF).0;
441 // This is maybe too permissive, since it allows
442 // `let u = &raw const Box::new((1,)).0`, which creates an
443 // immediately dangling raw pointer.
448 .map_or(false, |x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
451 self.tcx.sess.emit_err(AddressOfTemporaryTaken { span: oprnd.span })
455 fn check_lang_item_path(
457 lang_item: hir::LangItem,
458 expr: &'tcx hir::Expr<'tcx>,
460 self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id).1
463 fn check_expr_path(&self, qpath: &hir::QPath<'_>, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
465 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
468 self.set_tainted_by_errors();
471 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
472 report_unexpected_variant_res(tcx, res, expr.span);
475 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
478 if let ty::FnDef(..) = ty.kind() {
479 let fn_sig = ty.fn_sig(tcx);
480 if !tcx.features().unsized_fn_params {
481 // We want to remove some Sized bounds from std functions,
482 // but don't want to expose the removal to stable Rust.
483 // i.e., we don't want to allow
489 // to work in stable even if the Sized bound on `drop` is relaxed.
490 for i in 0..fn_sig.inputs().skip_binder().len() {
491 // We just want to check sizedness, so instead of introducing
492 // placeholder lifetimes with probing, we just replace higher lifetimes
495 .replace_bound_vars_with_fresh_vars(
497 infer::LateBoundRegionConversionTime::FnCall,
501 self.require_type_is_sized_deferred(
504 traits::SizedArgumentType(None),
508 // Here we want to prevent struct constructors from returning unsized types.
509 // There were two cases this happened: fn pointer coercion in stable
510 // and usual function call in presence of unsized_locals.
511 // Also, as we just want to check sizedness, instead of introducing
512 // placeholder lifetimes with probing, we just replace higher lifetimes
515 .replace_bound_vars_with_fresh_vars(
517 infer::LateBoundRegionConversionTime::FnCall,
521 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
524 // We always require that the type provided as the value for
525 // a type parameter outlives the moment of instantiation.
526 let substs = self.typeck_results.borrow().node_substs(expr.hir_id);
527 self.add_wf_bounds(substs, expr);
534 destination: hir::Destination,
535 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
536 expr: &'tcx hir::Expr<'tcx>,
539 if let Ok(target_id) = destination.target_id {
541 if let Some(ref e) = expr_opt {
542 // If this is a break with a value, we need to type-check
543 // the expression. Get an expected type from the loop context.
544 let opt_coerce_to = {
545 // We should release `enclosing_breakables` before the `check_expr_with_hint`
546 // below, so can't move this block of code to the enclosing scope and share
547 // `ctxt` with the second `encloding_breakables` borrow below.
548 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
549 match enclosing_breakables.opt_find_breakable(target_id) {
550 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
552 // Avoid ICE when `break` is inside a closure (#65383).
553 return tcx.ty_error_with_message(
555 "break was outside loop, but no error was emitted",
561 // If the loop context is not a `loop { }`, then break with
562 // a value is illegal, and `opt_coerce_to` will be `None`.
563 // Just set expectation to error in that case.
564 let coerce_to = opt_coerce_to.unwrap_or_else(|| tcx.ty_error());
566 // Recurse without `enclosing_breakables` borrowed.
567 e_ty = self.check_expr_with_hint(e, coerce_to);
568 cause = self.misc(e.span);
570 // Otherwise, this is a break *without* a value. That's
571 // always legal, and is equivalent to `break ()`.
572 e_ty = tcx.mk_unit();
573 cause = self.misc(expr.span);
576 // Now that we have type-checked `expr_opt`, borrow
577 // the `enclosing_loops` field and let's coerce the
578 // type of `expr_opt` into what is expected.
579 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
580 let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
583 // Avoid ICE when `break` is inside a closure (#65383).
584 return tcx.ty_error_with_message(
586 "break was outside loop, but no error was emitted",
591 if let Some(ref mut coerce) = ctxt.coerce {
592 if let Some(ref e) = expr_opt {
593 coerce.coerce(self, &cause, e, e_ty);
595 assert!(e_ty.is_unit());
596 let ty = coerce.expected_ty();
597 coerce.coerce_forced_unit(
601 self.suggest_mismatched_types_on_tail(
602 &mut err, expr, ty, e_ty, cause.span, target_id,
604 if let Some(val) = ty_kind_suggestion(ty) {
605 let label = destination
607 .map(|l| format!(" {}", l.ident))
608 .unwrap_or_else(String::new);
611 "give it a value of the expected type",
612 format!("break{} {}", label, val),
613 Applicability::HasPlaceholders,
621 // If `ctxt.coerce` is `None`, we can just ignore
622 // the type of the expression. This is because
623 // either this was a break *without* a value, in
624 // which case it is always a legal type (`()`), or
625 // else an error would have been flagged by the
626 // `loops` pass for using break with an expression
627 // where you are not supposed to.
628 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
631 // If we encountered a `break`, then (no surprise) it may be possible to break from the
632 // loop... unless the value being returned from the loop diverges itself, e.g.
633 // `break return 5` or `break loop {}`.
634 ctxt.may_break |= !self.diverges.get().is_always();
636 // the type of a `break` is always `!`, since it diverges
639 // Otherwise, we failed to find the enclosing loop;
640 // this can only happen if the `break` was not
641 // inside a loop at all, which is caught by the
642 // loop-checking pass.
643 let err = self.tcx.ty_error_with_message(
645 "break was outside loop, but no error was emitted",
648 // We still need to assign a type to the inner expression to
649 // prevent the ICE in #43162.
650 if let Some(ref e) = expr_opt {
651 self.check_expr_with_hint(e, err);
653 // ... except when we try to 'break rust;'.
654 // ICE this expression in particular (see #43162).
655 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
656 if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
657 fatally_break_rust(self.tcx.sess);
662 // There was an error; make type-check fail.
667 fn check_expr_return(
669 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
670 expr: &'tcx hir::Expr<'tcx>,
672 if self.ret_coercion.is_none() {
673 self.tcx.sess.emit_err(ReturnStmtOutsideOfFnBody { span: expr.span });
674 } else if let Some(ref e) = expr_opt {
675 if self.ret_coercion_span.borrow().is_none() {
676 *self.ret_coercion_span.borrow_mut() = Some(e.span);
678 self.check_return_expr(e);
680 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
681 if self.ret_coercion_span.borrow().is_none() {
682 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
684 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
685 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
686 coercion.coerce_forced_unit(
690 let span = fn_decl.output.span();
691 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
694 format!("expected `{}` because of this return type", snippet),
701 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
707 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr<'tcx>) {
708 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
709 span_bug!(return_expr.span, "check_return_expr called outside fn body")
712 let ret_ty = ret_coercion.borrow().expected_ty();
713 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
714 ret_coercion.borrow_mut().coerce(
716 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
722 pub(crate) fn check_lhs_assignable(
724 lhs: &'tcx hir::Expr<'tcx>,
725 err_code: &'static str,
728 if lhs.is_syntactic_place_expr() {
732 // FIXME: Make this use SessionDiagnostic once error codes can be dynamically set.
733 let mut err = self.tcx.sess.struct_span_err_with_code(
735 "invalid left-hand side of assignment",
736 DiagnosticId::Error(err_code.into()),
738 err.span_label(lhs.span, "cannot assign to this expression");
742 /// Type check assignment expression `expr` of form `lhs = rhs`.
743 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
744 fn check_expr_assign(
746 expr: &'tcx hir::Expr<'tcx>,
747 expected: Expectation<'tcx>,
748 lhs: &'tcx hir::Expr<'tcx>,
749 rhs: &'tcx hir::Expr<'tcx>,
752 let expected_ty = expected.coercion_target_type(self, expr.span);
753 if expected_ty == self.tcx.types.bool {
754 // The expected type is `bool` but this will result in `()` so we can reasonably
755 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
756 // The likely cause of this is `if foo = bar { .. }`.
757 let actual_ty = self.tcx.mk_unit();
758 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
759 let lhs_ty = self.check_expr(&lhs);
760 let rhs_ty = self.check_expr(&rhs);
761 let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) {
762 (Applicability::MachineApplicable, true)
764 (Applicability::MaybeIncorrect, false)
766 if !lhs.is_syntactic_place_expr() {
767 // Do not suggest `if let x = y` as `==` is way more likely to be the intention.
768 if let hir::Node::Expr(hir::Expr {
773 hir::MatchSource::IfDesugar { .. } | hir::MatchSource::WhileDesugar,
776 }) = self.tcx.hir().get(
777 self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(expr.hir_id)),
779 // Likely `if let` intended.
780 err.span_suggestion_verbose(
781 expr.span.shrink_to_lo(),
782 "you might have meant to use pattern matching",
789 err.span_suggestion_verbose(
791 "you might have meant to compare for equality",
797 if self.sess().if_let_suggestions.borrow().get(&expr.span).is_some() {
798 // We already emitted an `if let` suggestion due to an identifier not found.
803 return self.tcx.ty_error();
806 self.check_lhs_assignable(lhs, "E0070", span);
808 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
809 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs));
811 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
813 if lhs_ty.references_error() || rhs_ty.references_error() {
822 body: &'tcx hir::Block<'tcx>,
823 source: hir::LoopSource,
824 expected: Expectation<'tcx>,
825 expr: &'tcx hir::Expr<'tcx>,
827 let coerce = match source {
828 // you can only use break with a value from a normal `loop { }`
829 hir::LoopSource::Loop => {
830 let coerce_to = expected.coercion_target_type(self, body.span);
831 Some(CoerceMany::new(coerce_to))
834 hir::LoopSource::While | hir::LoopSource::WhileLet | hir::LoopSource::ForLoop => None,
837 let ctxt = BreakableCtxt {
839 may_break: false, // Will get updated if/when we find a `break`.
842 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
843 self.check_block_no_value(&body);
847 // No way to know whether it's diverging because
848 // of a `break` or an outer `break` or `return`.
849 self.diverges.set(Diverges::Maybe);
852 // If we permit break with a value, then result type is
853 // the LUB of the breaks (possibly ! if none); else, it
854 // is nil. This makes sense because infinite loops
855 // (which would have type !) are only possible iff we
856 // permit break with a value [1].
857 if ctxt.coerce.is_none() && !ctxt.may_break {
859 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
861 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
864 /// Checks a method call.
865 fn check_method_call(
867 expr: &'tcx hir::Expr<'tcx>,
868 segment: &hir::PathSegment<'_>,
870 args: &'tcx [hir::Expr<'tcx>],
871 expected: Expectation<'tcx>,
874 let rcvr_t = self.check_expr(&rcvr);
875 // no need to check for bot/err -- callee does that
876 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
878 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
880 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
881 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
883 self.write_method_call(expr.hir_id, method);
887 if segment.ident.name != kw::Empty {
888 self.report_extended_method_error(segment, span, args, rcvr_t, error);
894 // Call the generic checker.
895 self.check_method_argument_types(
905 fn report_extended_method_error(
907 segment: &hir::PathSegment<'_>,
909 args: &'tcx [hir::Expr<'tcx>],
911 error: MethodError<'tcx>,
914 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, new_rcvr_t| {
915 if let Some(new_rcvr_t) = new_rcvr_t {
916 if let Ok(pick) = self.lookup_probe(
921 probe::ProbeScope::AllTraits,
923 debug!("try_alt_rcvr: pick candidate {:?}", pick);
924 // Make sure the method is defined for the *actual* receiver:
925 // we don't want to treat `Box<Self>` as a receiver if
926 // it only works because of an autoderef to `&self`
927 if pick.autoderefs == 0 {
929 pick.item.ident.span,
930 &format!("the method is available for `{}` here", new_rcvr_t),
937 if let Some(mut err) = self.report_method_error(
941 SelfSource::MethodCall(rcvr),
945 if let ty::Adt(..) = rcvr_t.kind() {
946 // Try alternative arbitrary self types that could fulfill this call.
947 // FIXME: probe for all types that *could* be arbitrary self-types, not
949 try_alt_rcvr(&mut err, self.tcx.mk_lang_item(rcvr_t, LangItem::OwnedBox));
950 try_alt_rcvr(&mut err, self.tcx.mk_lang_item(rcvr_t, LangItem::Pin));
951 try_alt_rcvr(&mut err, self.tcx.mk_diagnostic_item(rcvr_t, sym::Arc));
952 try_alt_rcvr(&mut err, self.tcx.mk_diagnostic_item(rcvr_t, sym::Rc));
960 e: &'tcx hir::Expr<'tcx>,
961 t: &'tcx hir::Ty<'tcx>,
962 expr: &'tcx hir::Expr<'tcx>,
964 // Find the type of `e`. Supply hints based on the type we are casting to,
966 let t_cast = self.to_ty_saving_user_provided_ty(t);
967 let t_cast = self.resolve_vars_if_possible(t_cast);
968 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
969 let t_cast = self.resolve_vars_if_possible(t_cast);
971 // Eagerly check for some obvious errors.
972 if t_expr.references_error() || t_cast.references_error() {
975 // Defer other checks until we're done type checking.
976 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
977 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
979 deferred_cast_checks.push(cast_check);
982 Err(ErrorReported) => self.tcx.ty_error(),
989 args: &'tcx [hir::Expr<'tcx>],
990 expected: Expectation<'tcx>,
991 expr: &'tcx hir::Expr<'tcx>,
993 let element_ty = if !args.is_empty() {
994 let coerce_to = expected
996 .and_then(|uty| match *uty.kind() {
997 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1000 .unwrap_or_else(|| {
1001 self.next_ty_var(TypeVariableOrigin {
1002 kind: TypeVariableOriginKind::TypeInference,
1006 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1007 assert_eq!(self.diverges.get(), Diverges::Maybe);
1009 let e_ty = self.check_expr_with_hint(e, coerce_to);
1010 let cause = self.misc(e.span);
1011 coerce.coerce(self, &cause, e, e_ty);
1013 coerce.complete(self)
1015 self.next_ty_var(TypeVariableOrigin {
1016 kind: TypeVariableOriginKind::TypeInference,
1020 self.tcx.mk_array(element_ty, args.len() as u64)
1023 fn check_expr_repeat(
1025 element: &'tcx hir::Expr<'tcx>,
1026 count: &'tcx hir::AnonConst,
1027 expected: Expectation<'tcx>,
1028 _expr: &'tcx hir::Expr<'tcx>,
1031 let count = self.to_const(count);
1033 let uty = match expected {
1034 ExpectHasType(uty) => match *uty.kind() {
1035 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1041 let (element_ty, t) = match uty {
1043 self.check_expr_coercable_to_type(&element, uty, None);
1047 let ty = self.next_ty_var(TypeVariableOrigin {
1048 kind: TypeVariableOriginKind::MiscVariable,
1051 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1056 if element_ty.references_error() {
1057 return tcx.ty_error();
1060 tcx.mk_ty(ty::Array(t, count))
1063 fn check_expr_tuple(
1065 elts: &'tcx [hir::Expr<'tcx>],
1066 expected: Expectation<'tcx>,
1067 expr: &'tcx hir::Expr<'tcx>,
1069 let flds = expected.only_has_type(self).and_then(|ty| {
1070 let ty = self.resolve_vars_with_obligations(ty);
1072 ty::Tuple(ref flds) => Some(&flds[..]),
1077 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1078 Some(ref fs) if i < fs.len() => {
1079 let ety = fs[i].expect_ty();
1080 self.check_expr_coercable_to_type(&e, ety, None);
1083 _ => self.check_expr_with_expectation(&e, NoExpectation),
1085 let tuple = self.tcx.mk_tup(elt_ts_iter);
1086 if tuple.references_error() {
1089 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1094 fn check_expr_struct(
1096 expr: &hir::Expr<'_>,
1097 expected: Expectation<'tcx>,
1099 fields: &'tcx [hir::Field<'tcx>],
1100 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1102 // Find the relevant variant
1103 let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id)
1107 self.check_struct_fields_on_error(fields, base_expr);
1108 return self.tcx.ty_error();
1111 // Prohibit struct expressions when non-exhaustive flag is set.
1112 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1113 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1116 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1119 let error_happened = self.check_expr_struct_fields(
1126 base_expr.is_none(),
1128 if let &Some(ref base_expr) = base_expr {
1129 // If check_expr_struct_fields hit an error, do not attempt to populate
1130 // the fields with the base_expr. This could cause us to hit errors later
1131 // when certain fields are assumed to exist that in fact do not.
1132 if !error_happened {
1133 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1134 match adt_ty.kind() {
1135 ty::Adt(adt, substs) if adt.is_struct() => {
1136 let fru_field_types = adt
1141 self.normalize_associated_types_in(
1143 f.ty(self.tcx, substs),
1150 .fru_field_types_mut()
1151 .insert(expr.hir_id, fru_field_types);
1156 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
1161 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1165 fn check_expr_struct_fields(
1168 expected: Expectation<'tcx>,
1169 expr_id: hir::HirId,
1171 variant: &'tcx ty::VariantDef,
1172 ast_fields: &'tcx [hir::Field<'tcx>],
1173 check_completeness: bool,
1177 let adt_ty_hint = self
1178 .expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1182 // re-link the regions that EIfEO can erase.
1183 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1185 let (substs, adt_kind, kind_name) = match &adt_ty.kind() {
1186 &ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()),
1187 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"),
1190 let mut remaining_fields = variant
1194 .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
1195 .collect::<FxHashMap<_, _>>();
1197 let mut seen_fields = FxHashMap::default();
1199 let mut error_happened = false;
1201 // Type-check each field.
1202 for field in ast_fields {
1203 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1204 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1205 seen_fields.insert(ident, field.span);
1206 self.write_field_index(field.hir_id, i);
1208 // We don't look at stability attributes on
1209 // struct-like enums (yet...), but it's definitely not
1210 // a bug to have constructed one.
1211 if adt_kind != AdtKind::Enum {
1212 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1215 self.field_ty(field.span, v_field, substs)
1217 error_happened = true;
1218 if let Some(prev_span) = seen_fields.get(&ident) {
1219 tcx.sess.emit_err(FieldMultiplySpecifiedInInitializer {
1220 span: field.ident.span,
1221 prev_span: *prev_span,
1225 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1231 // Make sure to give a type to the field even if there's
1232 // an error, so we can continue type-checking.
1233 self.check_expr_coercable_to_type(&field.expr, field_type, None);
1236 // Make sure the programmer specified correct number of fields.
1237 if kind_name == "union" {
1238 if ast_fields.len() != 1 {
1239 tcx.sess.span_err(span, "union expressions should have exactly one field");
1241 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1242 let no_accessible_remaining_fields = remaining_fields
1244 .find(|(_, (_, field))| {
1245 field.vis.is_accessible_from(tcx.parent_module(expr_id).to_def_id(), tcx)
1249 if no_accessible_remaining_fields {
1250 self.report_no_accessible_fields(adt_ty, span);
1252 self.report_missing_fields(adt_ty, span, remaining_fields);
1259 fn check_struct_fields_on_error(
1261 fields: &'tcx [hir::Field<'tcx>],
1262 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1264 for field in fields {
1265 self.check_expr(&field.expr);
1267 if let Some(ref base) = *base_expr {
1268 self.check_expr(&base);
1272 /// Report an error for a struct field expression when there are fields which aren't provided.
1275 /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
1276 /// --> src/main.rs:8:5
1278 /// 8 | foo::Foo {};
1279 /// | ^^^^^^^^ missing `you_can_use_this_field`
1281 /// error: aborting due to previous error
1283 fn report_missing_fields(
1287 remaining_fields: FxHashMap<Ident, (usize, &ty::FieldDef)>,
1290 let len = remaining_fields.len();
1292 let mut displayable_field_names =
1293 remaining_fields.keys().map(|ident| ident.as_str()).collect::<Vec<_>>();
1295 displayable_field_names.sort();
1297 let truncated_fields_error = if len <= 3 {
1300 format!(" and {} other field{}", (len - 3), if len - 3 == 1 { "" } else { "s" })
1303 let remaining_fields_names = displayable_field_names
1306 .map(|n| format!("`{}`", n))
1307 .collect::<Vec<_>>()
1314 "missing field{} {}{} in initializer of `{}`",
1315 pluralize!(remaining_fields.len()),
1316 remaining_fields_names,
1317 truncated_fields_error,
1320 .span_label(span, format!("missing {}{}", remaining_fields_names, truncated_fields_error))
1324 /// Report an error for a struct field expression when there are no visible fields.
1327 /// error: cannot construct `Foo` with struct literal syntax due to inaccessible fields
1328 /// --> src/main.rs:8:5
1330 /// 8 | foo::Foo {};
1333 /// error: aborting due to previous error
1335 fn report_no_accessible_fields(&self, adt_ty: Ty<'tcx>, span: Span) {
1336 self.tcx.sess.span_err(
1339 "cannot construct `{}` with struct literal syntax due to inaccessible fields",
1345 fn report_unknown_field(
1348 variant: &'tcx ty::VariantDef,
1349 field: &hir::Field<'_>,
1350 skip_fields: &[hir::Field<'_>],
1354 if variant.is_recovered() {
1355 self.set_tainted_by_errors();
1358 let mut err = self.type_error_struct_with_diag(
1360 |actual| match ty.kind() {
1361 ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
1365 "{} `{}::{}` has no field named `{}`",
1371 _ => struct_span_err!(
1375 "{} `{}` has no field named `{}`",
1383 match variant.ctor_kind {
1384 CtorKind::Fn => match ty.kind() {
1385 ty::Adt(adt, ..) if adt.is_enum() => {
1389 "`{adt}::{variant}` defined here",
1391 variant = variant.ident,
1394 err.span_label(field.ident.span, "field does not exist");
1398 "`{adt}::{variant}` is a tuple {kind_name}, \
1399 use the appropriate syntax: `{adt}::{variant}(/* fields */)`",
1401 variant = variant.ident,
1402 kind_name = kind_name
1407 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt = ty));
1408 err.span_label(field.ident.span, "field does not exist");
1412 "`{adt}` is a tuple {kind_name}, \
1413 use the appropriate syntax: `{adt}(/* fields */)`",
1415 kind_name = kind_name
1421 // prevent all specified fields from being suggested
1422 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1423 if let Some(field_name) =
1424 Self::suggest_field_name(variant, field.ident.name, skip_fields.collect())
1426 err.span_suggestion(
1428 "a field with a similar name exists",
1429 field_name.to_string(),
1430 Applicability::MaybeIncorrect,
1434 ty::Adt(adt, ..) => {
1438 format!("`{}::{}` does not have this field", ty, variant.ident),
1443 format!("`{}` does not have this field", ty),
1446 let available_field_names = self.available_field_names(variant);
1447 if !available_field_names.is_empty() {
1449 "available fields are: {}",
1450 self.name_series_display(available_field_names)
1454 _ => bug!("non-ADT passed to report_unknown_field"),
1462 // Return an hint about the closest match in field names
1463 fn suggest_field_name(
1464 variant: &'tcx ty::VariantDef,
1467 ) -> Option<Symbol> {
1471 .filter_map(|field| {
1472 // ignore already set fields and private fields from non-local crates
1473 if skip.iter().any(|&x| x == field.ident.name)
1474 || (!variant.def_id.is_local() && field.vis != Visibility::Public)
1478 Some(field.ident.name)
1481 .collect::<Vec<Symbol>>();
1483 find_best_match_for_name(&names, field, None)
1486 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<Symbol> {
1491 let def_scope = self
1493 .adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id)
1495 field.vis.is_accessible_from(def_scope, self.tcx)
1497 .map(|field| field.ident.name)
1501 fn name_series_display(&self, names: Vec<Symbol>) -> String {
1502 // dynamic limit, to never omit just one field
1503 let limit = if names.len() == 6 { 6 } else { 5 };
1505 names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1506 if names.len() > limit {
1507 display = format!("{} ... and {} others", display, names.len() - limit);
1512 // Check field access expressions
1515 expr: &'tcx hir::Expr<'tcx>,
1516 base: &'tcx hir::Expr<'tcx>,
1519 let expr_t = self.check_expr(base);
1520 let expr_t = self.structurally_resolved_type(base.span, expr_t);
1521 let mut private_candidate = None;
1522 let mut autoderef = self.autoderef(expr.span, expr_t);
1523 while let Some((base_t, _)) = autoderef.next() {
1524 match base_t.kind() {
1525 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1526 debug!("struct named {:?}", base_t);
1527 let (ident, def_scope) =
1528 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1529 let fields = &base_def.non_enum_variant().fields;
1530 if let Some(index) =
1531 fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident)
1533 let field = &fields[index];
1534 let field_ty = self.field_ty(expr.span, field, substs);
1535 // Save the index of all fields regardless of their visibility in case
1536 // of error recovery.
1537 self.write_field_index(expr.hir_id, index);
1538 if field.vis.is_accessible_from(def_scope, self.tcx) {
1539 let adjustments = self.adjust_steps(&autoderef);
1540 self.apply_adjustments(base, adjustments);
1541 self.register_predicates(autoderef.into_obligations());
1543 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1546 private_candidate = Some((base_def.did, field_ty));
1549 ty::Tuple(ref tys) => {
1550 let fstr = field.as_str();
1551 if let Ok(index) = fstr.parse::<usize>() {
1552 if fstr == index.to_string() {
1553 if let Some(field_ty) = tys.get(index) {
1554 let adjustments = self.adjust_steps(&autoderef);
1555 self.apply_adjustments(base, adjustments);
1556 self.register_predicates(autoderef.into_obligations());
1558 self.write_field_index(expr.hir_id, index);
1559 return field_ty.expect_ty();
1567 self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
1569 if let Some((did, field_ty)) = private_candidate {
1570 self.ban_private_field_access(expr, expr_t, field, did);
1574 if field.name == kw::Empty {
1575 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1576 self.ban_take_value_of_method(expr, expr_t, field);
1577 } else if !expr_t.is_primitive_ty() {
1578 self.ban_nonexisting_field(field, base, expr, expr_t);
1585 "`{}` is a primitive type and therefore doesn't have fields",
1591 self.tcx().ty_error()
1594 fn suggest_await_on_field_access(
1596 err: &mut DiagnosticBuilder<'_>,
1598 base: &'tcx hir::Expr<'tcx>,
1601 let output_ty = match self.infcx.get_impl_future_output_ty(ty) {
1602 Some(output_ty) => self.resolve_vars_if_possible(output_ty),
1605 let mut add_label = true;
1606 if let ty::Adt(def, _) = output_ty.kind() {
1607 // no field access on enum type
1609 if def.non_enum_variant().fields.iter().any(|field| field.ident == field_ident) {
1613 "field not available in `impl Future`, but it is available in its `Output`",
1615 err.span_suggestion_verbose(
1616 base.span.shrink_to_hi(),
1617 "consider `await`ing on the `Future` and access the field of its `Output`",
1618 ".await".to_string(),
1619 Applicability::MaybeIncorrect,
1625 err.span_label(field_ident.span, &format!("field not found in `{}`", ty));
1629 fn ban_nonexisting_field(
1632 base: &'tcx hir::Expr<'tcx>,
1633 expr: &'tcx hir::Expr<'tcx>,
1637 "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, expr_ty={:?}",
1638 field, base, expr, expr_t
1640 let mut err = self.no_such_field_err(field.span, field, expr_t);
1642 match *expr_t.peel_refs().kind() {
1643 ty::Array(_, len) => {
1644 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1647 self.suggest_first_deref_field(&mut err, expr, base, field);
1649 ty::Adt(def, _) if !def.is_enum() => {
1650 self.suggest_fields_on_recordish(&mut err, def, field);
1652 ty::Param(param_ty) => {
1653 self.point_at_param_definition(&mut err, param_ty);
1655 ty::Opaque(_, _) => {
1656 self.suggest_await_on_field_access(&mut err, field, base, expr_t.peel_refs());
1661 if field.name == kw::Await {
1662 // We know by construction that `<expr>.await` is either on Rust 2015
1663 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1664 err.note("to `.await` a `Future`, switch to Rust 2018 or later");
1665 err.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
1666 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1672 fn ban_private_field_access(
1674 expr: &hir::Expr<'_>,
1679 let struct_path = self.tcx().def_path_str(base_did);
1680 let kind_name = self.tcx().def_kind(base_did).descr(base_did);
1681 let mut err = struct_span_err!(
1685 "field `{}` of {} `{}` is private",
1690 err.span_label(field.span, "private field");
1691 // Also check if an accessible method exists, which is often what is meant.
1692 if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
1694 self.suggest_method_call(
1696 &format!("a method `{}` also exists, call it with parentheses", field),
1705 fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: Ident) {
1706 let mut err = type_error_struct!(
1711 "attempted to take value of method `{}` on type `{}`",
1715 err.span_label(field.span, "method, not a field");
1716 if !self.expr_in_place(expr.hir_id) {
1717 self.suggest_method_call(
1719 "use parentheses to call the method",
1725 err.help("methods are immutable and cannot be assigned to");
1731 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1732 let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
1733 let generic_param = generics.type_param(¶m, self.tcx);
1734 if let ty::GenericParamDefKind::Type { synthetic: Some(..), .. } = generic_param.kind {
1737 let param_def_id = generic_param.def_id;
1738 let param_hir_id = match param_def_id.as_local() {
1739 Some(x) => self.tcx.hir().local_def_id_to_hir_id(x),
1742 let param_span = self.tcx.hir().span(param_hir_id);
1743 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1745 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1748 fn suggest_fields_on_recordish(
1750 err: &mut DiagnosticBuilder<'_>,
1751 def: &'tcx ty::AdtDef,
1754 if let Some(suggested_field_name) =
1755 Self::suggest_field_name(def.non_enum_variant(), field.name, vec![])
1757 err.span_suggestion(
1759 "a field with a similar name exists",
1760 suggested_field_name.to_string(),
1761 Applicability::MaybeIncorrect,
1764 err.span_label(field.span, "unknown field");
1765 let struct_variant_def = def.non_enum_variant();
1766 let field_names = self.available_field_names(struct_variant_def);
1767 if !field_names.is_empty() {
1769 "available fields are: {}",
1770 self.name_series_display(field_names),
1776 fn maybe_suggest_array_indexing(
1778 err: &mut DiagnosticBuilder<'_>,
1779 expr: &hir::Expr<'_>,
1780 base: &hir::Expr<'_>,
1782 len: &ty::Const<'tcx>,
1784 if let (Some(len), Ok(user_index)) =
1785 (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
1787 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
1788 let help = "instead of using tuple indexing, use array indexing";
1789 let suggestion = format!("{}[{}]", base, field);
1790 let applicability = if len < user_index {
1791 Applicability::MachineApplicable
1793 Applicability::MaybeIncorrect
1795 err.span_suggestion(expr.span, help, suggestion, applicability);
1800 fn suggest_first_deref_field(
1802 err: &mut DiagnosticBuilder<'_>,
1803 expr: &hir::Expr<'_>,
1804 base: &hir::Expr<'_>,
1807 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
1808 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1809 let suggestion = format!("(*{}).{}", base, field);
1810 err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
1814 fn no_such_field_err<T: Display>(
1818 expr_t: &ty::TyS<'_>,
1819 ) -> DiagnosticBuilder<'_> {
1825 "no field `{}` on type `{}`",
1831 fn check_expr_index(
1833 base: &'tcx hir::Expr<'tcx>,
1834 idx: &'tcx hir::Expr<'tcx>,
1835 expr: &'tcx hir::Expr<'tcx>,
1837 let base_t = self.check_expr(&base);
1838 let idx_t = self.check_expr(&idx);
1840 if base_t.references_error() {
1842 } else if idx_t.references_error() {
1845 let base_t = self.structurally_resolved_type(base.span, base_t);
1846 match self.lookup_indexing(expr, base, base_t, idx_t) {
1847 Some((index_ty, element_ty)) => {
1848 // two-phase not needed because index_ty is never mutable
1849 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
1853 let mut err = type_error_struct!(
1858 "cannot index into a value of type `{}`",
1861 // Try to give some advice about indexing tuples.
1862 if let ty::Tuple(..) = base_t.kind() {
1863 let mut needs_note = true;
1864 // If the index is an integer, we can show the actual
1865 // fixed expression:
1866 if let ExprKind::Lit(ref lit) = idx.kind {
1867 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1868 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1869 if let Ok(snip) = snip {
1870 err.span_suggestion(
1872 "to access tuple elements, use",
1873 format!("{}.{}", snip, i),
1874 Applicability::MachineApplicable,
1882 "to access tuple elements, use tuple indexing \
1883 syntax (e.g., `tuple.0`)",
1894 fn check_expr_yield(
1896 value: &'tcx hir::Expr<'tcx>,
1897 expr: &'tcx hir::Expr<'tcx>,
1898 src: &'tcx hir::YieldSource,
1900 match self.resume_yield_tys {
1901 Some((resume_ty, yield_ty)) => {
1902 self.check_expr_coercable_to_type(&value, yield_ty, None);
1906 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1907 // we know that the yield type must be `()`; however, the context won't contain this
1908 // information. Hence, we check the source of the yield expression here and check its
1909 // value's type against `()` (this check should always hold).
1910 None if src.is_await() => {
1911 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit(), None);
1915 self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr.span });
1921 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
1922 let needs = if is_input { Needs::None } else { Needs::MutPlace };
1923 let ty = self.check_expr_with_needs(expr, needs);
1924 self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
1926 if !is_input && !expr.is_syntactic_place_expr() {
1927 let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output");
1928 err.span_label(expr.span, "cannot assign to this expression");
1932 // If this is an input value, we require its type to be fully resolved
1933 // at this point. This allows us to provide helpful coercions which help
1934 // pass the type candidate list in a later pass.
1936 // We don't require output types to be resolved at this point, which
1937 // allows them to be inferred based on how they are used later in the
1940 let ty = self.structurally_resolved_type(expr.span, &ty);
1943 let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx));
1944 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
1946 ty::Ref(_, base_ty, mutbl) => {
1947 let ptr_ty = self.tcx.mk_ptr(ty::TypeAndMut { ty: base_ty, mutbl });
1948 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
1955 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
1956 for (op, _op_sp) in asm.operands {
1958 hir::InlineAsmOperand::In { expr, .. } | hir::InlineAsmOperand::Const { expr } => {
1959 self.check_expr_asm_operand(expr, true);
1961 hir::InlineAsmOperand::Out { expr, .. } => {
1962 if let Some(expr) = expr {
1963 self.check_expr_asm_operand(expr, false);
1966 hir::InlineAsmOperand::InOut { expr, .. } => {
1967 self.check_expr_asm_operand(expr, false);
1969 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1970 self.check_expr_asm_operand(in_expr, true);
1971 if let Some(out_expr) = out_expr {
1972 self.check_expr_asm_operand(out_expr, false);
1975 hir::InlineAsmOperand::Sym { expr } => {
1976 self.check_expr(expr);
1980 if asm.options.contains(ast::InlineAsmOptions::NORETURN) {
1981 self.tcx.types.never
1988 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1989 Some(match ty.kind() {
1992 ty::Int(_) | ty::Uint(_) => "42",
1993 ty::Float(_) => "3.14159",
1994 ty::Error(_) | ty::Never => return None,