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;
17 use crate::type_error_struct;
20 use rustc_ast::util::lev_distance::find_best_match_for_name;
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_errors::ErrorReported;
23 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId};
25 use rustc_hir::def::{CtorKind, DefKind, Res};
26 use rustc_hir::def_id::DefId;
27 use rustc_hir::lang_items;
28 use rustc_hir::{ExprKind, QPath};
29 use rustc_infer::infer;
30 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
32 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
33 use rustc_middle::ty::Ty;
34 use rustc_middle::ty::TypeFoldable;
35 use rustc_middle::ty::{AdtKind, Visibility};
36 use rustc_span::hygiene::DesugaringKind;
37 use rustc_span::source_map::Span;
38 use rustc_span::symbol::{kw, sym, Ident, Symbol};
39 use rustc_trait_selection::traits::{self, ObligationCauseCode};
41 use std::fmt::Display;
43 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
44 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
45 let ty = self.check_expr_with_hint(expr, expected);
46 self.demand_eqtype(expr.span, expected, ty);
49 pub fn check_expr_has_type_or_error(
51 expr: &'tcx hir::Expr<'tcx>,
53 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
55 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
58 fn check_expr_meets_expectation_or_error(
60 expr: &'tcx hir::Expr<'tcx>,
61 expected: Expectation<'tcx>,
62 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
64 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
65 let mut ty = self.check_expr_with_expectation(expr, expected);
67 // While we don't allow *arbitrary* coercions here, we *do* allow
68 // coercions from ! to `expected`.
71 !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id),
72 "expression with never type wound up being adjusted"
74 let adj_ty = self.next_diverging_ty_var(TypeVariableOrigin {
75 kind: TypeVariableOriginKind::AdjustmentType,
78 self.apply_adjustments(
80 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
85 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
86 let expr = expr.peel_drop_temps();
87 self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None);
89 // Error possibly reported in `check_assign` so avoid emitting error again.
90 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
95 pub(super) fn check_expr_coercable_to_type(
97 expr: &'tcx hir::Expr<'tcx>,
99 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
101 let ty = self.check_expr_with_hint(expr, expected);
102 // checks don't need two phase
103 self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No)
106 pub(super) fn check_expr_with_hint(
108 expr: &'tcx hir::Expr<'tcx>,
111 self.check_expr_with_expectation(expr, ExpectHasType(expected))
114 fn check_expr_with_expectation_and_needs(
116 expr: &'tcx hir::Expr<'tcx>,
117 expected: Expectation<'tcx>,
120 let ty = self.check_expr_with_expectation(expr, expected);
122 // If the expression is used in a place whether mutable place is required
123 // e.g. LHS of assignment, perform the conversion.
124 if let Needs::MutPlace = needs {
125 self.convert_place_derefs_to_mutable(expr);
131 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
132 self.check_expr_with_expectation(expr, NoExpectation)
135 pub(super) fn check_expr_with_needs(
137 expr: &'tcx hir::Expr<'tcx>,
140 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
144 /// If an expression has any sub-expressions that result in a type error,
145 /// inspecting that expression's type with `ty.references_error()` will return
146 /// true. Likewise, if an expression is known to diverge, inspecting its
147 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
148 /// strict, _|_ can appear in the type of an expression that does not,
149 /// itself, diverge: for example, fn() -> _|_.)
150 /// Note that inspecting a type's structure *directly* may expose the fact
151 /// that there are actually multiple representations for `Error`, so avoid
152 /// that when err needs to be handled differently.
153 pub(super) fn check_expr_with_expectation(
155 expr: &'tcx hir::Expr<'tcx>,
156 expected: Expectation<'tcx>,
158 debug!(">> type-checking: expr={:?} expected={:?}", expr, expected);
160 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
161 // without the final expr (e.g. `try { return; }`). We don't want to generate an
162 // unreachable_code lint for it since warnings for autogenerated code are confusing.
163 let is_try_block_generated_unit_expr = match expr.kind {
164 ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
165 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
171 // Warn for expressions after diverging siblings.
172 if !is_try_block_generated_unit_expr {
173 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
176 // Hide the outer diverging and has_errors flags.
177 let old_diverges = self.diverges.replace(Diverges::Maybe);
178 let old_has_errors = self.has_errors.replace(false);
180 let ty = self.check_expr_kind(expr, expected);
182 // Warn for non-block expressions with diverging children.
184 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {}
185 // If `expr` is a result of desugaring the try block and is an ok-wrapped
186 // diverging expression (e.g. it arose from desugaring of `try { return }`),
187 // we skip issuing a warning because it is autogenerated code.
188 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
189 ExprKind::Call(ref callee, _) => {
190 self.warn_if_unreachable(expr.hir_id, callee.span, "call")
192 ExprKind::MethodCall(_, ref span, _, _) => {
193 self.warn_if_unreachable(expr.hir_id, *span, "call")
195 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
198 // Any expression that produces a value of type `!` must have diverged
200 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
203 // Record the type, which applies it effects.
204 // We need to do this after the warning above, so that
205 // we don't warn for the diverging expression itself.
206 self.write_ty(expr.hir_id, ty);
208 // Combine the diverging and has_error flags.
209 self.diverges.set(self.diverges.get() | old_diverges);
210 self.has_errors.set(self.has_errors.get() | old_has_errors);
212 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
213 debug!("... {:?}, expected is {:?}", ty, expected);
220 expr: &'tcx hir::Expr<'tcx>,
221 expected: Expectation<'tcx>,
223 debug!("check_expr_kind(expr={:?}, expected={:?})", expr, expected);
227 ExprKind::Box(ref subexpr) => self.check_expr_box(subexpr, expected),
228 ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
229 ExprKind::Binary(op, ref lhs, ref rhs) => self.check_binop(expr, op, lhs, rhs),
230 ExprKind::Assign(ref lhs, ref rhs, ref span) => {
231 self.check_expr_assign(expr, expected, lhs, rhs, span)
233 ExprKind::AssignOp(op, ref lhs, ref rhs) => self.check_binop_assign(expr, op, lhs, rhs),
234 ExprKind::Unary(unop, ref oprnd) => self.check_expr_unary(unop, oprnd, expected, expr),
235 ExprKind::AddrOf(kind, mutbl, ref oprnd) => {
236 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
238 ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr),
239 ExprKind::InlineAsm(asm) => self.check_expr_asm(asm),
240 ExprKind::LlvmInlineAsm(ref asm) => {
241 for expr in asm.outputs_exprs.iter().chain(asm.inputs_exprs.iter()) {
242 self.check_expr(expr);
246 ExprKind::Break(destination, ref expr_opt) => {
247 self.check_expr_break(destination, expr_opt.as_deref(), expr)
249 ExprKind::Continue(destination) => {
250 if destination.target_id.is_ok() {
253 // There was an error; make type-check fail.
257 ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
258 ExprKind::Loop(ref body, _, source) => {
259 self.check_expr_loop(body, source, expected, expr)
261 ExprKind::Match(ref discrim, ref arms, match_src) => {
262 self.check_match(expr, &discrim, arms, expected, match_src)
264 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
265 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
267 ExprKind::Block(ref body, _) => self.check_block_with_expected(&body, expected),
268 ExprKind::Call(ref callee, ref args) => self.check_call(expr, &callee, args, expected),
269 ExprKind::MethodCall(ref segment, span, ref args, _) => {
270 self.check_method_call(expr, segment, span, args, expected)
272 ExprKind::Cast(ref e, ref t) => self.check_expr_cast(e, t, expr),
273 ExprKind::Type(ref e, ref t) => {
274 let ty = self.to_ty_saving_user_provided_ty(&t);
275 self.check_expr_eq_type(&e, ty);
278 ExprKind::DropTemps(ref e) => self.check_expr_with_expectation(e, expected),
279 ExprKind::Array(ref args) => self.check_expr_array(args, expected, expr),
280 ExprKind::Repeat(ref element, ref count) => {
281 self.check_expr_repeat(element, count, expected, expr)
283 ExprKind::Tup(ref elts) => self.check_expr_tuple(elts, expected, expr),
284 ExprKind::Struct(ref qpath, fields, ref base_expr) => {
285 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
287 ExprKind::Field(ref base, field) => self.check_field(expr, &base, field),
288 ExprKind::Index(ref base, ref idx) => self.check_expr_index(base, idx, expr),
289 ExprKind::Yield(ref value, ref src) => self.check_expr_yield(value, expr, src),
290 hir::ExprKind::Err => tcx.ty_error(),
294 fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
295 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind {
296 ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
299 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
300 self.tcx.mk_box(referent_ty)
306 oprnd: &'tcx hir::Expr<'tcx>,
307 expected: Expectation<'tcx>,
308 expr: &'tcx hir::Expr<'tcx>,
311 let expected_inner = match unop {
312 hir::UnOp::UnNot | hir::UnOp::UnNeg => expected,
313 hir::UnOp::UnDeref => NoExpectation,
315 let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner);
317 if !oprnd_t.references_error() {
318 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
320 hir::UnOp::UnDeref => {
321 if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
324 let mut err = type_error_struct!(
329 "type `{}` cannot be dereferenced",
332 let sp = tcx.sess.source_map().start_point(expr.span);
334 tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
336 tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp, None);
339 oprnd_t = tcx.ty_error();
342 hir::UnOp::UnNot => {
343 let result = self.check_user_unop(expr, oprnd_t, unop);
344 // If it's builtin, we can reuse the type, this helps inference.
345 if !(oprnd_t.is_integral() || oprnd_t.kind == ty::Bool) {
349 hir::UnOp::UnNeg => {
350 let result = self.check_user_unop(expr, oprnd_t, unop);
351 // If it's builtin, we can reuse the type, this helps inference.
352 if !oprnd_t.is_numeric() {
361 fn check_expr_addr_of(
363 kind: hir::BorrowKind,
364 mutbl: hir::Mutability,
365 oprnd: &'tcx hir::Expr<'tcx>,
366 expected: Expectation<'tcx>,
367 expr: &'tcx hir::Expr<'tcx>,
369 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
371 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
372 if oprnd.is_syntactic_place_expr() {
373 // Places may legitimately have unsized types.
374 // For example, dereferences of a fat pointer and
375 // the last field of a struct can be unsized.
378 Expectation::rvalue_hint(self, ty)
385 self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl));
387 let tm = ty::TypeAndMut { ty, mutbl };
389 _ if tm.ty.references_error() => self.tcx.ty_error(),
390 hir::BorrowKind::Raw => {
391 self.check_named_place_expr(oprnd);
394 hir::BorrowKind::Ref => {
395 // Note: at this point, we cannot say what the best lifetime
396 // is to use for resulting pointer. We want to use the
397 // shortest lifetime possible so as to avoid spurious borrowck
398 // errors. Moreover, the longest lifetime will depend on the
399 // precise details of the value whose address is being taken
400 // (and how long it is valid), which we don't know yet until
401 // type inference is complete.
403 // Therefore, here we simply generate a region variable. The
404 // region inferencer will then select a suitable value.
405 // Finally, borrowck will infer the value of the region again,
406 // this time with enough precision to check that the value
407 // whose address was taken can actually be made to live as long
408 // as it needs to live.
409 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
410 self.tcx.mk_ref(region, tm)
415 /// Does this expression refer to a place that either:
416 /// * Is based on a local or static.
417 /// * Contains a dereference
418 /// Note that the adjustments for the children of `expr` should already
419 /// have been resolved.
420 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
421 let is_named = oprnd.is_place_expr(|base| {
422 // Allow raw borrows if there are any deref adjustments.
424 // const VAL: (i32,) = (0,);
425 // const REF: &(i32,) = &(0,);
427 // &raw const VAL.0; // ERROR
428 // &raw const REF.0; // OK, same as &raw const (*REF).0;
430 // This is maybe too permissive, since it allows
431 // `let u = &raw const Box::new((1,)).0`, which creates an
432 // immediately dangling raw pointer.
433 self.typeck_results.borrow().adjustments().get(base.hir_id).map_or(false, |x| {
434 x.iter().any(|adj| if let Adjust::Deref(_) = adj.kind { true } else { false })
442 "cannot take address of a temporary"
444 .span_label(oprnd.span, "temporary value")
449 fn check_expr_path(&self, qpath: &hir::QPath<'_>, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
451 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
454 self.set_tainted_by_errors();
457 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
458 report_unexpected_variant_res(tcx, res, expr.span);
461 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
464 if let ty::FnDef(..) = ty.kind {
465 let fn_sig = ty.fn_sig(tcx);
466 if !tcx.features().unsized_locals {
467 // We want to remove some Sized bounds from std functions,
468 // but don't want to expose the removal to stable Rust.
469 // i.e., we don't want to allow
475 // to work in stable even if the Sized bound on `drop` is relaxed.
476 for i in 0..fn_sig.inputs().skip_binder().len() {
477 // We just want to check sizedness, so instead of introducing
478 // placeholder lifetimes with probing, we just replace higher lifetimes
481 .replace_bound_vars_with_fresh_vars(
483 infer::LateBoundRegionConversionTime::FnCall,
487 self.require_type_is_sized_deferred(
490 traits::SizedArgumentType(None),
494 // Here we want to prevent struct constructors from returning unsized types.
495 // There were two cases this happened: fn pointer coercion in stable
496 // and usual function call in presence of unsized_locals.
497 // Also, as we just want to check sizedness, instead of introducing
498 // placeholder lifetimes with probing, we just replace higher lifetimes
501 .replace_bound_vars_with_fresh_vars(
503 infer::LateBoundRegionConversionTime::FnCall,
507 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
510 // We always require that the type provided as the value for
511 // a type parameter outlives the moment of instantiation.
512 let substs = self.typeck_results.borrow().node_substs(expr.hir_id);
513 self.add_wf_bounds(substs, expr);
520 destination: hir::Destination,
521 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
522 expr: &'tcx hir::Expr<'tcx>,
525 if let Ok(target_id) = destination.target_id {
527 if let Some(ref e) = expr_opt {
528 // If this is a break with a value, we need to type-check
529 // the expression. Get an expected type from the loop context.
530 let opt_coerce_to = {
531 // We should release `enclosing_breakables` before the `check_expr_with_hint`
532 // below, so can't move this block of code to the enclosing scope and share
533 // `ctxt` with the second `encloding_breakables` borrow below.
534 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
535 match enclosing_breakables.opt_find_breakable(target_id) {
536 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
538 // Avoid ICE when `break` is inside a closure (#65383).
539 return tcx.ty_error_with_message(
541 "break was outside loop, but no error was emitted",
547 // If the loop context is not a `loop { }`, then break with
548 // a value is illegal, and `opt_coerce_to` will be `None`.
549 // Just set expectation to error in that case.
550 let coerce_to = opt_coerce_to.unwrap_or_else(|| tcx.ty_error());
552 // Recurse without `enclosing_breakables` borrowed.
553 e_ty = self.check_expr_with_hint(e, coerce_to);
554 cause = self.misc(e.span);
556 // Otherwise, this is a break *without* a value. That's
557 // always legal, and is equivalent to `break ()`.
558 e_ty = tcx.mk_unit();
559 cause = self.misc(expr.span);
562 // Now that we have type-checked `expr_opt`, borrow
563 // the `enclosing_loops` field and let's coerce the
564 // type of `expr_opt` into what is expected.
565 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
566 let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
569 // Avoid ICE when `break` is inside a closure (#65383).
570 return tcx.ty_error_with_message(
572 "break was outside loop, but no error was emitted",
577 if let Some(ref mut coerce) = ctxt.coerce {
578 if let Some(ref e) = expr_opt {
579 coerce.coerce(self, &cause, e, e_ty);
581 assert!(e_ty.is_unit());
582 let ty = coerce.expected_ty();
583 coerce.coerce_forced_unit(
587 self.suggest_mismatched_types_on_tail(
588 &mut err, expr, ty, e_ty, cause.span, target_id,
590 if let Some(val) = ty_kind_suggestion(ty) {
591 let label = destination
593 .map(|l| format!(" {}", l.ident))
594 .unwrap_or_else(String::new);
597 "give it a value of the expected type",
598 format!("break{} {}", label, val),
599 Applicability::HasPlaceholders,
607 // If `ctxt.coerce` is `None`, we can just ignore
608 // the type of the expression. This is because
609 // either this was a break *without* a value, in
610 // which case it is always a legal type (`()`), or
611 // else an error would have been flagged by the
612 // `loops` pass for using break with an expression
613 // where you are not supposed to.
614 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
617 ctxt.may_break = true;
619 // the type of a `break` is always `!`, since it diverges
622 // Otherwise, we failed to find the enclosing loop;
623 // this can only happen if the `break` was not
624 // inside a loop at all, which is caught by the
625 // loop-checking pass.
626 let err = self.tcx.ty_error_with_message(
628 "break was outside loop, but no error was emitted",
631 // We still need to assign a type to the inner expression to
632 // prevent the ICE in #43162.
633 if let Some(ref e) = expr_opt {
634 self.check_expr_with_hint(e, err);
636 // ... except when we try to 'break rust;'.
637 // ICE this expression in particular (see #43162).
638 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
639 if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
640 fatally_break_rust(self.tcx.sess);
645 // There was an error; make type-check fail.
650 fn check_expr_return(
652 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
653 expr: &'tcx hir::Expr<'tcx>,
655 if self.ret_coercion.is_none() {
660 "return statement outside of function body",
663 } else if let Some(ref e) = expr_opt {
664 if self.ret_coercion_span.borrow().is_none() {
665 *self.ret_coercion_span.borrow_mut() = Some(e.span);
667 self.check_return_expr(e);
669 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
670 if self.ret_coercion_span.borrow().is_none() {
671 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
673 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
674 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
675 coercion.coerce_forced_unit(
679 let span = fn_decl.output.span();
680 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
683 format!("expected `{}` because of this return type", snippet),
690 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
696 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr<'tcx>) {
697 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
698 span_bug!(return_expr.span, "check_return_expr called outside fn body")
701 let ret_ty = ret_coercion.borrow().expected_ty();
702 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
703 ret_coercion.borrow_mut().coerce(
705 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
711 fn is_destructuring_place_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> bool {
713 ExprKind::Array(comps) | ExprKind::Tup(comps) => {
714 comps.iter().all(|e| self.is_destructuring_place_expr(e))
716 ExprKind::Struct(_path, fields, rest) => {
717 rest.as_ref().map(|e| self.is_destructuring_place_expr(e)).unwrap_or(true)
718 && fields.iter().all(|f| self.is_destructuring_place_expr(&f.expr))
720 _ => expr.is_syntactic_place_expr(),
724 pub(crate) fn check_lhs_assignable(
726 lhs: &'tcx hir::Expr<'tcx>,
727 err_code: &'static str,
730 if !lhs.is_syntactic_place_expr() {
731 let mut err = self.tcx.sess.struct_span_err_with_code(
733 "invalid left-hand side of assignment",
734 DiagnosticId::Error(err_code.into()),
736 err.span_label(lhs.span, "cannot assign to this expression");
737 if self.is_destructuring_place_expr(lhs) {
738 err.note("destructuring assignments are not currently supported");
739 err.note("for more information, see https://github.com/rust-lang/rfcs/issues/372");
745 /// Type check assignment expression `expr` of form `lhs = rhs`.
746 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
747 fn check_expr_assign(
749 expr: &'tcx hir::Expr<'tcx>,
750 expected: Expectation<'tcx>,
751 lhs: &'tcx hir::Expr<'tcx>,
752 rhs: &'tcx hir::Expr<'tcx>,
755 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
756 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs));
758 let expected_ty = expected.coercion_target_type(self, expr.span);
759 if expected_ty == self.tcx.types.bool {
760 // The expected type is `bool` but this will result in `()` so we can reasonably
761 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
762 // The likely cause of this is `if foo = bar { .. }`.
763 let actual_ty = self.tcx.mk_unit();
764 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
765 let msg = "try comparing for equality";
766 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
767 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
768 if let (Ok(left), Ok(right)) = (left, right) {
769 let help = format!("{} == {}", left, right);
770 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
776 self.check_lhs_assignable(lhs, "E0070", span);
779 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
781 if lhs_ty.references_error() || rhs_ty.references_error() {
790 body: &'tcx hir::Block<'tcx>,
791 source: hir::LoopSource,
792 expected: Expectation<'tcx>,
793 expr: &'tcx hir::Expr<'tcx>,
795 let coerce = match source {
796 // you can only use break with a value from a normal `loop { }`
797 hir::LoopSource::Loop => {
798 let coerce_to = expected.coercion_target_type(self, body.span);
799 Some(CoerceMany::new(coerce_to))
802 hir::LoopSource::While | hir::LoopSource::WhileLet | hir::LoopSource::ForLoop => None,
805 let ctxt = BreakableCtxt {
807 may_break: false, // Will get updated if/when we find a `break`.
810 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
811 self.check_block_no_value(&body);
815 // No way to know whether it's diverging because
816 // of a `break` or an outer `break` or `return`.
817 self.diverges.set(Diverges::Maybe);
820 // If we permit break with a value, then result type is
821 // the LUB of the breaks (possibly ! if none); else, it
822 // is nil. This makes sense because infinite loops
823 // (which would have type !) are only possible iff we
824 // permit break with a value [1].
825 if ctxt.coerce.is_none() && !ctxt.may_break {
827 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
829 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
832 /// Checks a method call.
833 fn check_method_call(
835 expr: &'tcx hir::Expr<'tcx>,
836 segment: &hir::PathSegment<'_>,
838 args: &'tcx [hir::Expr<'tcx>],
839 expected: Expectation<'tcx>,
842 let rcvr_t = self.check_expr(&rcvr);
843 // no need to check for bot/err -- callee does that
844 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
846 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
848 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
849 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
851 self.write_method_call(expr.hir_id, method);
855 if segment.ident.name != kw::Invalid {
856 self.report_extended_method_error(segment, span, args, rcvr_t, error);
862 // Call the generic checker.
863 self.check_method_argument_types(
873 fn report_extended_method_error(
875 segment: &hir::PathSegment<'_>,
877 args: &'tcx [hir::Expr<'tcx>],
879 error: MethodError<'tcx>,
882 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, new_rcvr_t| {
883 if let Some(new_rcvr_t) = new_rcvr_t {
884 if let Ok(pick) = self.lookup_probe(
889 probe::ProbeScope::AllTraits,
891 debug!("try_alt_rcvr: pick candidate {:?}", pick);
892 // Make sure the method is defined for the *actual* receiver:
893 // we don't want to treat `Box<Self>` as a receiver if
894 // it only works because of an autoderef to `&self`
895 if pick.autoderefs == 0 {
897 pick.item.ident.span,
898 &format!("the method is available for `{}` here", new_rcvr_t),
905 if let Some(mut err) = self.report_method_error(
909 SelfSource::MethodCall(rcvr),
913 if let ty::Adt(..) = rcvr_t.kind {
914 // Try alternative arbitrary self types that could fulfill this call.
915 // FIXME: probe for all types that *could* be arbitrary self-types, not
917 try_alt_rcvr(&mut err, self.tcx.mk_lang_item(rcvr_t, lang_items::OwnedBoxLangItem));
918 try_alt_rcvr(&mut err, self.tcx.mk_lang_item(rcvr_t, lang_items::PinTypeLangItem));
919 try_alt_rcvr(&mut err, self.tcx.mk_diagnostic_item(rcvr_t, sym::Arc));
920 try_alt_rcvr(&mut err, self.tcx.mk_diagnostic_item(rcvr_t, sym::Rc));
928 e: &'tcx hir::Expr<'tcx>,
929 t: &'tcx hir::Ty<'tcx>,
930 expr: &'tcx hir::Expr<'tcx>,
932 // Find the type of `e`. Supply hints based on the type we are casting to,
934 let t_cast = self.to_ty_saving_user_provided_ty(t);
935 let t_cast = self.resolve_vars_if_possible(&t_cast);
936 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
937 let t_cast = self.resolve_vars_if_possible(&t_cast);
939 // Eagerly check for some obvious errors.
940 if t_expr.references_error() || t_cast.references_error() {
943 // Defer other checks until we're done type checking.
944 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
945 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
947 deferred_cast_checks.push(cast_check);
950 Err(ErrorReported) => self.tcx.ty_error(),
957 args: &'tcx [hir::Expr<'tcx>],
958 expected: Expectation<'tcx>,
959 expr: &'tcx hir::Expr<'tcx>,
961 let element_ty = if !args.is_empty() {
962 let coerce_to = expected
964 .and_then(|uty| match uty.kind {
965 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
969 self.next_ty_var(TypeVariableOrigin {
970 kind: TypeVariableOriginKind::TypeInference,
974 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
975 assert_eq!(self.diverges.get(), Diverges::Maybe);
977 let e_ty = self.check_expr_with_hint(e, coerce_to);
978 let cause = self.misc(e.span);
979 coerce.coerce(self, &cause, e, e_ty);
981 coerce.complete(self)
983 self.next_ty_var(TypeVariableOrigin {
984 kind: TypeVariableOriginKind::TypeInference,
988 self.tcx.mk_array(element_ty, args.len() as u64)
991 fn check_expr_repeat(
993 element: &'tcx hir::Expr<'tcx>,
994 count: &'tcx hir::AnonConst,
995 expected: Expectation<'tcx>,
996 _expr: &'tcx hir::Expr<'tcx>,
999 let count = self.to_const(count);
1001 let uty = match expected {
1002 ExpectHasType(uty) => match uty.kind {
1003 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1009 let (element_ty, t) = match uty {
1011 self.check_expr_coercable_to_type(&element, uty, None);
1015 let ty = self.next_ty_var(TypeVariableOrigin {
1016 kind: TypeVariableOriginKind::MiscVariable,
1019 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1024 if element_ty.references_error() {
1025 return tcx.ty_error();
1028 tcx.mk_ty(ty::Array(t, count))
1031 fn check_expr_tuple(
1033 elts: &'tcx [hir::Expr<'tcx>],
1034 expected: Expectation<'tcx>,
1035 expr: &'tcx hir::Expr<'tcx>,
1037 let flds = expected.only_has_type(self).and_then(|ty| {
1038 let ty = self.resolve_vars_with_obligations(ty);
1040 ty::Tuple(ref flds) => Some(&flds[..]),
1045 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1046 Some(ref fs) if i < fs.len() => {
1047 let ety = fs[i].expect_ty();
1048 self.check_expr_coercable_to_type(&e, ety, None);
1051 _ => self.check_expr_with_expectation(&e, NoExpectation),
1053 let tuple = self.tcx.mk_tup(elt_ts_iter);
1054 if tuple.references_error() {
1057 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1062 fn check_expr_struct(
1064 expr: &hir::Expr<'_>,
1065 expected: Expectation<'tcx>,
1067 fields: &'tcx [hir::Field<'tcx>],
1068 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1070 // Find the relevant variant
1071 let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id)
1075 self.check_struct_fields_on_error(fields, base_expr);
1076 return self.tcx.ty_error();
1079 let path_span = match *qpath {
1080 QPath::Resolved(_, ref path) => path.span,
1081 QPath::TypeRelative(ref qself, _) => qself.span,
1084 // Prohibit struct expressions when non-exhaustive flag is set.
1085 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1086 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1091 "cannot create non-exhaustive {} using struct expression",
1097 let error_happened = self.check_expr_struct_fields(
1104 base_expr.is_none(),
1106 if let &Some(ref base_expr) = base_expr {
1107 // If check_expr_struct_fields hit an error, do not attempt to populate
1108 // the fields with the base_expr. This could cause us to hit errors later
1109 // when certain fields are assumed to exist that in fact do not.
1110 if !error_happened {
1111 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1113 ty::Adt(adt, substs) if adt.is_struct() => {
1114 let fru_field_types = adt
1119 self.normalize_associated_types_in(
1121 &f.ty(self.tcx, substs),
1128 .fru_field_types_mut()
1129 .insert(expr.hir_id, fru_field_types);
1136 "functional record update syntax requires a struct"
1143 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1147 fn check_expr_struct_fields(
1150 expected: Expectation<'tcx>,
1151 expr_id: hir::HirId,
1153 variant: &'tcx ty::VariantDef,
1154 ast_fields: &'tcx [hir::Field<'tcx>],
1155 check_completeness: bool,
1159 let adt_ty_hint = self
1160 .expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1164 // re-link the regions that EIfEO can erase.
1165 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1167 let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1168 &ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()),
1169 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"),
1172 let mut remaining_fields = variant
1176 .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
1177 .collect::<FxHashMap<_, _>>();
1179 let mut seen_fields = FxHashMap::default();
1181 let mut error_happened = false;
1183 // Type-check each field.
1184 for field in ast_fields {
1185 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1186 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1187 seen_fields.insert(ident, field.span);
1188 self.write_field_index(field.hir_id, i);
1190 // We don't look at stability attributes on
1191 // struct-like enums (yet...), but it's definitely not
1192 // a bug to have constructed one.
1193 if adt_kind != AdtKind::Enum {
1194 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1197 self.field_ty(field.span, v_field, substs)
1199 error_happened = true;
1200 if let Some(prev_span) = seen_fields.get(&ident) {
1201 let mut err = struct_span_err!(
1205 "field `{}` specified more than once",
1209 err.span_label(field.ident.span, "used more than once");
1210 err.span_label(*prev_span, format!("first use of `{}`", ident));
1214 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1220 // Make sure to give a type to the field even if there's
1221 // an error, so we can continue type-checking.
1222 self.check_expr_coercable_to_type(&field.expr, field_type, None);
1225 // Make sure the programmer specified correct number of fields.
1226 if kind_name == "union" {
1227 if ast_fields.len() != 1 {
1228 tcx.sess.span_err(span, "union expressions should have exactly one field");
1230 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1231 let len = remaining_fields.len();
1233 let mut displayable_field_names =
1234 remaining_fields.keys().map(|ident| ident.as_str()).collect::<Vec<_>>();
1236 displayable_field_names.sort();
1238 let truncated_fields_error = if len <= 3 {
1241 format!(" and {} other field{}", (len - 3), if len - 3 == 1 { "" } else { "s" })
1244 let remaining_fields_names = displayable_field_names
1247 .map(|n| format!("`{}`", n))
1248 .collect::<Vec<_>>()
1255 "missing field{} {}{} in initializer of `{}`",
1256 pluralize!(remaining_fields.len()),
1257 remaining_fields_names,
1258 truncated_fields_error,
1263 format!("missing {}{}", remaining_fields_names, truncated_fields_error),
1270 fn check_struct_fields_on_error(
1272 fields: &'tcx [hir::Field<'tcx>],
1273 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1275 for field in fields {
1276 self.check_expr(&field.expr);
1278 if let Some(ref base) = *base_expr {
1279 self.check_expr(&base);
1283 fn report_unknown_field(
1286 variant: &'tcx ty::VariantDef,
1287 field: &hir::Field<'_>,
1288 skip_fields: &[hir::Field<'_>],
1292 if variant.recovered {
1293 self.set_tainted_by_errors();
1296 let mut err = self.type_error_struct_with_diag(
1298 |actual| match ty.kind {
1299 ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
1303 "{} `{}::{}` has no field named `{}`",
1309 _ => struct_span_err!(
1313 "{} `{}` has no field named `{}`",
1321 match variant.ctor_kind {
1323 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt = ty));
1324 err.span_label(field.ident.span, "field does not exist");
1328 "`{adt}` is a tuple {kind_name}, \
1329 use the appropriate syntax: `{adt}(/* fields */)`",
1331 kind_name = kind_name
1336 // prevent all specified fields from being suggested
1337 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1338 if let Some(field_name) =
1339 Self::suggest_field_name(variant, field.ident.name, skip_fields.collect())
1341 err.span_suggestion(
1343 "a field with a similar name exists",
1344 field_name.to_string(),
1345 Applicability::MaybeIncorrect,
1349 ty::Adt(adt, ..) => {
1353 format!("`{}::{}` does not have this field", ty, variant.ident),
1358 format!("`{}` does not have this field", ty),
1361 let available_field_names = self.available_field_names(variant);
1362 if !available_field_names.is_empty() {
1364 "available fields are: {}",
1365 self.name_series_display(available_field_names)
1369 _ => bug!("non-ADT passed to report_unknown_field"),
1377 // Return an hint about the closest match in field names
1378 fn suggest_field_name(
1379 variant: &'tcx ty::VariantDef,
1382 ) -> Option<Symbol> {
1383 let names = variant.fields.iter().filter_map(|field| {
1384 // ignore already set fields and private fields from non-local crates
1385 if skip.iter().any(|&x| x == field.ident.name)
1386 || (!variant.def_id.is_local() && field.vis != Visibility::Public)
1390 Some(&field.ident.name)
1394 find_best_match_for_name(names, field, None)
1397 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<Symbol> {
1402 let def_scope = self
1404 .adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id)
1406 field.vis.is_accessible_from(def_scope, self.tcx)
1408 .map(|field| field.ident.name)
1412 fn name_series_display(&self, names: Vec<Symbol>) -> String {
1413 // dynamic limit, to never omit just one field
1414 let limit = if names.len() == 6 { 6 } else { 5 };
1416 names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1417 if names.len() > limit {
1418 display = format!("{} ... and {} others", display, names.len() - limit);
1423 // Check field access expressions
1426 expr: &'tcx hir::Expr<'tcx>,
1427 base: &'tcx hir::Expr<'tcx>,
1430 let expr_t = self.check_expr(base);
1431 let expr_t = self.structurally_resolved_type(base.span, expr_t);
1432 let mut private_candidate = None;
1433 let mut autoderef = self.autoderef(expr.span, expr_t);
1434 while let Some((base_t, _)) = autoderef.next() {
1436 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1437 debug!("struct named {:?}", base_t);
1438 let (ident, def_scope) =
1439 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1440 let fields = &base_def.non_enum_variant().fields;
1441 if let Some(index) =
1442 fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident)
1444 let field = &fields[index];
1445 let field_ty = self.field_ty(expr.span, field, substs);
1446 // Save the index of all fields regardless of their visibility in case
1447 // of error recovery.
1448 self.write_field_index(expr.hir_id, index);
1449 if field.vis.is_accessible_from(def_scope, self.tcx) {
1450 let adjustments = self.adjust_steps(&autoderef);
1451 self.apply_adjustments(base, adjustments);
1452 self.register_predicates(autoderef.into_obligations());
1454 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1457 private_candidate = Some((base_def.did, field_ty));
1460 ty::Tuple(ref tys) => {
1461 let fstr = field.as_str();
1462 if let Ok(index) = fstr.parse::<usize>() {
1463 if fstr == index.to_string() {
1464 if let Some(field_ty) = tys.get(index) {
1465 let adjustments = self.adjust_steps(&autoderef);
1466 self.apply_adjustments(base, adjustments);
1467 self.register_predicates(autoderef.into_obligations());
1469 self.write_field_index(expr.hir_id, index);
1470 return field_ty.expect_ty();
1478 self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
1480 if let Some((did, field_ty)) = private_candidate {
1481 self.ban_private_field_access(expr, expr_t, field, did);
1485 if field.name == kw::Invalid {
1486 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1487 self.ban_take_value_of_method(expr, expr_t, field);
1488 } else if !expr_t.is_primitive_ty() {
1489 self.ban_nonexisting_field(field, base, expr, expr_t);
1496 "`{}` is a primitive type and therefore doesn't have fields",
1502 self.tcx().ty_error()
1505 fn ban_nonexisting_field(
1508 base: &'tcx hir::Expr<'tcx>,
1509 expr: &'tcx hir::Expr<'tcx>,
1512 let mut err = self.no_such_field_err(field.span, field, expr_t);
1514 match expr_t.peel_refs().kind {
1515 ty::Array(_, len) => {
1516 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1519 self.suggest_first_deref_field(&mut err, expr, base, field);
1521 ty::Adt(def, _) if !def.is_enum() => {
1522 self.suggest_fields_on_recordish(&mut err, def, field);
1524 ty::Param(param_ty) => {
1525 self.point_at_param_definition(&mut err, param_ty);
1530 if field.name == kw::Await {
1531 // We know by construction that `<expr>.await` is either on Rust 2015
1532 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1533 err.note("to `.await` a `Future`, switch to Rust 2018");
1534 err.help("set `edition = \"2018\"` in `Cargo.toml`");
1535 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1541 fn ban_private_field_access(
1543 expr: &hir::Expr<'_>,
1548 let struct_path = self.tcx().def_path_str(base_did);
1549 let kind_name = self.tcx().def_kind(base_did).descr(base_did);
1550 let mut err = struct_span_err!(
1554 "field `{}` of {} `{}` is private",
1559 err.span_label(field.span, "private field");
1560 // Also check if an accessible method exists, which is often what is meant.
1561 if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
1563 self.suggest_method_call(
1565 &format!("a method `{}` also exists, call it with parentheses", field),
1574 fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: Ident) {
1575 let mut err = type_error_struct!(
1580 "attempted to take value of method `{}` on type `{}`",
1584 err.span_label(field.span, "method, not a field");
1585 if !self.expr_in_place(expr.hir_id) {
1586 self.suggest_method_call(
1588 "use parentheses to call the method",
1594 err.help("methods are immutable and cannot be assigned to");
1600 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1601 let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
1602 let generic_param = generics.type_param(¶m, self.tcx);
1603 if let ty::GenericParamDefKind::Type { synthetic: Some(..), .. } = generic_param.kind {
1606 let param_def_id = generic_param.def_id;
1607 let param_hir_id = match param_def_id.as_local() {
1608 Some(x) => self.tcx.hir().as_local_hir_id(x),
1611 let param_span = self.tcx.hir().span(param_hir_id);
1612 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1614 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1617 fn suggest_fields_on_recordish(
1619 err: &mut DiagnosticBuilder<'_>,
1620 def: &'tcx ty::AdtDef,
1623 if let Some(suggested_field_name) =
1624 Self::suggest_field_name(def.non_enum_variant(), field.name, vec![])
1626 err.span_suggestion(
1628 "a field with a similar name exists",
1629 suggested_field_name.to_string(),
1630 Applicability::MaybeIncorrect,
1633 err.span_label(field.span, "unknown field");
1634 let struct_variant_def = def.non_enum_variant();
1635 let field_names = self.available_field_names(struct_variant_def);
1636 if !field_names.is_empty() {
1638 "available fields are: {}",
1639 self.name_series_display(field_names),
1645 fn maybe_suggest_array_indexing(
1647 err: &mut DiagnosticBuilder<'_>,
1648 expr: &hir::Expr<'_>,
1649 base: &hir::Expr<'_>,
1651 len: &ty::Const<'tcx>,
1653 if let (Some(len), Ok(user_index)) =
1654 (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
1656 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
1657 let help = "instead of using tuple indexing, use array indexing";
1658 let suggestion = format!("{}[{}]", base, field);
1659 let applicability = if len < user_index {
1660 Applicability::MachineApplicable
1662 Applicability::MaybeIncorrect
1664 err.span_suggestion(expr.span, help, suggestion, applicability);
1669 fn suggest_first_deref_field(
1671 err: &mut DiagnosticBuilder<'_>,
1672 expr: &hir::Expr<'_>,
1673 base: &hir::Expr<'_>,
1676 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
1677 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1678 let suggestion = format!("(*{}).{}", base, field);
1679 err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
1683 fn no_such_field_err<T: Display>(
1687 expr_t: &ty::TyS<'_>,
1688 ) -> DiagnosticBuilder<'_> {
1694 "no field `{}` on type `{}`",
1700 fn check_expr_index(
1702 base: &'tcx hir::Expr<'tcx>,
1703 idx: &'tcx hir::Expr<'tcx>,
1704 expr: &'tcx hir::Expr<'tcx>,
1706 let base_t = self.check_expr(&base);
1707 let idx_t = self.check_expr(&idx);
1709 if base_t.references_error() {
1711 } else if idx_t.references_error() {
1714 let base_t = self.structurally_resolved_type(base.span, base_t);
1715 match self.lookup_indexing(expr, base, base_t, idx_t) {
1716 Some((index_ty, element_ty)) => {
1717 // two-phase not needed because index_ty is never mutable
1718 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
1722 let mut err = type_error_struct!(
1727 "cannot index into a value of type `{}`",
1730 // Try to give some advice about indexing tuples.
1731 if let ty::Tuple(..) = base_t.kind {
1732 let mut needs_note = true;
1733 // If the index is an integer, we can show the actual
1734 // fixed expression:
1735 if let ExprKind::Lit(ref lit) = idx.kind {
1736 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1737 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1738 if let Ok(snip) = snip {
1739 err.span_suggestion(
1741 "to access tuple elements, use",
1742 format!("{}.{}", snip, i),
1743 Applicability::MachineApplicable,
1751 "to access tuple elements, use tuple indexing \
1752 syntax (e.g., `tuple.0`)",
1763 fn check_expr_yield(
1765 value: &'tcx hir::Expr<'tcx>,
1766 expr: &'tcx hir::Expr<'tcx>,
1767 src: &'tcx hir::YieldSource,
1769 match self.resume_yield_tys {
1770 Some((resume_ty, yield_ty)) => {
1771 self.check_expr_coercable_to_type(&value, yield_ty, None);
1775 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1776 // we know that the yield type must be `()`; however, the context won't contain this
1777 // information. Hence, we check the source of the yield expression here and check its
1778 // value's type against `()` (this check should always hold).
1779 None if src.is_await() => {
1780 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit(), None);
1788 "yield expression outside of generator literal"
1796 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
1797 let needs = if is_input { Needs::None } else { Needs::MutPlace };
1798 let ty = self.check_expr_with_needs(expr, needs);
1799 self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
1801 if !is_input && !expr.is_syntactic_place_expr() {
1802 let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output");
1803 err.span_label(expr.span, "cannot assign to this expression");
1807 // If this is an input value, we require its type to be fully resolved
1808 // at this point. This allows us to provide helpful coercions which help
1809 // pass the type candidate list in a later pass.
1811 // We don't require output types to be resolved at this point, which
1812 // allows them to be inferred based on how they are used later in the
1815 let ty = self.structurally_resolved_type(expr.span, &ty);
1818 let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx));
1819 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
1821 ty::Ref(_, base_ty, mutbl) => {
1822 let ptr_ty = self.tcx.mk_ptr(ty::TypeAndMut { ty: base_ty, mutbl });
1823 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
1830 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
1831 for op in asm.operands {
1833 hir::InlineAsmOperand::In { expr, .. } | hir::InlineAsmOperand::Const { expr } => {
1834 self.check_expr_asm_operand(expr, true);
1836 hir::InlineAsmOperand::Out { expr, .. } => {
1837 if let Some(expr) = expr {
1838 self.check_expr_asm_operand(expr, false);
1841 hir::InlineAsmOperand::InOut { expr, .. } => {
1842 self.check_expr_asm_operand(expr, false);
1844 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1845 self.check_expr_asm_operand(in_expr, true);
1846 if let Some(out_expr) = out_expr {
1847 self.check_expr_asm_operand(out_expr, false);
1850 hir::InlineAsmOperand::Sym { expr } => {
1851 self.check_expr(expr);
1855 if asm.options.contains(ast::InlineAsmOptions::NORETURN) {
1856 self.tcx.types.never
1863 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1864 Some(match ty.kind {
1867 ty::Int(_) | ty::Uint(_) => "42",
1868 ty::Float(_) => "3.14159",
1869 ty::Error(_) | ty::Never => return None,