1 //! Type checking expressions.
3 //! See `mod.rs` for more context on type checking in general.
5 use crate::check::BreakableCtxt;
6 use crate::check::cast;
7 use crate::check::coercion::CoerceMany;
8 use crate::check::Diverges;
9 use crate::check::FnCtxt;
10 use crate::check::Expectation::{self, NoExpectation, ExpectHasType, ExpectCastableToType};
11 use crate::check::fatally_break_rust;
12 use crate::check::report_unexpected_variant_res;
13 use crate::check::Needs;
14 use crate::check::TupleArgumentsFlag::DontTupleArguments;
15 use crate::check::method::{probe, SelfSource, MethodError};
16 use crate::util::common::ErrorReported;
17 use crate::util::nodemap::FxHashMap;
18 use crate::astconv::AstConv as _;
20 use errors::{Applicability, DiagnosticBuilder, pluralise};
21 use syntax_pos::hygiene::DesugaringKind;
23 use syntax::symbol::{Symbol, kw, sym};
24 use syntax::source_map::Span;
25 use syntax::util::lev_distance::find_best_match_for_name;
27 use rustc::hir::{ExprKind, QPath};
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::def::{CtorKind, Res, DefKind};
30 use rustc::hir::ptr::P;
32 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
33 use rustc::middle::lang_items;
34 use rustc::mir::interpret::GlobalId;
36 use rustc::ty::adjustment::{
37 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
39 use rustc::ty::{AdtKind, Visibility};
41 use rustc::ty::TypeFoldable;
42 use rustc::ty::subst::InternalSubsts;
43 use rustc::traits::{self, ObligationCauseCode};
45 use std::fmt::Display;
47 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
49 let ty = self.check_expr_with_hint(expr, expected);
50 self.demand_eqtype(expr.span, expected, ty);
53 pub fn check_expr_has_type_or_error(
55 expr: &'tcx hir::Expr,
57 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
59 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
62 fn check_expr_meets_expectation_or_error(
64 expr: &'tcx hir::Expr,
65 expected: Expectation<'tcx>,
66 extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
68 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
69 let mut ty = self.check_expr_with_expectation(expr, expected);
71 // While we don't allow *arbitrary* coercions here, we *do* allow
72 // coercions from ! to `expected`.
74 assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
75 "expression with never type wound up being adjusted");
76 let adj_ty = self.next_diverging_ty_var(
78 kind: TypeVariableOriginKind::AdjustmentType,
82 self.apply_adjustments(expr, vec![Adjustment {
83 kind: Adjust::NeverToAny,
89 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
90 let expr = expr.peel_drop_temps();
91 self.suggest_ref_or_into(&mut err, expr, expected_ty, ty);
93 // Error possibly reported in `check_assign` so avoid emitting error again.
94 err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
99 pub(super) fn check_expr_coercable_to_type(
101 expr: &'tcx hir::Expr,
104 let ty = self.check_expr_with_hint(expr, expected);
105 // checks don't need two phase
106 self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
109 pub(super) fn check_expr_with_hint(
111 expr: &'tcx hir::Expr,
114 self.check_expr_with_expectation(expr, ExpectHasType(expected))
117 pub(super) fn check_expr_with_expectation(
119 expr: &'tcx hir::Expr,
120 expected: Expectation<'tcx>,
122 self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
125 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
126 self.check_expr_with_expectation(expr, NoExpectation)
129 pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
130 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
134 /// If an expression has any sub-expressions that result in a type error,
135 /// inspecting that expression's type with `ty.references_error()` will return
136 /// true. Likewise, if an expression is known to diverge, inspecting its
137 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
138 /// strict, _|_ can appear in the type of an expression that does not,
139 /// itself, diverge: for example, fn() -> _|_.)
140 /// Note that inspecting a type's structure *directly* may expose the fact
141 /// that there are actually multiple representations for `Error`, so avoid
142 /// that when err needs to be handled differently.
143 fn check_expr_with_expectation_and_needs(
145 expr: &'tcx hir::Expr,
146 expected: Expectation<'tcx>,
149 debug!(">> type-checking: expr={:?} expected={:?}",
152 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
153 // without the final expr (e.g. `try { return; }`). We don't want to generate an
154 // unreachable_code lint for it since warnings for autogenerated code are confusing.
155 let is_try_block_generated_unit_expr = match expr.kind {
156 ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
157 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock),
162 // Warn for expressions after diverging siblings.
163 if !is_try_block_generated_unit_expr {
164 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
167 // Hide the outer diverging and has_errors flags.
168 let old_diverges = self.diverges.get();
169 let old_has_errors = self.has_errors.get();
170 self.diverges.set(Diverges::Maybe);
171 self.has_errors.set(false);
173 let ty = self.check_expr_kind(expr, expected, needs);
175 // Warn for non-block expressions with diverging children.
177 ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {},
178 // If `expr` is a result of desugaring the try block and is an ok-wrapped
179 // diverging expression (e.g. it arose from desugaring of `try { return }`),
180 // we skip issuing a warning because it is autogenerated code.
181 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {},
182 ExprKind::Call(ref callee, _) =>
183 self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
184 ExprKind::MethodCall(_, ref span, _) =>
185 self.warn_if_unreachable(expr.hir_id, *span, "call"),
186 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
189 // Any expression that produces a value of type `!` must have diverged
191 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
194 // Record the type, which applies it effects.
195 // We need to do this after the warning above, so that
196 // we don't warn for the diverging expression itself.
197 self.write_ty(expr.hir_id, ty);
199 // Combine the diverging and has_error flags.
200 self.diverges.set(self.diverges.get() | old_diverges);
201 self.has_errors.set(self.has_errors.get() | old_has_errors);
203 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
204 debug!("... {:?}, expected is {:?}", ty, expected);
211 expr: &'tcx hir::Expr,
212 expected: Expectation<'tcx>,
216 "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
224 ExprKind::Box(ref subexpr) => {
225 self.check_expr_box(subexpr, expected)
227 ExprKind::Lit(ref lit) => {
228 self.check_lit(&lit, expected)
230 ExprKind::Binary(op, ref lhs, ref rhs) => {
231 self.check_binop(expr, op, lhs, rhs)
233 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
234 self.check_binop_assign(expr, op, lhs, rhs)
236 ExprKind::Unary(unop, ref oprnd) => {
237 self.check_expr_unary(unop, oprnd, expected, needs, expr)
239 ExprKind::AddrOf(mutbl, ref oprnd) => {
240 self.check_expr_addr_of(mutbl, oprnd, expected, expr)
242 ExprKind::Path(ref qpath) => {
243 self.check_expr_path(qpath, expr)
245 ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
246 for expr in outputs.iter().chain(inputs.iter()) {
247 self.check_expr(expr);
251 ExprKind::Break(destination, ref expr_opt) => {
252 self.check_expr_break(destination, expr_opt.as_deref(), expr)
254 ExprKind::Continue(destination) => {
255 if destination.target_id.is_ok() {
258 // There was an error; make type-check fail.
262 ExprKind::Ret(ref expr_opt) => {
263 self.check_expr_return(expr_opt.as_deref(), expr)
265 ExprKind::Assign(ref lhs, ref rhs) => {
266 self.check_expr_assign(expr, expected, lhs, rhs)
268 ExprKind::Loop(ref body, _, source) => {
269 self.check_expr_loop(body, source, expected, expr)
271 ExprKind::Match(ref discrim, ref arms, match_src) => {
272 self.check_match(expr, &discrim, arms, expected, match_src)
274 ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
275 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
277 ExprKind::Block(ref body, _) => {
278 self.check_block_with_expected(&body, expected)
280 ExprKind::Call(ref callee, ref args) => {
281 self.check_call(expr, &callee, args, expected)
283 ExprKind::MethodCall(ref segment, span, ref args) => {
284 self.check_method_call(expr, segment, span, args, expected, needs)
286 ExprKind::Cast(ref e, ref t) => {
287 self.check_expr_cast(e, t, expr)
289 ExprKind::Type(ref e, ref t) => {
290 let ty = self.to_ty_saving_user_provided_ty(&t);
291 self.check_expr_eq_type(&e, ty);
294 ExprKind::DropTemps(ref e) => {
295 self.check_expr_with_expectation(e, expected)
297 ExprKind::Array(ref args) => {
298 self.check_expr_array(args, expected, expr)
300 ExprKind::Repeat(ref element, ref count) => {
301 self.check_expr_repeat(element, count, expected, expr)
303 ExprKind::Tup(ref elts) => {
304 self.check_expr_tuple(elts, expected, expr)
306 ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
307 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
309 ExprKind::Field(ref base, field) => {
310 self.check_field(expr, needs, &base, field)
312 ExprKind::Index(ref base, ref idx) => {
313 self.check_expr_index(base, idx, needs, expr)
315 ExprKind::Yield(ref value, ref src) => {
316 self.check_expr_yield(value, expr, src)
318 hir::ExprKind::Err => {
324 fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
325 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
327 ty::Adt(def, _) if def.is_box()
328 => Expectation::rvalue_hint(self, ty.boxed_ty()),
332 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
333 self.tcx.mk_box(referent_ty)
339 oprnd: &'tcx hir::Expr,
340 expected: Expectation<'tcx>,
342 expr: &'tcx hir::Expr,
345 let expected_inner = match unop {
346 hir::UnNot | hir::UnNeg => expected,
347 hir::UnDeref => NoExpectation,
349 let needs = match unop {
350 hir::UnDeref => needs,
353 let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
355 if !oprnd_t.references_error() {
356 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
359 if let Some(mt) = oprnd_t.builtin_deref(true) {
361 } else if let Some(ok) = self.try_overloaded_deref(
362 expr.span, oprnd_t, needs) {
363 let method = self.register_infer_ok_obligations(ok);
364 if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
365 let mutbl = match mutbl {
366 hir::MutImmutable => AutoBorrowMutability::Immutable,
367 hir::MutMutable => AutoBorrowMutability::Mutable {
368 // (It shouldn't actually matter for unary ops whether
369 // we enable two-phase borrows or not, since a unary
370 // op has no additional operands.)
371 allow_two_phase_borrow: AllowTwoPhase::No,
374 self.apply_adjustments(oprnd, vec![Adjustment {
375 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
376 target: method.sig.inputs()[0]
379 oprnd_t = self.make_overloaded_place_return_type(method).ty;
380 self.write_method_call(expr.hir_id, method);
382 let mut err = type_error_struct!(
387 "type `{}` cannot be dereferenced",
390 let sp = tcx.sess.source_map().start_point(expr.span);
391 if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
394 tcx.sess.parse_sess.expr_parentheses_needed(
401 oprnd_t = tcx.types.err;
405 let result = self.check_user_unop(expr, oprnd_t, unop);
406 // If it's builtin, we can reuse the type, this helps inference.
407 if !(oprnd_t.is_integral() || oprnd_t.kind == ty::Bool) {
412 let result = self.check_user_unop(expr, oprnd_t, unop);
413 // If it's builtin, we can reuse the type, this helps inference.
414 if !oprnd_t.is_numeric() {
423 fn check_expr_addr_of(
425 mutbl: hir::Mutability,
426 oprnd: &'tcx hir::Expr,
427 expected: Expectation<'tcx>,
428 expr: &'tcx hir::Expr,
430 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
432 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
433 if oprnd.is_place_expr() {
434 // Places may legitimately have unsized types.
435 // For example, dereferences of a fat pointer and
436 // the last field of a struct can be unsized.
439 Expectation::rvalue_hint(self, ty)
445 let needs = Needs::maybe_mut_place(mutbl);
446 let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
448 let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
449 if tm.ty.references_error() {
452 // Note: at this point, we cannot say what the best lifetime
453 // is to use for resulting pointer. We want to use the
454 // shortest lifetime possible so as to avoid spurious borrowck
455 // errors. Moreover, the longest lifetime will depend on the
456 // precise details of the value whose address is being taken
457 // (and how long it is valid), which we don't know yet until type
458 // inference is complete.
460 // Therefore, here we simply generate a region variable. The
461 // region inferencer will then select the ultimate value.
462 // Finally, borrowck is charged with guaranteeing that the
463 // value whose address was taken can actually be made to live
464 // as long as it needs to live.
465 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
466 self.tcx.mk_ref(region, tm)
470 fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
472 let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
475 self.set_tainted_by_errors();
478 Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
479 report_unexpected_variant_res(tcx, res, expr.span, qpath);
482 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
485 if let ty::FnDef(..) = ty.kind {
486 let fn_sig = ty.fn_sig(tcx);
487 if !tcx.features().unsized_locals {
488 // We want to remove some Sized bounds from std functions,
489 // but don't want to expose the removal to stable Rust.
490 // i.e., we don't want to allow
496 // to work in stable even if the Sized bound on `drop` is relaxed.
497 for i in 0..fn_sig.inputs().skip_binder().len() {
498 // We just want to check sizedness, so instead of introducing
499 // placeholder lifetimes with probing, we just replace higher lifetimes
501 let input = self.replace_bound_vars_with_fresh_vars(
503 infer::LateBoundRegionConversionTime::FnCall,
505 self.require_type_is_sized_deferred(input, expr.span,
506 traits::SizedArgumentType);
509 // Here we want to prevent struct constructors from returning unsized types.
510 // There were two cases this happened: fn pointer coercion in stable
511 // and usual function call in presense of unsized_locals.
512 // Also, as we just want to check sizedness, instead of introducing
513 // placeholder lifetimes with probing, we just replace higher lifetimes
515 let output = self.replace_bound_vars_with_fresh_vars(
517 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.tables.borrow().node_substs(expr.hir_id);
525 self.add_wf_bounds(substs, expr);
532 destination: hir::Destination,
533 expr_opt: Option<&'tcx hir::Expr>,
534 expr: &'tcx hir::Expr,
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 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
544 enclosing_breakables.find_breakable(target_id)
547 .map(|coerce| coerce.expected_ty())
550 // If the loop context is not a `loop { }`, then break with
551 // a value is illegal, and `opt_coerce_to` will be `None`.
552 // Just set expectation to error in that case.
553 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
555 // Recurse without `enclosing_breakables` borrowed.
556 e_ty = self.check_expr_with_hint(e, coerce_to);
557 cause = self.misc(e.span);
559 // Otherwise, this is a break *without* a value. That's
560 // always legal, and is equivalent to `break ()`.
561 e_ty = tcx.mk_unit();
562 cause = self.misc(expr.span);
565 // Now that we have type-checked `expr_opt`, borrow
566 // the `enclosing_loops` field and let's coerce the
567 // type of `expr_opt` into what is expected.
568 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
569 let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
571 None => { // Avoid ICE when `break` is inside a closure (#65383).
572 self.tcx.sess.delay_span_bug(
574 "break was outside loop, but no error was emitted",
576 return tcx.types.err;
580 if let Some(ref mut coerce) = ctxt.coerce {
581 if let Some(ref e) = expr_opt {
582 coerce.coerce(self, &cause, e, e_ty);
584 assert!(e_ty.is_unit());
585 let ty = coerce.expected_ty();
586 coerce.coerce_forced_unit(self, &cause, &mut |err| {
587 let val = match ty.kind {
590 ty::Int(_) | ty::Uint(_) => "42",
591 ty::Float(_) => "3.14159",
592 ty::Error | ty::Never => return,
595 let msg = "give it a value of the expected type";
596 let label = destination.label
597 .map(|l| format!(" {}", l.ident))
598 .unwrap_or_else(String::new);
599 let sugg = format!("break{} {}", label, val);
600 err.span_suggestion(expr.span, msg, sugg, Applicability::HasPlaceholders);
604 // If `ctxt.coerce` is `None`, we can just ignore
605 // the type of the expression. This is because
606 // either this was a break *without* a value, in
607 // which case it is always a legal type (`()`), or
608 // else an error would have been flagged by the
609 // `loops` pass for using break with an expression
610 // where you are not supposed to.
611 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
614 ctxt.may_break = true;
616 // the type of a `break` is always `!`, since it diverges
619 // Otherwise, we failed to find the enclosing loop;
620 // this can only happen if the `break` was not
621 // inside a loop at all, which is caught by the
622 // loop-checking pass.
623 self.tcx.sess.delay_span_bug(expr.span,
624 "break was outside loop, but no error was emitted");
626 // We still need to assign a type to the inner expression to
627 // prevent the ICE in #43162.
628 if let Some(ref e) = expr_opt {
629 self.check_expr_with_hint(e, tcx.types.err);
631 // ... except when we try to 'break rust;'.
632 // ICE this expression in particular (see #43162).
633 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
634 if path.segments.len() == 1 &&
635 path.segments[0].ident.name == sym::rust {
636 fatally_break_rust(self.tcx.sess);
640 // There was an error; make type-check fail.
645 fn check_expr_return(
647 expr_opt: Option<&'tcx hir::Expr>,
648 expr: &'tcx hir::Expr
650 if self.ret_coercion.is_none() {
655 "return statement outside of function body",
657 } else if let Some(ref e) = expr_opt {
658 if self.ret_coercion_span.borrow().is_none() {
659 *self.ret_coercion_span.borrow_mut() = Some(e.span);
661 self.check_return_expr(e);
663 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
664 if self.ret_coercion_span.borrow().is_none() {
665 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
667 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
668 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
669 coercion.coerce_forced_unit(
674 fn_decl.output.span(),
676 "expected `{}` because of this return type",
684 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
690 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
694 .unwrap_or_else(|| span_bug!(return_expr.span,
695 "check_return_expr called outside fn body"));
697 let ret_ty = ret_coercion.borrow().expected_ty();
698 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
699 ret_coercion.borrow_mut().coerce(
701 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
707 /// Type check assignment expression `expr` of form `lhs = rhs`.
708 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
709 fn check_expr_assign(
711 expr: &'tcx hir::Expr,
712 expected: Expectation<'tcx>,
713 lhs: &'tcx hir::Expr,
714 rhs: &'tcx hir::Expr,
716 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
717 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
719 let expected_ty = expected.coercion_target_type(self, expr.span);
720 if expected_ty == self.tcx.types.bool {
721 // The expected type is `bool` but this will result in `()` so we can reasonably
722 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
723 // The likely cause of this is `if foo = bar { .. }`.
724 let actual_ty = self.tcx.mk_unit();
725 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
726 let msg = "try comparing for equality";
727 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
728 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
729 if let (Ok(left), Ok(right)) = (left, right) {
730 let help = format!("{} == {}", left, right);
731 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
736 } else if !lhs.is_place_expr() {
737 struct_span_err!(self.tcx.sess, expr.span, E0070,
738 "invalid left-hand side expression")
739 .span_label(expr.span, "left-hand of expression not valid")
743 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
745 if lhs_ty.references_error() || rhs_ty.references_error() {
754 body: &'tcx hir::Block,
755 source: hir::LoopSource,
756 expected: Expectation<'tcx>,
757 expr: &'tcx hir::Expr,
759 let coerce = match source {
760 // you can only use break with a value from a normal `loop { }`
761 hir::LoopSource::Loop => {
762 let coerce_to = expected.coercion_target_type(self, body.span);
763 Some(CoerceMany::new(coerce_to))
766 hir::LoopSource::While |
767 hir::LoopSource::WhileLet |
768 hir::LoopSource::ForLoop => {
773 let ctxt = BreakableCtxt {
775 may_break: false, // Will get updated if/when we find a `break`.
778 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
779 self.check_block_no_value(&body);
783 // No way to know whether it's diverging because
784 // of a `break` or an outer `break` or `return`.
785 self.diverges.set(Diverges::Maybe);
788 // If we permit break with a value, then result type is
789 // the LUB of the breaks (possibly ! if none); else, it
790 // is nil. This makes sense because infinite loops
791 // (which would have type !) are only possible iff we
792 // permit break with a value [1].
793 if ctxt.coerce.is_none() && !ctxt.may_break {
795 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
797 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
800 /// Checks a method call.
801 fn check_method_call(
803 expr: &'tcx hir::Expr,
804 segment: &hir::PathSegment,
806 args: &'tcx [hir::Expr],
807 expected: Expectation<'tcx>,
811 let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
812 // no need to check for bot/err -- callee does that
813 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
815 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
817 self.write_method_call(expr.hir_id, method);
821 if segment.ident.name != kw::Invalid {
822 self.report_extended_method_error(segment, span, args, rcvr_t, error);
828 // Call the generic checker.
829 self.check_method_argument_types(
839 fn report_extended_method_error(
841 segment: &hir::PathSegment,
843 args: &'tcx [hir::Expr],
845 error: MethodError<'tcx>
848 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, rcvr_t, lang_item| {
849 if let Some(new_rcvr_t) = self.tcx.mk_lang_item(rcvr_t, lang_item) {
850 if let Ok(pick) = self.lookup_probe(
855 probe::ProbeScope::AllTraits,
858 pick.item.ident.span,
859 &format!("the method is available for `{}` here", new_rcvr_t),
865 if let Some(mut err) = self.report_method_error(
869 SelfSource::MethodCall(rcvr),
873 if let ty::Adt(..) = rcvr_t.kind {
874 // Try alternative arbitrary self types that could fulfill this call.
875 // FIXME: probe for all types that *could* be arbitrary self-types, not
876 // just this whitelist.
877 try_alt_rcvr(&mut err, rcvr_t, lang_items::OwnedBoxLangItem);
878 try_alt_rcvr(&mut err, rcvr_t, lang_items::PinTypeLangItem);
879 try_alt_rcvr(&mut err, rcvr_t, lang_items::Arc);
880 try_alt_rcvr(&mut err, rcvr_t, lang_items::Rc);
890 expr: &'tcx hir::Expr,
892 // Find the type of `e`. Supply hints based on the type we are casting to,
894 let t_cast = self.to_ty_saving_user_provided_ty(t);
895 let t_cast = self.resolve_vars_if_possible(&t_cast);
896 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
897 let t_cast = self.resolve_vars_if_possible(&t_cast);
899 // Eagerly check for some obvious errors.
900 if t_expr.references_error() || t_cast.references_error() {
903 // Defer other checks until we're done type checking.
904 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
905 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
907 deferred_cast_checks.push(cast_check);
910 Err(ErrorReported) => {
919 args: &'tcx [hir::Expr],
920 expected: Expectation<'tcx>,
921 expr: &'tcx hir::Expr
923 let uty = expected.to_option(self).and_then(|uty| {
925 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
930 let element_ty = if !args.is_empty() {
931 let coerce_to = uty.unwrap_or_else(|| {
932 self.next_ty_var(TypeVariableOrigin {
933 kind: TypeVariableOriginKind::TypeInference,
937 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
938 assert_eq!(self.diverges.get(), Diverges::Maybe);
940 let e_ty = self.check_expr_with_hint(e, coerce_to);
941 let cause = self.misc(e.span);
942 coerce.coerce(self, &cause, e, e_ty);
944 coerce.complete(self)
946 self.next_ty_var(TypeVariableOrigin {
947 kind: TypeVariableOriginKind::TypeInference,
951 self.tcx.mk_array(element_ty, args.len() as u64)
954 fn check_expr_repeat(
956 element: &'tcx hir::Expr,
957 count: &'tcx hir::AnonConst,
958 expected: Expectation<'tcx>,
959 _expr: &'tcx hir::Expr,
962 let count_def_id = tcx.hir().local_def_id(count.hir_id);
963 let count = if self.const_param_def_id(count).is_some() {
964 Ok(self.to_const(count, tcx.type_of(count_def_id)))
966 let param_env = ty::ParamEnv::empty();
967 let substs = InternalSubsts::identity_for_item(tcx, count_def_id);
968 let instance = ty::Instance::resolve(
974 let global_id = GlobalId {
979 tcx.const_eval(param_env.and(global_id))
982 let uty = match expected {
983 ExpectHasType(uty) => {
985 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
992 let (element_ty, t) = match uty {
994 self.check_expr_coercable_to_type(&element, uty);
998 let ty = self.next_ty_var(TypeVariableOrigin {
999 kind: TypeVariableOriginKind::MiscVariable,
1002 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1007 if element_ty.references_error() {
1009 } else if let Ok(count) = count {
1010 tcx.mk_ty(ty::Array(t, count))
1016 fn check_expr_tuple(
1018 elts: &'tcx [hir::Expr],
1019 expected: Expectation<'tcx>,
1020 expr: &'tcx hir::Expr,
1022 let flds = expected.only_has_type(self).and_then(|ty| {
1023 let ty = self.resolve_vars_with_obligations(ty);
1025 ty::Tuple(ref flds) => Some(&flds[..]),
1030 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
1031 let t = match flds {
1032 Some(ref fs) if i < fs.len() => {
1033 let ety = fs[i].expect_ty();
1034 self.check_expr_coercable_to_type(&e, ety);
1038 self.check_expr_with_expectation(&e, NoExpectation)
1043 let tuple = self.tcx.mk_tup(elt_ts_iter);
1044 if tuple.references_error() {
1047 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1052 fn check_expr_struct(
1055 expected: Expectation<'tcx>,
1057 fields: &'tcx [hir::Field],
1058 base_expr: &'tcx Option<P<hir::Expr>>,
1060 // Find the relevant variant
1061 let (variant, adt_ty) =
1062 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1065 self.check_struct_fields_on_error(fields, base_expr);
1066 return self.tcx.types.err;
1069 let path_span = match *qpath {
1070 QPath::Resolved(_, ref path) => path.span,
1071 QPath::TypeRelative(ref qself, _) => qself.span
1074 // Prohibit struct expressions when non-exhaustive flag is set.
1075 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1076 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1077 span_err!(self.tcx.sess, expr.span, E0639,
1078 "cannot create non-exhaustive {} using struct expression",
1079 adt.variant_descr());
1082 let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1083 variant, fields, base_expr.is_none());
1084 if let &Some(ref base_expr) = base_expr {
1085 // If check_expr_struct_fields hit an error, do not attempt to populate
1086 // the fields with the base_expr. This could cause us to hit errors later
1087 // when certain fields are assumed to exist that in fact do not.
1088 if !error_happened {
1089 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1091 ty::Adt(adt, substs) if adt.is_struct() => {
1092 let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1093 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1098 .fru_field_types_mut()
1099 .insert(expr.hir_id, fru_field_types);
1102 span_err!(self.tcx.sess, base_expr.span, E0436,
1103 "functional record update syntax requires a struct");
1108 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1112 fn check_expr_struct_fields(
1115 expected: Expectation<'tcx>,
1116 expr_id: hir::HirId,
1118 variant: &'tcx ty::VariantDef,
1119 ast_fields: &'tcx [hir::Field],
1120 check_completeness: bool,
1125 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1126 .get(0).cloned().unwrap_or(adt_ty);
1127 // re-link the regions that EIfEO can erase.
1128 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1130 let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1131 &ty::Adt(adt, substs) => {
1132 (substs, adt.adt_kind(), adt.variant_descr())
1134 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1137 let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1138 (field.ident.modern(), (i, field))
1139 ).collect::<FxHashMap<_, _>>();
1141 let mut seen_fields = FxHashMap::default();
1143 let mut error_happened = false;
1145 // Type-check each field.
1146 for field in ast_fields {
1147 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1148 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1149 seen_fields.insert(ident, field.span);
1150 self.write_field_index(field.hir_id, i);
1152 // We don't look at stability attributes on
1153 // struct-like enums (yet...), but it's definitely not
1154 // a bug to have constructed one.
1155 if adt_kind != AdtKind::Enum {
1156 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1159 self.field_ty(field.span, v_field, substs)
1161 error_happened = true;
1162 if let Some(prev_span) = seen_fields.get(&ident) {
1163 let mut err = struct_span_err!(self.tcx.sess,
1166 "field `{}` specified more than once",
1169 err.span_label(field.ident.span, "used more than once");
1170 err.span_label(*prev_span, format!("first use of `{}`", ident));
1174 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1180 // Make sure to give a type to the field even if there's
1181 // an error, so we can continue type-checking.
1182 self.check_expr_coercable_to_type(&field.expr, field_type);
1185 // Make sure the programmer specified correct number of fields.
1186 if kind_name == "union" {
1187 if ast_fields.len() != 1 {
1188 tcx.sess.span_err(span, "union expressions should have exactly one field");
1190 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1191 let len = remaining_fields.len();
1193 let mut displayable_field_names = remaining_fields
1195 .map(|ident| ident.as_str())
1196 .collect::<Vec<_>>();
1198 displayable_field_names.sort();
1200 let truncated_fields_error = if len <= 3 {
1203 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1206 let remaining_fields_names = displayable_field_names.iter().take(3)
1207 .map(|n| format!("`{}`", n))
1208 .collect::<Vec<_>>()
1211 struct_span_err!(tcx.sess, span, E0063,
1212 "missing field{} {}{} in initializer of `{}`",
1213 pluralise!(remaining_fields.len()),
1214 remaining_fields_names,
1215 truncated_fields_error,
1217 .span_label(span, format!("missing {}{}",
1218 remaining_fields_names,
1219 truncated_fields_error))
1225 fn check_struct_fields_on_error(
1227 fields: &'tcx [hir::Field],
1228 base_expr: &'tcx Option<P<hir::Expr>>,
1230 for field in fields {
1231 self.check_expr(&field.expr);
1233 if let Some(ref base) = *base_expr {
1234 self.check_expr(&base);
1238 fn report_unknown_field(
1241 variant: &'tcx ty::VariantDef,
1243 skip_fields: &[hir::Field],
1247 if variant.recovered {
1250 let mut err = self.type_error_struct_with_diag(
1252 |actual| match ty.kind {
1253 ty::Adt(adt, ..) if adt.is_enum() => {
1254 struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1255 "{} `{}::{}` has no field named `{}`",
1256 kind_name, actual, variant.ident, field.ident)
1259 struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1260 "{} `{}` has no field named `{}`",
1261 kind_name, actual, field.ident)
1265 match variant.ctor_kind {
1267 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1268 err.span_label(field.ident.span, "field does not exist");
1269 err.span_label(ty_span, format!(
1270 "`{adt}` is a tuple {kind_name}, \
1271 use the appropriate syntax: `{adt}(/* fields */)`",
1277 // prevent all specified fields from being suggested
1278 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1279 if let Some(field_name) = Self::suggest_field_name(
1281 &field.ident.as_str(),
1282 skip_fields.collect()
1284 err.span_suggestion(
1286 "a field with a similar name exists",
1287 field_name.to_string(),
1288 Applicability::MaybeIncorrect,
1292 ty::Adt(adt, ..) => {
1294 err.span_label(field.ident.span, format!(
1295 "`{}::{}` does not have this field",
1300 err.span_label(field.ident.span, format!(
1301 "`{}` does not have this field",
1305 let available_field_names = self.available_field_names(variant);
1306 if !available_field_names.is_empty() {
1307 err.note(&format!("available fields are: {}",
1308 self.name_series_display(available_field_names)));
1311 _ => bug!("non-ADT passed to report_unknown_field")
1319 // Return an hint about the closest match in field names
1320 fn suggest_field_name(variant: &'tcx ty::VariantDef,
1324 let names = variant.fields.iter().filter_map(|field| {
1325 // ignore already set fields and private fields from non-local crates
1326 if skip.iter().any(|&x| x == field.ident.name) ||
1327 (!variant.def_id.is_local() && field.vis != Visibility::Public)
1331 Some(&field.ident.name)
1335 find_best_match_for_name(names, field, None)
1338 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1339 variant.fields.iter().filter(|field| {
1341 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1342 field.vis.is_accessible_from(def_scope, self.tcx)
1344 .map(|field| field.ident.name)
1348 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1349 // dynamic limit, to never omit just one field
1350 let limit = if names.len() == 6 { 6 } else { 5 };
1351 let mut display = names.iter().take(limit)
1352 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1353 if names.len() > limit {
1354 display = format!("{} ... and {} others", display, names.len() - limit);
1359 // Check field access expressions
1362 expr: &'tcx hir::Expr,
1364 base: &'tcx hir::Expr,
1367 let expr_t = self.check_expr_with_needs(base, needs);
1368 let expr_t = self.structurally_resolved_type(base.span,
1370 let mut private_candidate = None;
1371 let mut autoderef = self.autoderef(expr.span, expr_t);
1372 while let Some((base_t, _)) = autoderef.next() {
1374 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1375 debug!("struct named {:?}", base_t);
1376 let (ident, def_scope) =
1377 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1378 let fields = &base_def.non_enum_variant().fields;
1379 if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1380 let field = &fields[index];
1381 let field_ty = self.field_ty(expr.span, field, substs);
1382 // Save the index of all fields regardless of their visibility in case
1383 // of error recovery.
1384 self.write_field_index(expr.hir_id, index);
1385 if field.vis.is_accessible_from(def_scope, self.tcx) {
1386 let adjustments = autoderef.adjust_steps(self, needs);
1387 self.apply_adjustments(base, adjustments);
1388 autoderef.finalize(self);
1390 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1393 private_candidate = Some((base_def.did, field_ty));
1396 ty::Tuple(ref tys) => {
1397 let fstr = field.as_str();
1398 if let Ok(index) = fstr.parse::<usize>() {
1399 if fstr == index.to_string() {
1400 if let Some(field_ty) = tys.get(index) {
1401 let adjustments = autoderef.adjust_steps(self, needs);
1402 self.apply_adjustments(base, adjustments);
1403 autoderef.finalize(self);
1405 self.write_field_index(expr.hir_id, index);
1406 return field_ty.expect_ty();
1414 autoderef.unambiguous_final_ty(self);
1416 if let Some((did, field_ty)) = private_candidate {
1417 self.ban_private_field_access(expr, expr_t, field, did);
1421 if field.name == kw::Invalid {
1422 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1423 self.ban_take_value_of_method(expr, expr_t, field);
1424 } else if !expr_t.is_primitive_ty() {
1425 self.ban_nonexisting_field(field, base, expr, expr_t);
1432 "`{}` is a primitive type and therefore doesn't have fields",
1438 self.tcx().types.err
1441 fn ban_nonexisting_field(
1444 base: &'tcx hir::Expr,
1445 expr: &'tcx hir::Expr,
1448 let mut err = self.no_such_field_err(field.span, field, expr_t);
1450 match expr_t.peel_refs().kind {
1451 ty::Array(_, len) => {
1452 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1455 self.suggest_first_deref_field(&mut err, expr, base, field);
1457 ty::Adt(def, _) if !def.is_enum() => {
1458 self.suggest_fields_on_recordish(&mut err, def, field);
1460 ty::Param(param_ty) => {
1461 self.point_at_param_definition(&mut err, param_ty);
1466 if field.name == kw::Await {
1467 // We know by construction that `<expr>.await` is either on Rust 2015
1468 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1469 err.note("to `.await` a `Future`, switch to Rust 2018");
1470 err.help("set `edition = \"2018\"` in `Cargo.toml`");
1471 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1477 fn ban_private_field_access(
1484 let struct_path = self.tcx().def_path_str(base_did);
1485 let kind_name = match self.tcx().def_kind(base_did) {
1486 Some(def_kind) => def_kind.descr(base_did),
1489 let mut err = struct_span_err!(
1493 "field `{}` of {} `{}` is private",
1498 // Also check if an accessible method exists, which is often what is meant.
1499 if self.method_exists(field, expr_t, expr.hir_id, false)
1500 && !self.expr_in_place(expr.hir_id)
1502 self.suggest_method_call(
1504 &format!("a method `{}` also exists, call it with parentheses", field),
1513 fn ban_take_value_of_method(&self, expr: &hir::Expr, expr_t: Ty<'tcx>, field: ast::Ident) {
1514 let mut err = type_error_struct!(
1519 "attempted to take value of method `{}` on type `{}`",
1524 if !self.expr_in_place(expr.hir_id) {
1525 self.suggest_method_call(
1527 "use parentheses to call the method",
1533 err.help("methods are immutable and cannot be assigned to");
1539 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1540 let generics = self.tcx.generics_of(self.body_id.owner_def_id());
1541 let generic_param = generics.type_param(¶m, self.tcx);
1542 if let ty::GenericParamDefKind::Type{synthetic: Some(..), ..} = generic_param.kind {
1545 let param_def_id = generic_param.def_id;
1546 let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
1550 let param_span = self.tcx.hir().span(param_hir_id);
1551 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1553 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1556 fn suggest_fields_on_recordish(
1558 err: &mut DiagnosticBuilder<'_>,
1559 def: &'tcx ty::AdtDef,
1562 if let Some(suggested_field_name) =
1563 Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
1565 err.span_suggestion(
1567 "a field with a similar name exists",
1568 suggested_field_name.to_string(),
1569 Applicability::MaybeIncorrect,
1572 err.span_label(field.span, "unknown field");
1573 let struct_variant_def = def.non_enum_variant();
1574 let field_names = self.available_field_names(struct_variant_def);
1575 if !field_names.is_empty() {
1577 "available fields are: {}",
1578 self.name_series_display(field_names),
1584 fn maybe_suggest_array_indexing(
1586 err: &mut DiagnosticBuilder<'_>,
1590 len: &ty::Const<'tcx>,
1592 if let (Some(len), Ok(user_index)) = (
1593 len.try_eval_usize(self.tcx, self.param_env),
1594 field.as_str().parse::<u64>()
1596 let base = self.tcx.sess.source_map()
1597 .span_to_snippet(base.span)
1598 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1599 let help = "instead of using tuple indexing, use array indexing";
1600 let suggestion = format!("{}[{}]", base, field);
1601 let applicability = if len < user_index {
1602 Applicability::MachineApplicable
1604 Applicability::MaybeIncorrect
1606 err.span_suggestion(expr.span, help, suggestion, applicability);
1610 fn suggest_first_deref_field(
1612 err: &mut DiagnosticBuilder<'_>,
1617 let base = self.tcx.sess.source_map()
1618 .span_to_snippet(base.span)
1619 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1620 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1621 let suggestion = format!("(*{}).{}", base, field);
1622 err.span_suggestion(
1626 Applicability::MaybeIncorrect,
1630 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1631 -> DiagnosticBuilder<'_> {
1632 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1633 "no field `{}` on type `{}`",
1637 fn check_expr_index(
1639 base: &'tcx hir::Expr,
1640 idx: &'tcx hir::Expr,
1642 expr: &'tcx hir::Expr,
1644 let base_t = self.check_expr_with_needs(&base, needs);
1645 let idx_t = self.check_expr(&idx);
1647 if base_t.references_error() {
1649 } else if idx_t.references_error() {
1652 let base_t = self.structurally_resolved_type(base.span, base_t);
1653 match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1654 Some((index_ty, element_ty)) => {
1655 // two-phase not needed because index_ty is never mutable
1656 self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1661 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1662 "cannot index into a value of type `{}`",
1664 // Try to give some advice about indexing tuples.
1665 if let ty::Tuple(..) = base_t.kind {
1666 let mut needs_note = true;
1667 // If the index is an integer, we can show the actual
1668 // fixed expression:
1669 if let ExprKind::Lit(ref lit) = idx.kind {
1670 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1671 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1672 if let Ok(snip) = snip {
1673 err.span_suggestion(
1675 "to access tuple elements, use",
1676 format!("{}.{}", snip, i),
1677 Applicability::MachineApplicable,
1684 err.help("to access tuple elements, use tuple indexing \
1685 syntax (e.g., `tuple.0`)");
1695 fn check_expr_yield(
1697 value: &'tcx hir::Expr,
1698 expr: &'tcx hir::Expr,
1699 src: &'tcx hir::YieldSource
1701 match self.yield_ty {
1703 self.check_expr_coercable_to_type(&value, ty);
1705 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1706 // we know that the yield type must be `()`; however, the context won't contain this
1707 // information. Hence, we check the source of the yield expression here and check its
1708 // value's type against `()` (this check should always hold).
1709 None if src == &hir::YieldSource::Await => {
1710 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1713 struct_span_err!(self.tcx.sess, expr.span, E0627,
1714 "yield statement outside of generator literal").emit();