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_data_structures::stack::ensure_sufficient_stack;
23 use rustc_errors::ErrorReported;
24 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId};
26 use rustc_hir::def::{CtorKind, DefKind, Res};
27 use rustc_hir::def_id::DefId;
28 use rustc_hir::lang_items;
29 use rustc_hir::{ExprKind, QPath};
30 use rustc_infer::infer;
31 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
33 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
34 use rustc_middle::ty::Ty;
35 use rustc_middle::ty::TypeFoldable;
36 use rustc_middle::ty::{AdtKind, Visibility};
37 use rustc_span::hygiene::DesugaringKind;
38 use rustc_span::source_map::Span;
39 use rustc_span::symbol::{kw, sym, Ident, Symbol};
40 use rustc_trait_selection::traits::{self, ObligationCauseCode};
42 use std::fmt::Display;
44 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
45 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
46 let ty = self.check_expr_with_hint(expr, expected);
47 self.demand_eqtype(expr.span, expected, ty);
50 pub fn check_expr_has_type_or_error(
52 expr: &'tcx hir::Expr<'tcx>,
54 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
56 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
59 fn check_expr_meets_expectation_or_error(
61 expr: &'tcx hir::Expr<'tcx>,
62 expected: Expectation<'tcx>,
63 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
65 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
66 let mut ty = self.check_expr_with_expectation(expr, expected);
68 // While we don't allow *arbitrary* coercions here, we *do* allow
69 // coercions from ! to `expected`.
72 !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id),
73 "expression with never type wound up being adjusted"
75 let adj_ty = self.next_diverging_ty_var(TypeVariableOrigin {
76 kind: TypeVariableOriginKind::AdjustmentType,
79 self.apply_adjustments(
81 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
86 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
87 let expr = expr.peel_drop_temps();
88 self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None);
90 // Error possibly reported in `check_assign` so avoid emitting error again.
91 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
96 pub(super) fn check_expr_coercable_to_type(
98 expr: &'tcx hir::Expr<'tcx>,
100 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
102 let ty = self.check_expr_with_hint(expr, expected);
103 // checks don't need two phase
104 self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No)
107 pub(super) fn check_expr_with_hint(
109 expr: &'tcx hir::Expr<'tcx>,
112 self.check_expr_with_expectation(expr, ExpectHasType(expected))
115 fn check_expr_with_expectation_and_needs(
117 expr: &'tcx hir::Expr<'tcx>,
118 expected: Expectation<'tcx>,
121 let ty = self.check_expr_with_expectation(expr, expected);
123 // If the expression is used in a place whether mutable place is required
124 // e.g. LHS of assignment, perform the conversion.
125 if let Needs::MutPlace = needs {
126 self.convert_place_derefs_to_mutable(expr);
132 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
133 self.check_expr_with_expectation(expr, NoExpectation)
136 pub(super) fn check_expr_with_needs(
138 expr: &'tcx hir::Expr<'tcx>,
141 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
145 /// If an expression has any sub-expressions that result in a type error,
146 /// inspecting that expression's type with `ty.references_error()` will return
147 /// true. Likewise, if an expression is known to diverge, inspecting its
148 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
149 /// strict, _|_ can appear in the type of an expression that does not,
150 /// itself, diverge: for example, fn() -> _|_.)
151 /// Note that inspecting a type's structure *directly* may expose the fact
152 /// that there are actually multiple representations for `Error`, so avoid
153 /// that when err needs to be handled differently.
154 pub(super) fn check_expr_with_expectation(
156 expr: &'tcx hir::Expr<'tcx>,
157 expected: Expectation<'tcx>,
159 debug!(">> type-checking: expr={:?} expected={:?}", expr, expected);
161 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
162 // without the final expr (e.g. `try { return; }`). We don't want to generate an
163 // unreachable_code lint for it since warnings for autogenerated code are confusing.
164 let is_try_block_generated_unit_expr = match expr.kind {
165 ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
166 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
172 // Warn for expressions after diverging siblings.
173 if !is_try_block_generated_unit_expr {
174 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
177 // Hide the outer diverging and has_errors flags.
178 let old_diverges = self.diverges.replace(Diverges::Maybe);
179 let old_has_errors = self.has_errors.replace(false);
181 let ty = ensure_sufficient_stack(|| self.check_expr_kind(expr, expected));
183 // Warn for non-block expressions with diverging children.
185 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {}
186 // If `expr` is a result of desugaring the try block and is an ok-wrapped
187 // diverging expression (e.g. it arose from desugaring of `try { return }`),
188 // we skip issuing a warning because it is autogenerated code.
189 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
190 ExprKind::Call(ref callee, _) => {
191 self.warn_if_unreachable(expr.hir_id, callee.span, "call")
193 ExprKind::MethodCall(_, ref span, _, _) => {
194 self.warn_if_unreachable(expr.hir_id, *span, "call")
196 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
199 // Any expression that produces a value of type `!` must have diverged
201 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
204 // Record the type, which applies it effects.
205 // We need to do this after the warning above, so that
206 // we don't warn for the diverging expression itself.
207 self.write_ty(expr.hir_id, ty);
209 // Combine the diverging and has_error flags.
210 self.diverges.set(self.diverges.get() | old_diverges);
211 self.has_errors.set(self.has_errors.get() | old_has_errors);
213 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
214 debug!("... {:?}, expected is {:?}", ty, expected);
221 expr: &'tcx hir::Expr<'tcx>,
222 expected: Expectation<'tcx>,
224 debug!("check_expr_kind(expr={:?}, expected={:?})", expr, expected);
228 ExprKind::Box(ref subexpr) => self.check_expr_box(subexpr, expected),
229 ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
230 ExprKind::Binary(op, ref lhs, ref rhs) => self.check_binop(expr, op, lhs, rhs),
231 ExprKind::Assign(ref lhs, ref rhs, ref span) => {
232 self.check_expr_assign(expr, expected, lhs, rhs, span)
234 ExprKind::AssignOp(op, ref lhs, ref rhs) => self.check_binop_assign(expr, op, lhs, rhs),
235 ExprKind::Unary(unop, ref oprnd) => self.check_expr_unary(unop, oprnd, expected, expr),
236 ExprKind::AddrOf(kind, mutbl, ref oprnd) => {
237 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
239 ExprKind::Path(QPath::LangItem(lang_item, _)) => {
240 self.check_lang_item_path(lang_item, expr)
242 ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr),
243 ExprKind::InlineAsm(asm) => self.check_expr_asm(asm),
244 ExprKind::LlvmInlineAsm(ref asm) => {
245 for expr in asm.outputs_exprs.iter().chain(asm.inputs_exprs.iter()) {
246 self.check_expr(expr);
250 ExprKind::Break(destination, ref expr_opt) => {
251 self.check_expr_break(destination, expr_opt.as_deref(), expr)
253 ExprKind::Continue(destination) => {
254 if destination.target_id.is_ok() {
257 // There was an error; make type-check fail.
261 ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
262 ExprKind::Loop(ref body, _, source) => {
263 self.check_expr_loop(body, source, expected, expr)
265 ExprKind::Match(ref discrim, ref arms, match_src) => {
266 self.check_match(expr, &discrim, arms, expected, match_src)
268 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
269 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
271 ExprKind::Block(ref body, _) => self.check_block_with_expected(&body, expected),
272 ExprKind::Call(ref callee, ref args) => self.check_call(expr, &callee, args, expected),
273 ExprKind::MethodCall(ref segment, span, ref args, _) => {
274 self.check_method_call(expr, segment, span, args, expected)
276 ExprKind::Cast(ref e, ref t) => self.check_expr_cast(e, t, expr),
277 ExprKind::Type(ref e, ref t) => {
278 let ty = self.to_ty_saving_user_provided_ty(&t);
279 self.check_expr_eq_type(&e, ty);
282 ExprKind::DropTemps(ref e) => self.check_expr_with_expectation(e, expected),
283 ExprKind::Array(ref args) => self.check_expr_array(args, expected, expr),
284 ExprKind::Repeat(ref element, ref count) => {
285 self.check_expr_repeat(element, count, expected, expr)
287 ExprKind::Tup(ref elts) => self.check_expr_tuple(elts, expected, expr),
288 ExprKind::Struct(ref qpath, fields, ref base_expr) => {
289 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
291 ExprKind::Field(ref base, field) => self.check_field(expr, &base, field),
292 ExprKind::Index(ref base, ref idx) => self.check_expr_index(base, idx, expr),
293 ExprKind::Yield(ref value, ref src) => self.check_expr_yield(value, expr, src),
294 hir::ExprKind::Err => tcx.ty_error(),
298 fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
299 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind {
300 ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
303 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
304 self.tcx.mk_box(referent_ty)
310 oprnd: &'tcx hir::Expr<'tcx>,
311 expected: Expectation<'tcx>,
312 expr: &'tcx hir::Expr<'tcx>,
315 let expected_inner = match unop {
316 hir::UnOp::UnNot | hir::UnOp::UnNeg => expected,
317 hir::UnOp::UnDeref => NoExpectation,
319 let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner);
321 if !oprnd_t.references_error() {
322 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
324 hir::UnOp::UnDeref => {
325 if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
328 let mut err = type_error_struct!(
333 "type `{}` cannot be dereferenced",
336 let sp = tcx.sess.source_map().start_point(expr.span);
338 tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
340 tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp, None);
343 oprnd_t = tcx.ty_error();
346 hir::UnOp::UnNot => {
347 let result = self.check_user_unop(expr, oprnd_t, unop);
348 // If it's builtin, we can reuse the type, this helps inference.
349 if !(oprnd_t.is_integral() || oprnd_t.kind == ty::Bool) {
353 hir::UnOp::UnNeg => {
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_numeric() {
365 fn check_expr_addr_of(
367 kind: hir::BorrowKind,
368 mutbl: hir::Mutability,
369 oprnd: &'tcx hir::Expr<'tcx>,
370 expected: Expectation<'tcx>,
371 expr: &'tcx hir::Expr<'tcx>,
373 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
375 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
376 if oprnd.is_syntactic_place_expr() {
377 // Places may legitimately have unsized types.
378 // For example, dereferences of a fat pointer and
379 // the last field of a struct can be unsized.
382 Expectation::rvalue_hint(self, ty)
389 self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl));
391 let tm = ty::TypeAndMut { ty, mutbl };
393 _ if tm.ty.references_error() => self.tcx.ty_error(),
394 hir::BorrowKind::Raw => {
395 self.check_named_place_expr(oprnd);
398 hir::BorrowKind::Ref => {
399 // Note: at this point, we cannot say what the best lifetime
400 // is to use for resulting pointer. We want to use the
401 // shortest lifetime possible so as to avoid spurious borrowck
402 // errors. Moreover, the longest lifetime will depend on the
403 // precise details of the value whose address is being taken
404 // (and how long it is valid), which we don't know yet until
405 // type inference is complete.
407 // Therefore, here we simply generate a region variable. The
408 // region inferencer will then select a suitable value.
409 // Finally, borrowck will infer the value of the region again,
410 // this time with enough precision to check that the value
411 // whose address was taken can actually be made to live as long
412 // as it needs to live.
413 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
414 self.tcx.mk_ref(region, tm)
419 /// Does this expression refer to a place that either:
420 /// * Is based on a local or static.
421 /// * Contains a dereference
422 /// Note that the adjustments for the children of `expr` should already
423 /// have been resolved.
424 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
425 let is_named = oprnd.is_place_expr(|base| {
426 // Allow raw borrows if there are any deref adjustments.
428 // const VAL: (i32,) = (0,);
429 // const REF: &(i32,) = &(0,);
431 // &raw const VAL.0; // ERROR
432 // &raw const REF.0; // OK, same as &raw const (*REF).0;
434 // This is maybe too permissive, since it allows
435 // `let u = &raw const Box::new((1,)).0`, which creates an
436 // immediately dangling raw pointer.
437 self.typeck_results.borrow().adjustments().get(base.hir_id).map_or(false, |x| {
438 x.iter().any(|adj| if let Adjust::Deref(_) = adj.kind { true } else { false })
446 "cannot take address of a temporary"
448 .span_label(oprnd.span, "temporary value")
453 fn check_lang_item_path(
455 lang_item: hir::LangItem,
456 expr: &'tcx hir::Expr<'tcx>,
458 self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id).1
461 fn check_expr_path(&self, qpath: &hir::QPath<'_>, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
463 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
466 self.set_tainted_by_errors();
469 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
470 report_unexpected_variant_res(tcx, res, expr.span);
473 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
476 if let ty::FnDef(..) = ty.kind {
477 let fn_sig = ty.fn_sig(tcx);
478 if !tcx.features().unsized_locals {
479 // We want to remove some Sized bounds from std functions,
480 // but don't want to expose the removal to stable Rust.
481 // i.e., we don't want to allow
487 // to work in stable even if the Sized bound on `drop` is relaxed.
488 for i in 0..fn_sig.inputs().skip_binder().len() {
489 // We just want to check sizedness, so instead of introducing
490 // placeholder lifetimes with probing, we just replace higher lifetimes
493 .replace_bound_vars_with_fresh_vars(
495 infer::LateBoundRegionConversionTime::FnCall,
499 self.require_type_is_sized_deferred(
502 traits::SizedArgumentType(None),
506 // Here we want to prevent struct constructors from returning unsized types.
507 // There were two cases this happened: fn pointer coercion in stable
508 // and usual function call in presence of unsized_locals.
509 // Also, as we just want to check sizedness, instead of introducing
510 // placeholder lifetimes with probing, we just replace higher lifetimes
513 .replace_bound_vars_with_fresh_vars(
515 infer::LateBoundRegionConversionTime::FnCall,
519 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
522 // We always require that the type provided as the value for
523 // a type parameter outlives the moment of instantiation.
524 let substs = self.typeck_results.borrow().node_substs(expr.hir_id);
525 self.add_wf_bounds(substs, expr);
532 destination: hir::Destination,
533 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
534 expr: &'tcx hir::Expr<'tcx>,
537 if let Ok(target_id) = destination.target_id {
539 if let Some(ref e) = expr_opt {
540 // If this is a break with a value, we need to type-check
541 // the expression. Get an expected type from the loop context.
542 let opt_coerce_to = {
543 // We should release `enclosing_breakables` before the `check_expr_with_hint`
544 // below, so can't move this block of code to the enclosing scope and share
545 // `ctxt` with the second `encloding_breakables` borrow below.
546 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
547 match enclosing_breakables.opt_find_breakable(target_id) {
548 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
550 // Avoid ICE when `break` is inside a closure (#65383).
551 return tcx.ty_error_with_message(
553 "break was outside loop, but no error was emitted",
559 // If the loop context is not a `loop { }`, then break with
560 // a value is illegal, and `opt_coerce_to` will be `None`.
561 // Just set expectation to error in that case.
562 let coerce_to = opt_coerce_to.unwrap_or_else(|| tcx.ty_error());
564 // Recurse without `enclosing_breakables` borrowed.
565 e_ty = self.check_expr_with_hint(e, coerce_to);
566 cause = self.misc(e.span);
568 // Otherwise, this is a break *without* a value. That's
569 // always legal, and is equivalent to `break ()`.
570 e_ty = tcx.mk_unit();
571 cause = self.misc(expr.span);
574 // Now that we have type-checked `expr_opt`, borrow
575 // the `enclosing_loops` field and let's coerce the
576 // type of `expr_opt` into what is expected.
577 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
578 let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
581 // Avoid ICE when `break` is inside a closure (#65383).
582 return tcx.ty_error_with_message(
584 "break was outside loop, but no error was emitted",
589 if let Some(ref mut coerce) = ctxt.coerce {
590 if let Some(ref e) = expr_opt {
591 coerce.coerce(self, &cause, e, e_ty);
593 assert!(e_ty.is_unit());
594 let ty = coerce.expected_ty();
595 coerce.coerce_forced_unit(
599 self.suggest_mismatched_types_on_tail(
600 &mut err, expr, ty, e_ty, cause.span, target_id,
602 if let Some(val) = ty_kind_suggestion(ty) {
603 let label = destination
605 .map(|l| format!(" {}", l.ident))
606 .unwrap_or_else(String::new);
609 "give it a value of the expected type",
610 format!("break{} {}", label, val),
611 Applicability::HasPlaceholders,
619 // If `ctxt.coerce` is `None`, we can just ignore
620 // the type of the expression. This is because
621 // either this was a break *without* a value, in
622 // which case it is always a legal type (`()`), or
623 // else an error would have been flagged by the
624 // `loops` pass for using break with an expression
625 // where you are not supposed to.
626 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
629 ctxt.may_break = true;
631 // the type of a `break` is always `!`, since it diverges
634 // Otherwise, we failed to find the enclosing loop;
635 // this can only happen if the `break` was not
636 // inside a loop at all, which is caught by the
637 // loop-checking pass.
638 let err = self.tcx.ty_error_with_message(
640 "break was outside loop, but no error was emitted",
643 // We still need to assign a type to the inner expression to
644 // prevent the ICE in #43162.
645 if let Some(ref e) = expr_opt {
646 self.check_expr_with_hint(e, err);
648 // ... except when we try to 'break rust;'.
649 // ICE this expression in particular (see #43162).
650 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
651 if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
652 fatally_break_rust(self.tcx.sess);
657 // There was an error; make type-check fail.
662 fn check_expr_return(
664 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
665 expr: &'tcx hir::Expr<'tcx>,
667 if self.ret_coercion.is_none() {
672 "return statement outside of function body",
675 } else if let Some(ref e) = expr_opt {
676 if self.ret_coercion_span.borrow().is_none() {
677 *self.ret_coercion_span.borrow_mut() = Some(e.span);
679 self.check_return_expr(e);
681 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
682 if self.ret_coercion_span.borrow().is_none() {
683 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
685 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
686 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
687 coercion.coerce_forced_unit(
691 let span = fn_decl.output.span();
692 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
695 format!("expected `{}` because of this return type", snippet),
702 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
708 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr<'tcx>) {
709 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
710 span_bug!(return_expr.span, "check_return_expr called outside fn body")
713 let ret_ty = ret_coercion.borrow().expected_ty();
714 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
715 ret_coercion.borrow_mut().coerce(
717 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
723 fn is_destructuring_place_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> bool {
725 ExprKind::Array(comps) | ExprKind::Tup(comps) => {
726 comps.iter().all(|e| self.is_destructuring_place_expr(e))
728 ExprKind::Struct(_path, fields, rest) => {
729 rest.as_ref().map(|e| self.is_destructuring_place_expr(e)).unwrap_or(true)
730 && fields.iter().all(|f| self.is_destructuring_place_expr(&f.expr))
732 _ => expr.is_syntactic_place_expr(),
736 pub(crate) fn check_lhs_assignable(
738 lhs: &'tcx hir::Expr<'tcx>,
739 err_code: &'static str,
742 if !lhs.is_syntactic_place_expr() {
743 let mut err = self.tcx.sess.struct_span_err_with_code(
745 "invalid left-hand side of assignment",
746 DiagnosticId::Error(err_code.into()),
748 err.span_label(lhs.span, "cannot assign to this expression");
749 if self.is_destructuring_place_expr(lhs) {
750 err.note("destructuring assignments are not currently supported");
751 err.note("for more information, see https://github.com/rust-lang/rfcs/issues/372");
757 /// Type check assignment expression `expr` of form `lhs = rhs`.
758 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
759 fn check_expr_assign(
761 expr: &'tcx hir::Expr<'tcx>,
762 expected: Expectation<'tcx>,
763 lhs: &'tcx hir::Expr<'tcx>,
764 rhs: &'tcx hir::Expr<'tcx>,
767 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
768 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs));
770 let expected_ty = expected.coercion_target_type(self, expr.span);
771 if expected_ty == self.tcx.types.bool {
772 // The expected type is `bool` but this will result in `()` so we can reasonably
773 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
774 // The likely cause of this is `if foo = bar { .. }`.
775 let actual_ty = self.tcx.mk_unit();
776 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
777 let msg = "try comparing for equality";
778 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
779 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
780 if let (Ok(left), Ok(right)) = (left, right) {
781 let help = format!("{} == {}", left, right);
782 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
788 self.check_lhs_assignable(lhs, "E0070", span);
791 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
793 if lhs_ty.references_error() || rhs_ty.references_error() {
802 body: &'tcx hir::Block<'tcx>,
803 source: hir::LoopSource,
804 expected: Expectation<'tcx>,
805 expr: &'tcx hir::Expr<'tcx>,
807 let coerce = match source {
808 // you can only use break with a value from a normal `loop { }`
809 hir::LoopSource::Loop => {
810 let coerce_to = expected.coercion_target_type(self, body.span);
811 Some(CoerceMany::new(coerce_to))
814 hir::LoopSource::While | hir::LoopSource::WhileLet | hir::LoopSource::ForLoop => None,
817 let ctxt = BreakableCtxt {
819 may_break: false, // Will get updated if/when we find a `break`.
822 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
823 self.check_block_no_value(&body);
827 // No way to know whether it's diverging because
828 // of a `break` or an outer `break` or `return`.
829 self.diverges.set(Diverges::Maybe);
832 // If we permit break with a value, then result type is
833 // the LUB of the breaks (possibly ! if none); else, it
834 // is nil. This makes sense because infinite loops
835 // (which would have type !) are only possible iff we
836 // permit break with a value [1].
837 if ctxt.coerce.is_none() && !ctxt.may_break {
839 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
841 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
844 /// Checks a method call.
845 fn check_method_call(
847 expr: &'tcx hir::Expr<'tcx>,
848 segment: &hir::PathSegment<'_>,
850 args: &'tcx [hir::Expr<'tcx>],
851 expected: Expectation<'tcx>,
854 let rcvr_t = self.check_expr(&rcvr);
855 // no need to check for bot/err -- callee does that
856 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
858 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
860 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
861 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
863 self.write_method_call(expr.hir_id, method);
867 if segment.ident.name != kw::Invalid {
868 self.report_extended_method_error(segment, span, args, rcvr_t, error);
874 // Call the generic checker.
875 self.check_method_argument_types(
885 fn report_extended_method_error(
887 segment: &hir::PathSegment<'_>,
889 args: &'tcx [hir::Expr<'tcx>],
891 error: MethodError<'tcx>,
894 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, new_rcvr_t| {
895 if let Some(new_rcvr_t) = new_rcvr_t {
896 if let Ok(pick) = self.lookup_probe(
901 probe::ProbeScope::AllTraits,
903 debug!("try_alt_rcvr: pick candidate {:?}", pick);
904 // Make sure the method is defined for the *actual* receiver:
905 // we don't want to treat `Box<Self>` as a receiver if
906 // it only works because of an autoderef to `&self`
907 if pick.autoderefs == 0 {
909 pick.item.ident.span,
910 &format!("the method is available for `{}` here", new_rcvr_t),
917 if let Some(mut err) = self.report_method_error(
921 SelfSource::MethodCall(rcvr),
925 if let ty::Adt(..) = rcvr_t.kind {
926 // Try alternative arbitrary self types that could fulfill this call.
927 // FIXME: probe for all types that *could* be arbitrary self-types, not
929 try_alt_rcvr(&mut err, self.tcx.mk_lang_item(rcvr_t, lang_items::OwnedBoxLangItem));
930 try_alt_rcvr(&mut err, self.tcx.mk_lang_item(rcvr_t, lang_items::PinTypeLangItem));
931 try_alt_rcvr(&mut err, self.tcx.mk_diagnostic_item(rcvr_t, sym::Arc));
932 try_alt_rcvr(&mut err, self.tcx.mk_diagnostic_item(rcvr_t, sym::Rc));
940 e: &'tcx hir::Expr<'tcx>,
941 t: &'tcx hir::Ty<'tcx>,
942 expr: &'tcx hir::Expr<'tcx>,
944 // Find the type of `e`. Supply hints based on the type we are casting to,
946 let t_cast = self.to_ty_saving_user_provided_ty(t);
947 let t_cast = self.resolve_vars_if_possible(&t_cast);
948 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
949 let t_cast = self.resolve_vars_if_possible(&t_cast);
951 // Eagerly check for some obvious errors.
952 if t_expr.references_error() || t_cast.references_error() {
955 // Defer other checks until we're done type checking.
956 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
957 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
959 deferred_cast_checks.push(cast_check);
962 Err(ErrorReported) => self.tcx.ty_error(),
969 args: &'tcx [hir::Expr<'tcx>],
970 expected: Expectation<'tcx>,
971 expr: &'tcx hir::Expr<'tcx>,
973 let element_ty = if !args.is_empty() {
974 let coerce_to = expected
976 .and_then(|uty| match uty.kind {
977 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
981 self.next_ty_var(TypeVariableOrigin {
982 kind: TypeVariableOriginKind::TypeInference,
986 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
987 assert_eq!(self.diverges.get(), Diverges::Maybe);
989 let e_ty = self.check_expr_with_hint(e, coerce_to);
990 let cause = self.misc(e.span);
991 coerce.coerce(self, &cause, e, e_ty);
993 coerce.complete(self)
995 self.next_ty_var(TypeVariableOrigin {
996 kind: TypeVariableOriginKind::TypeInference,
1000 self.tcx.mk_array(element_ty, args.len() as u64)
1003 fn check_expr_repeat(
1005 element: &'tcx hir::Expr<'tcx>,
1006 count: &'tcx hir::AnonConst,
1007 expected: Expectation<'tcx>,
1008 _expr: &'tcx hir::Expr<'tcx>,
1011 let count = self.to_const(count);
1013 let uty = match expected {
1014 ExpectHasType(uty) => match uty.kind {
1015 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1021 let (element_ty, t) = match uty {
1023 self.check_expr_coercable_to_type(&element, uty, None);
1027 let ty = self.next_ty_var(TypeVariableOrigin {
1028 kind: TypeVariableOriginKind::MiscVariable,
1031 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1036 if element_ty.references_error() {
1037 return tcx.ty_error();
1040 tcx.mk_ty(ty::Array(t, count))
1043 fn check_expr_tuple(
1045 elts: &'tcx [hir::Expr<'tcx>],
1046 expected: Expectation<'tcx>,
1047 expr: &'tcx hir::Expr<'tcx>,
1049 let flds = expected.only_has_type(self).and_then(|ty| {
1050 let ty = self.resolve_vars_with_obligations(ty);
1052 ty::Tuple(ref flds) => Some(&flds[..]),
1057 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1058 Some(ref fs) if i < fs.len() => {
1059 let ety = fs[i].expect_ty();
1060 self.check_expr_coercable_to_type(&e, ety, None);
1063 _ => self.check_expr_with_expectation(&e, NoExpectation),
1065 let tuple = self.tcx.mk_tup(elt_ts_iter);
1066 if tuple.references_error() {
1069 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1074 fn check_expr_struct(
1076 expr: &hir::Expr<'_>,
1077 expected: Expectation<'tcx>,
1079 fields: &'tcx [hir::Field<'tcx>],
1080 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1082 // Find the relevant variant
1083 let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id)
1087 self.check_struct_fields_on_error(fields, base_expr);
1088 return self.tcx.ty_error();
1091 // Prohibit struct expressions when non-exhaustive flag is set.
1092 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1093 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1098 "cannot create non-exhaustive {} using struct expression",
1104 let error_happened = self.check_expr_struct_fields(
1111 base_expr.is_none(),
1113 if let &Some(ref base_expr) = base_expr {
1114 // If check_expr_struct_fields hit an error, do not attempt to populate
1115 // the fields with the base_expr. This could cause us to hit errors later
1116 // when certain fields are assumed to exist that in fact do not.
1117 if !error_happened {
1118 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1120 ty::Adt(adt, substs) if adt.is_struct() => {
1121 let fru_field_types = adt
1126 self.normalize_associated_types_in(
1128 &f.ty(self.tcx, substs),
1135 .fru_field_types_mut()
1136 .insert(expr.hir_id, fru_field_types);
1143 "functional record update syntax requires a struct"
1150 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1154 fn check_expr_struct_fields(
1157 expected: Expectation<'tcx>,
1158 expr_id: hir::HirId,
1160 variant: &'tcx ty::VariantDef,
1161 ast_fields: &'tcx [hir::Field<'tcx>],
1162 check_completeness: bool,
1166 let adt_ty_hint = self
1167 .expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1171 // re-link the regions that EIfEO can erase.
1172 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1174 let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1175 &ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()),
1176 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"),
1179 let mut remaining_fields = variant
1183 .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
1184 .collect::<FxHashMap<_, _>>();
1186 let mut seen_fields = FxHashMap::default();
1188 let mut error_happened = false;
1190 // Type-check each field.
1191 for field in ast_fields {
1192 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1193 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1194 seen_fields.insert(ident, field.span);
1195 self.write_field_index(field.hir_id, i);
1197 // We don't look at stability attributes on
1198 // struct-like enums (yet...), but it's definitely not
1199 // a bug to have constructed one.
1200 if adt_kind != AdtKind::Enum {
1201 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1204 self.field_ty(field.span, v_field, substs)
1206 error_happened = true;
1207 if let Some(prev_span) = seen_fields.get(&ident) {
1208 let mut err = struct_span_err!(
1212 "field `{}` specified more than once",
1216 err.span_label(field.ident.span, "used more than once");
1217 err.span_label(*prev_span, format!("first use of `{}`", ident));
1221 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1227 // Make sure to give a type to the field even if there's
1228 // an error, so we can continue type-checking.
1229 self.check_expr_coercable_to_type(&field.expr, field_type, None);
1232 // Make sure the programmer specified correct number of fields.
1233 if kind_name == "union" {
1234 if ast_fields.len() != 1 {
1235 tcx.sess.span_err(span, "union expressions should have exactly one field");
1237 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1238 let len = remaining_fields.len();
1240 let mut displayable_field_names =
1241 remaining_fields.keys().map(|ident| ident.as_str()).collect::<Vec<_>>();
1243 displayable_field_names.sort();
1245 let truncated_fields_error = if len <= 3 {
1248 format!(" and {} other field{}", (len - 3), if len - 3 == 1 { "" } else { "s" })
1251 let remaining_fields_names = displayable_field_names
1254 .map(|n| format!("`{}`", n))
1255 .collect::<Vec<_>>()
1262 "missing field{} {}{} in initializer of `{}`",
1263 pluralize!(remaining_fields.len()),
1264 remaining_fields_names,
1265 truncated_fields_error,
1270 format!("missing {}{}", remaining_fields_names, truncated_fields_error),
1277 fn check_struct_fields_on_error(
1279 fields: &'tcx [hir::Field<'tcx>],
1280 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1282 for field in fields {
1283 self.check_expr(&field.expr);
1285 if let Some(ref base) = *base_expr {
1286 self.check_expr(&base);
1290 fn report_unknown_field(
1293 variant: &'tcx ty::VariantDef,
1294 field: &hir::Field<'_>,
1295 skip_fields: &[hir::Field<'_>],
1299 if variant.recovered {
1300 self.set_tainted_by_errors();
1303 let mut err = self.type_error_struct_with_diag(
1305 |actual| match ty.kind {
1306 ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
1310 "{} `{}::{}` has no field named `{}`",
1316 _ => struct_span_err!(
1320 "{} `{}` has no field named `{}`",
1328 match variant.ctor_kind {
1330 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt = ty));
1331 err.span_label(field.ident.span, "field does not exist");
1335 "`{adt}` is a tuple {kind_name}, \
1336 use the appropriate syntax: `{adt}(/* fields */)`",
1338 kind_name = kind_name
1343 // prevent all specified fields from being suggested
1344 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1345 if let Some(field_name) =
1346 Self::suggest_field_name(variant, field.ident.name, skip_fields.collect())
1348 err.span_suggestion(
1350 "a field with a similar name exists",
1351 field_name.to_string(),
1352 Applicability::MaybeIncorrect,
1356 ty::Adt(adt, ..) => {
1360 format!("`{}::{}` does not have this field", ty, variant.ident),
1365 format!("`{}` does not have this field", ty),
1368 let available_field_names = self.available_field_names(variant);
1369 if !available_field_names.is_empty() {
1371 "available fields are: {}",
1372 self.name_series_display(available_field_names)
1376 _ => bug!("non-ADT passed to report_unknown_field"),
1384 // Return an hint about the closest match in field names
1385 fn suggest_field_name(
1386 variant: &'tcx ty::VariantDef,
1389 ) -> Option<Symbol> {
1390 let names = variant.fields.iter().filter_map(|field| {
1391 // ignore already set fields and private fields from non-local crates
1392 if skip.iter().any(|&x| x == field.ident.name)
1393 || (!variant.def_id.is_local() && field.vis != Visibility::Public)
1397 Some(&field.ident.name)
1401 find_best_match_for_name(names, field, None)
1404 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<Symbol> {
1409 let def_scope = self
1411 .adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id)
1413 field.vis.is_accessible_from(def_scope, self.tcx)
1415 .map(|field| field.ident.name)
1419 fn name_series_display(&self, names: Vec<Symbol>) -> String {
1420 // dynamic limit, to never omit just one field
1421 let limit = if names.len() == 6 { 6 } else { 5 };
1423 names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1424 if names.len() > limit {
1425 display = format!("{} ... and {} others", display, names.len() - limit);
1430 // Check field access expressions
1433 expr: &'tcx hir::Expr<'tcx>,
1434 base: &'tcx hir::Expr<'tcx>,
1437 let expr_t = self.check_expr(base);
1438 let expr_t = self.structurally_resolved_type(base.span, expr_t);
1439 let mut private_candidate = None;
1440 let mut autoderef = self.autoderef(expr.span, expr_t);
1441 while let Some((base_t, _)) = autoderef.next() {
1443 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1444 debug!("struct named {:?}", base_t);
1445 let (ident, def_scope) =
1446 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1447 let fields = &base_def.non_enum_variant().fields;
1448 if let Some(index) =
1449 fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident)
1451 let field = &fields[index];
1452 let field_ty = self.field_ty(expr.span, field, substs);
1453 // Save the index of all fields regardless of their visibility in case
1454 // of error recovery.
1455 self.write_field_index(expr.hir_id, index);
1456 if field.vis.is_accessible_from(def_scope, self.tcx) {
1457 let adjustments = self.adjust_steps(&autoderef);
1458 self.apply_adjustments(base, adjustments);
1459 self.register_predicates(autoderef.into_obligations());
1461 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1464 private_candidate = Some((base_def.did, field_ty));
1467 ty::Tuple(ref tys) => {
1468 let fstr = field.as_str();
1469 if let Ok(index) = fstr.parse::<usize>() {
1470 if fstr == index.to_string() {
1471 if let Some(field_ty) = tys.get(index) {
1472 let adjustments = self.adjust_steps(&autoderef);
1473 self.apply_adjustments(base, adjustments);
1474 self.register_predicates(autoderef.into_obligations());
1476 self.write_field_index(expr.hir_id, index);
1477 return field_ty.expect_ty();
1485 self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
1487 if let Some((did, field_ty)) = private_candidate {
1488 self.ban_private_field_access(expr, expr_t, field, did);
1492 if field.name == kw::Invalid {
1493 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1494 self.ban_take_value_of_method(expr, expr_t, field);
1495 } else if !expr_t.is_primitive_ty() {
1496 self.ban_nonexisting_field(field, base, expr, expr_t);
1503 "`{}` is a primitive type and therefore doesn't have fields",
1509 self.tcx().ty_error()
1512 fn ban_nonexisting_field(
1515 base: &'tcx hir::Expr<'tcx>,
1516 expr: &'tcx hir::Expr<'tcx>,
1519 let mut err = self.no_such_field_err(field.span, field, expr_t);
1521 match expr_t.peel_refs().kind {
1522 ty::Array(_, len) => {
1523 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1526 self.suggest_first_deref_field(&mut err, expr, base, field);
1528 ty::Adt(def, _) if !def.is_enum() => {
1529 self.suggest_fields_on_recordish(&mut err, def, field);
1531 ty::Param(param_ty) => {
1532 self.point_at_param_definition(&mut err, param_ty);
1537 if field.name == kw::Await {
1538 // We know by construction that `<expr>.await` is either on Rust 2015
1539 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1540 err.note("to `.await` a `Future`, switch to Rust 2018");
1541 err.help("set `edition = \"2018\"` in `Cargo.toml`");
1542 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1548 fn ban_private_field_access(
1550 expr: &hir::Expr<'_>,
1555 let struct_path = self.tcx().def_path_str(base_did);
1556 let kind_name = self.tcx().def_kind(base_did).descr(base_did);
1557 let mut err = struct_span_err!(
1561 "field `{}` of {} `{}` is private",
1566 err.span_label(field.span, "private field");
1567 // Also check if an accessible method exists, which is often what is meant.
1568 if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
1570 self.suggest_method_call(
1572 &format!("a method `{}` also exists, call it with parentheses", field),
1581 fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: Ident) {
1582 let mut err = type_error_struct!(
1587 "attempted to take value of method `{}` on type `{}`",
1591 err.span_label(field.span, "method, not a field");
1592 if !self.expr_in_place(expr.hir_id) {
1593 self.suggest_method_call(
1595 "use parentheses to call the method",
1601 err.help("methods are immutable and cannot be assigned to");
1607 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1608 let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
1609 let generic_param = generics.type_param(¶m, self.tcx);
1610 if let ty::GenericParamDefKind::Type { synthetic: Some(..), .. } = generic_param.kind {
1613 let param_def_id = generic_param.def_id;
1614 let param_hir_id = match param_def_id.as_local() {
1615 Some(x) => self.tcx.hir().local_def_id_to_hir_id(x),
1618 let param_span = self.tcx.hir().span(param_hir_id);
1619 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1621 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1624 fn suggest_fields_on_recordish(
1626 err: &mut DiagnosticBuilder<'_>,
1627 def: &'tcx ty::AdtDef,
1630 if let Some(suggested_field_name) =
1631 Self::suggest_field_name(def.non_enum_variant(), field.name, vec![])
1633 err.span_suggestion(
1635 "a field with a similar name exists",
1636 suggested_field_name.to_string(),
1637 Applicability::MaybeIncorrect,
1640 err.span_label(field.span, "unknown field");
1641 let struct_variant_def = def.non_enum_variant();
1642 let field_names = self.available_field_names(struct_variant_def);
1643 if !field_names.is_empty() {
1645 "available fields are: {}",
1646 self.name_series_display(field_names),
1652 fn maybe_suggest_array_indexing(
1654 err: &mut DiagnosticBuilder<'_>,
1655 expr: &hir::Expr<'_>,
1656 base: &hir::Expr<'_>,
1658 len: &ty::Const<'tcx>,
1660 if let (Some(len), Ok(user_index)) =
1661 (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
1663 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
1664 let help = "instead of using tuple indexing, use array indexing";
1665 let suggestion = format!("{}[{}]", base, field);
1666 let applicability = if len < user_index {
1667 Applicability::MachineApplicable
1669 Applicability::MaybeIncorrect
1671 err.span_suggestion(expr.span, help, suggestion, applicability);
1676 fn suggest_first_deref_field(
1678 err: &mut DiagnosticBuilder<'_>,
1679 expr: &hir::Expr<'_>,
1680 base: &hir::Expr<'_>,
1683 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
1684 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1685 let suggestion = format!("(*{}).{}", base, field);
1686 err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
1690 fn no_such_field_err<T: Display>(
1694 expr_t: &ty::TyS<'_>,
1695 ) -> DiagnosticBuilder<'_> {
1701 "no field `{}` on type `{}`",
1707 fn check_expr_index(
1709 base: &'tcx hir::Expr<'tcx>,
1710 idx: &'tcx hir::Expr<'tcx>,
1711 expr: &'tcx hir::Expr<'tcx>,
1713 let base_t = self.check_expr(&base);
1714 let idx_t = self.check_expr(&idx);
1716 if base_t.references_error() {
1718 } else if idx_t.references_error() {
1721 let base_t = self.structurally_resolved_type(base.span, base_t);
1722 match self.lookup_indexing(expr, base, base_t, idx_t) {
1723 Some((index_ty, element_ty)) => {
1724 // two-phase not needed because index_ty is never mutable
1725 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
1729 let mut err = type_error_struct!(
1734 "cannot index into a value of type `{}`",
1737 // Try to give some advice about indexing tuples.
1738 if let ty::Tuple(..) = base_t.kind {
1739 let mut needs_note = true;
1740 // If the index is an integer, we can show the actual
1741 // fixed expression:
1742 if let ExprKind::Lit(ref lit) = idx.kind {
1743 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1744 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1745 if let Ok(snip) = snip {
1746 err.span_suggestion(
1748 "to access tuple elements, use",
1749 format!("{}.{}", snip, i),
1750 Applicability::MachineApplicable,
1758 "to access tuple elements, use tuple indexing \
1759 syntax (e.g., `tuple.0`)",
1770 fn check_expr_yield(
1772 value: &'tcx hir::Expr<'tcx>,
1773 expr: &'tcx hir::Expr<'tcx>,
1774 src: &'tcx hir::YieldSource,
1776 match self.resume_yield_tys {
1777 Some((resume_ty, yield_ty)) => {
1778 self.check_expr_coercable_to_type(&value, yield_ty, None);
1782 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1783 // we know that the yield type must be `()`; however, the context won't contain this
1784 // information. Hence, we check the source of the yield expression here and check its
1785 // value's type against `()` (this check should always hold).
1786 None if src.is_await() => {
1787 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit(), None);
1795 "yield expression outside of generator literal"
1803 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
1804 let needs = if is_input { Needs::None } else { Needs::MutPlace };
1805 let ty = self.check_expr_with_needs(expr, needs);
1806 self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
1808 if !is_input && !expr.is_syntactic_place_expr() {
1809 let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output");
1810 err.span_label(expr.span, "cannot assign to this expression");
1814 // If this is an input value, we require its type to be fully resolved
1815 // at this point. This allows us to provide helpful coercions which help
1816 // pass the type candidate list in a later pass.
1818 // We don't require output types to be resolved at this point, which
1819 // allows them to be inferred based on how they are used later in the
1822 let ty = self.structurally_resolved_type(expr.span, &ty);
1825 let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx));
1826 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
1828 ty::Ref(_, base_ty, mutbl) => {
1829 let ptr_ty = self.tcx.mk_ptr(ty::TypeAndMut { ty: base_ty, mutbl });
1830 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
1837 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
1838 for op in asm.operands {
1840 hir::InlineAsmOperand::In { expr, .. } | hir::InlineAsmOperand::Const { expr } => {
1841 self.check_expr_asm_operand(expr, true);
1843 hir::InlineAsmOperand::Out { expr, .. } => {
1844 if let Some(expr) = expr {
1845 self.check_expr_asm_operand(expr, false);
1848 hir::InlineAsmOperand::InOut { expr, .. } => {
1849 self.check_expr_asm_operand(expr, false);
1851 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1852 self.check_expr_asm_operand(in_expr, true);
1853 if let Some(out_expr) = out_expr {
1854 self.check_expr_asm_operand(out_expr, false);
1857 hir::InlineAsmOperand::Sym { expr } => {
1858 self.check_expr(expr);
1862 if asm.options.contains(ast::InlineAsmOptions::NORETURN) {
1863 self.tcx.types.never
1870 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1871 Some(match ty.kind {
1874 ty::Int(_) | ty::Uint(_) => "42",
1875 ty::Float(_) => "3.14159",
1876 ty::Error(_) | ty::Never => return None,