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 = enclosing_breakables.find_breakable(target_id);
570 if let Some(ref mut coerce) = ctxt.coerce {
571 if let Some(ref e) = expr_opt {
572 coerce.coerce(self, &cause, e, e_ty);
574 assert!(e_ty.is_unit());
575 let ty = coerce.expected_ty();
576 coerce.coerce_forced_unit(self, &cause, &mut |err| {
577 let val = match ty.kind {
580 ty::Int(_) | ty::Uint(_) => "42",
581 ty::Float(_) => "3.14159",
582 ty::Error | ty::Never => return,
585 let msg = "give it a value of the expected type";
586 let label = destination.label
587 .map(|l| format!(" {}", l.ident))
588 .unwrap_or_else(String::new);
589 let sugg = format!("break{} {}", label, val);
590 err.span_suggestion(expr.span, msg, sugg, Applicability::HasPlaceholders);
594 // If `ctxt.coerce` is `None`, we can just ignore
595 // the type of the expresison. This is because
596 // either this was a break *without* a value, in
597 // which case it is always a legal type (`()`), or
598 // else an error would have been flagged by the
599 // `loops` pass for using break with an expression
600 // where you are not supposed to.
601 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
604 ctxt.may_break = true;
606 // the type of a `break` is always `!`, since it diverges
609 // Otherwise, we failed to find the enclosing loop;
610 // this can only happen if the `break` was not
611 // inside a loop at all, which is caught by the
612 // loop-checking pass.
613 self.tcx.sess.delay_span_bug(expr.span,
614 "break was outside loop, but no error was emitted");
616 // We still need to assign a type to the inner expression to
617 // prevent the ICE in #43162.
618 if let Some(ref e) = expr_opt {
619 self.check_expr_with_hint(e, tcx.types.err);
621 // ... except when we try to 'break rust;'.
622 // ICE this expression in particular (see #43162).
623 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
624 if path.segments.len() == 1 &&
625 path.segments[0].ident.name == sym::rust {
626 fatally_break_rust(self.tcx.sess);
630 // There was an error; make type-check fail.
635 fn check_expr_return(
637 expr_opt: Option<&'tcx hir::Expr>,
638 expr: &'tcx hir::Expr
640 if self.ret_coercion.is_none() {
645 "return statement outside of function body",
647 } else if let Some(ref e) = expr_opt {
648 if self.ret_coercion_span.borrow().is_none() {
649 *self.ret_coercion_span.borrow_mut() = Some(e.span);
651 self.check_return_expr(e);
653 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
654 if self.ret_coercion_span.borrow().is_none() {
655 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
657 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
658 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
659 coercion.coerce_forced_unit(
664 fn_decl.output.span(),
666 "expected `{}` because of this return type",
674 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
680 pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
684 .unwrap_or_else(|| span_bug!(return_expr.span,
685 "check_return_expr called outside fn body"));
687 let ret_ty = ret_coercion.borrow().expected_ty();
688 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
689 ret_coercion.borrow_mut().coerce(
691 &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
697 /// Type check assignment expression `expr` of form `lhs = rhs`.
698 /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
699 fn check_expr_assign(
701 expr: &'tcx hir::Expr,
702 expected: Expectation<'tcx>,
703 lhs: &'tcx hir::Expr,
704 rhs: &'tcx hir::Expr,
706 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
707 let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
709 let expected_ty = expected.coercion_target_type(self, expr.span);
710 if expected_ty == self.tcx.types.bool {
711 // The expected type is `bool` but this will result in `()` so we can reasonably
712 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
713 // The likely cause of this is `if foo = bar { .. }`.
714 let actual_ty = self.tcx.mk_unit();
715 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
716 let msg = "try comparing for equality";
717 let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
718 let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
719 if let (Ok(left), Ok(right)) = (left, right) {
720 let help = format!("{} == {}", left, right);
721 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
726 } else if !lhs.is_place_expr() {
727 struct_span_err!(self.tcx.sess, expr.span, E0070,
728 "invalid left-hand side expression")
729 .span_label(expr.span, "left-hand of expression not valid")
733 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
735 if lhs_ty.references_error() || rhs_ty.references_error() {
744 body: &'tcx hir::Block,
745 source: hir::LoopSource,
746 expected: Expectation<'tcx>,
747 expr: &'tcx hir::Expr,
749 let coerce = match source {
750 // you can only use break with a value from a normal `loop { }`
751 hir::LoopSource::Loop => {
752 let coerce_to = expected.coercion_target_type(self, body.span);
753 Some(CoerceMany::new(coerce_to))
756 hir::LoopSource::While |
757 hir::LoopSource::WhileLet |
758 hir::LoopSource::ForLoop => {
763 let ctxt = BreakableCtxt {
765 may_break: false, // Will get updated if/when we find a `break`.
768 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
769 self.check_block_no_value(&body);
773 // No way to know whether it's diverging because
774 // of a `break` or an outer `break` or `return`.
775 self.diverges.set(Diverges::Maybe);
778 // If we permit break with a value, then result type is
779 // the LUB of the breaks (possibly ! if none); else, it
780 // is nil. This makes sense because infinite loops
781 // (which would have type !) are only possible iff we
782 // permit break with a value [1].
783 if ctxt.coerce.is_none() && !ctxt.may_break {
785 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
787 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
790 /// Checks a method call.
791 fn check_method_call(
793 expr: &'tcx hir::Expr,
794 segment: &hir::PathSegment,
796 args: &'tcx [hir::Expr],
797 expected: Expectation<'tcx>,
801 let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
802 // no need to check for bot/err -- callee does that
803 let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
805 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
807 self.write_method_call(expr.hir_id, method);
811 if segment.ident.name != kw::Invalid {
812 self.report_extended_method_error(segment, span, args, rcvr_t, error);
818 // Call the generic checker.
819 self.check_method_argument_types(
829 fn report_extended_method_error(
831 segment: &hir::PathSegment,
833 args: &'tcx [hir::Expr],
835 error: MethodError<'tcx>
838 let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, rcvr_t, lang_item| {
839 if let Some(new_rcvr_t) = self.tcx.mk_lang_item(rcvr_t, lang_item) {
840 if let Ok(pick) = self.lookup_probe(
845 probe::ProbeScope::AllTraits,
848 pick.item.ident.span,
849 &format!("the method is available for `{}` here", new_rcvr_t),
855 if let Some(mut err) = self.report_method_error(
859 SelfSource::MethodCall(rcvr),
863 if let ty::Adt(..) = rcvr_t.kind {
864 // Try alternative arbitrary self types that could fulfill this call.
865 // FIXME: probe for all types that *could* be arbitrary self-types, not
866 // just this whitelist.
867 try_alt_rcvr(&mut err, rcvr_t, lang_items::OwnedBoxLangItem);
868 try_alt_rcvr(&mut err, rcvr_t, lang_items::PinTypeLangItem);
869 try_alt_rcvr(&mut err, rcvr_t, lang_items::Arc);
870 try_alt_rcvr(&mut err, rcvr_t, lang_items::Rc);
880 expr: &'tcx hir::Expr,
882 // Find the type of `e`. Supply hints based on the type we are casting to,
884 let t_cast = self.to_ty_saving_user_provided_ty(t);
885 let t_cast = self.resolve_vars_if_possible(&t_cast);
886 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
887 let t_cast = self.resolve_vars_if_possible(&t_cast);
889 // Eagerly check for some obvious errors.
890 if t_expr.references_error() || t_cast.references_error() {
893 // Defer other checks until we're done type checking.
894 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
895 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
897 deferred_cast_checks.push(cast_check);
900 Err(ErrorReported) => {
909 args: &'tcx [hir::Expr],
910 expected: Expectation<'tcx>,
911 expr: &'tcx hir::Expr
913 let uty = expected.to_option(self).and_then(|uty| {
915 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
920 let element_ty = if !args.is_empty() {
921 let coerce_to = uty.unwrap_or_else(|| {
922 self.next_ty_var(TypeVariableOrigin {
923 kind: TypeVariableOriginKind::TypeInference,
927 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
928 assert_eq!(self.diverges.get(), Diverges::Maybe);
930 let e_ty = self.check_expr_with_hint(e, coerce_to);
931 let cause = self.misc(e.span);
932 coerce.coerce(self, &cause, e, e_ty);
934 coerce.complete(self)
936 self.next_ty_var(TypeVariableOrigin {
937 kind: TypeVariableOriginKind::TypeInference,
941 self.tcx.mk_array(element_ty, args.len() as u64)
944 fn check_expr_repeat(
946 element: &'tcx hir::Expr,
947 count: &'tcx hir::AnonConst,
948 expected: Expectation<'tcx>,
949 _expr: &'tcx hir::Expr,
952 let count_def_id = tcx.hir().local_def_id(count.hir_id);
953 let count = if self.const_param_def_id(count).is_some() {
954 Ok(self.to_const(count, tcx.type_of(count_def_id)))
956 let param_env = ty::ParamEnv::empty();
957 let substs = InternalSubsts::identity_for_item(tcx, count_def_id);
958 let instance = ty::Instance::resolve(
964 let global_id = GlobalId {
969 tcx.const_eval(param_env.and(global_id))
972 let uty = match expected {
973 ExpectHasType(uty) => {
975 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
982 let (element_ty, t) = match uty {
984 self.check_expr_coercable_to_type(&element, uty);
988 let ty = self.next_ty_var(TypeVariableOrigin {
989 kind: TypeVariableOriginKind::MiscVariable,
992 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
997 if element_ty.references_error() {
999 } else if let Ok(count) = count {
1000 tcx.mk_ty(ty::Array(t, count))
1006 fn check_expr_tuple(
1008 elts: &'tcx [hir::Expr],
1009 expected: Expectation<'tcx>,
1010 expr: &'tcx hir::Expr,
1012 let flds = expected.only_has_type(self).and_then(|ty| {
1013 let ty = self.resolve_vars_with_obligations(ty);
1015 ty::Tuple(ref flds) => Some(&flds[..]),
1020 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
1021 let t = match flds {
1022 Some(ref fs) if i < fs.len() => {
1023 let ety = fs[i].expect_ty();
1024 self.check_expr_coercable_to_type(&e, ety);
1028 self.check_expr_with_expectation(&e, NoExpectation)
1033 let tuple = self.tcx.mk_tup(elt_ts_iter);
1034 if tuple.references_error() {
1037 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1042 fn check_expr_struct(
1045 expected: Expectation<'tcx>,
1047 fields: &'tcx [hir::Field],
1048 base_expr: &'tcx Option<P<hir::Expr>>,
1050 // Find the relevant variant
1051 let (variant, adt_ty) =
1052 if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1055 self.check_struct_fields_on_error(fields, base_expr);
1056 return self.tcx.types.err;
1059 let path_span = match *qpath {
1060 QPath::Resolved(_, ref path) => path.span,
1061 QPath::TypeRelative(ref qself, _) => qself.span
1064 // Prohibit struct expressions when non-exhaustive flag is set.
1065 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1066 if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1067 span_err!(self.tcx.sess, expr.span, E0639,
1068 "cannot create non-exhaustive {} using struct expression",
1069 adt.variant_descr());
1072 let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1073 variant, fields, base_expr.is_none());
1074 if let &Some(ref base_expr) = base_expr {
1075 // If check_expr_struct_fields hit an error, do not attempt to populate
1076 // the fields with the base_expr. This could cause us to hit errors later
1077 // when certain fields are assumed to exist that in fact do not.
1078 if !error_happened {
1079 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1081 ty::Adt(adt, substs) if adt.is_struct() => {
1082 let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1083 self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1088 .fru_field_types_mut()
1089 .insert(expr.hir_id, fru_field_types);
1092 span_err!(self.tcx.sess, base_expr.span, E0436,
1093 "functional record update syntax requires a struct");
1098 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1102 fn check_expr_struct_fields(
1105 expected: Expectation<'tcx>,
1106 expr_id: hir::HirId,
1108 variant: &'tcx ty::VariantDef,
1109 ast_fields: &'tcx [hir::Field],
1110 check_completeness: bool,
1115 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1116 .get(0).cloned().unwrap_or(adt_ty);
1117 // re-link the regions that EIfEO can erase.
1118 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1120 let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1121 &ty::Adt(adt, substs) => {
1122 (substs, adt.adt_kind(), adt.variant_descr())
1124 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1127 let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1128 (field.ident.modern(), (i, field))
1129 ).collect::<FxHashMap<_, _>>();
1131 let mut seen_fields = FxHashMap::default();
1133 let mut error_happened = false;
1135 // Type-check each field.
1136 for field in ast_fields {
1137 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1138 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1139 seen_fields.insert(ident, field.span);
1140 self.write_field_index(field.hir_id, i);
1142 // We don't look at stability attributes on
1143 // struct-like enums (yet...), but it's definitely not
1144 // a bug to have constructed one.
1145 if adt_kind != AdtKind::Enum {
1146 tcx.check_stability(v_field.did, Some(expr_id), field.span);
1149 self.field_ty(field.span, v_field, substs)
1151 error_happened = true;
1152 if let Some(prev_span) = seen_fields.get(&ident) {
1153 let mut err = struct_span_err!(self.tcx.sess,
1156 "field `{}` specified more than once",
1159 err.span_label(field.ident.span, "used more than once");
1160 err.span_label(*prev_span, format!("first use of `{}`", ident));
1164 self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1170 // Make sure to give a type to the field even if there's
1171 // an error, so we can continue type-checking.
1172 self.check_expr_coercable_to_type(&field.expr, field_type);
1175 // Make sure the programmer specified correct number of fields.
1176 if kind_name == "union" {
1177 if ast_fields.len() != 1 {
1178 tcx.sess.span_err(span, "union expressions should have exactly one field");
1180 } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1181 let len = remaining_fields.len();
1183 let mut displayable_field_names = remaining_fields
1185 .map(|ident| ident.as_str())
1186 .collect::<Vec<_>>();
1188 displayable_field_names.sort();
1190 let truncated_fields_error = if len <= 3 {
1193 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1196 let remaining_fields_names = displayable_field_names.iter().take(3)
1197 .map(|n| format!("`{}`", n))
1198 .collect::<Vec<_>>()
1201 struct_span_err!(tcx.sess, span, E0063,
1202 "missing field{} {}{} in initializer of `{}`",
1203 pluralise!(remaining_fields.len()),
1204 remaining_fields_names,
1205 truncated_fields_error,
1207 .span_label(span, format!("missing {}{}",
1208 remaining_fields_names,
1209 truncated_fields_error))
1215 fn check_struct_fields_on_error(
1217 fields: &'tcx [hir::Field],
1218 base_expr: &'tcx Option<P<hir::Expr>>,
1220 for field in fields {
1221 self.check_expr(&field.expr);
1223 if let Some(ref base) = *base_expr {
1224 self.check_expr(&base);
1228 fn report_unknown_field(
1231 variant: &'tcx ty::VariantDef,
1233 skip_fields: &[hir::Field],
1237 if variant.recovered {
1240 let mut err = self.type_error_struct_with_diag(
1242 |actual| match ty.kind {
1243 ty::Adt(adt, ..) if adt.is_enum() => {
1244 struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1245 "{} `{}::{}` has no field named `{}`",
1246 kind_name, actual, variant.ident, field.ident)
1249 struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1250 "{} `{}` has no field named `{}`",
1251 kind_name, actual, field.ident)
1255 match variant.ctor_kind {
1257 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1258 err.span_label(field.ident.span, "field does not exist");
1259 err.span_label(ty_span, format!(
1260 "`{adt}` is a tuple {kind_name}, \
1261 use the appropriate syntax: `{adt}(/* fields */)`",
1267 // prevent all specified fields from being suggested
1268 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1269 if let Some(field_name) = Self::suggest_field_name(
1271 &field.ident.as_str(),
1272 skip_fields.collect()
1274 err.span_suggestion(
1276 "a field with a similar name exists",
1277 field_name.to_string(),
1278 Applicability::MaybeIncorrect,
1282 ty::Adt(adt, ..) => {
1284 err.span_label(field.ident.span, format!(
1285 "`{}::{}` does not have this field",
1290 err.span_label(field.ident.span, format!(
1291 "`{}` does not have this field",
1295 let available_field_names = self.available_field_names(variant);
1296 if !available_field_names.is_empty() {
1297 err.note(&format!("available fields are: {}",
1298 self.name_series_display(available_field_names)));
1301 _ => bug!("non-ADT passed to report_unknown_field")
1309 // Return an hint about the closest match in field names
1310 fn suggest_field_name(variant: &'tcx ty::VariantDef,
1314 let names = variant.fields.iter().filter_map(|field| {
1315 // ignore already set fields and private fields from non-local crates
1316 if skip.iter().any(|&x| x == field.ident.name) ||
1317 (!variant.def_id.is_local() && field.vis != Visibility::Public)
1321 Some(&field.ident.name)
1325 find_best_match_for_name(names, field, None)
1328 fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1329 variant.fields.iter().filter(|field| {
1331 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1332 field.vis.is_accessible_from(def_scope, self.tcx)
1334 .map(|field| field.ident.name)
1338 fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1339 // dynamic limit, to never omit just one field
1340 let limit = if names.len() == 6 { 6 } else { 5 };
1341 let mut display = names.iter().take(limit)
1342 .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1343 if names.len() > limit {
1344 display = format!("{} ... and {} others", display, names.len() - limit);
1349 // Check field access expressions
1352 expr: &'tcx hir::Expr,
1354 base: &'tcx hir::Expr,
1357 let expr_t = self.check_expr_with_needs(base, needs);
1358 let expr_t = self.structurally_resolved_type(base.span,
1360 let mut private_candidate = None;
1361 let mut autoderef = self.autoderef(expr.span, expr_t);
1362 while let Some((base_t, _)) = autoderef.next() {
1364 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1365 debug!("struct named {:?}", base_t);
1366 let (ident, def_scope) =
1367 self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1368 let fields = &base_def.non_enum_variant().fields;
1369 if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1370 let field = &fields[index];
1371 let field_ty = self.field_ty(expr.span, field, substs);
1372 // Save the index of all fields regardless of their visibility in case
1373 // of error recovery.
1374 self.write_field_index(expr.hir_id, index);
1375 if field.vis.is_accessible_from(def_scope, self.tcx) {
1376 let adjustments = autoderef.adjust_steps(self, needs);
1377 self.apply_adjustments(base, adjustments);
1378 autoderef.finalize(self);
1380 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1383 private_candidate = Some((base_def.did, field_ty));
1386 ty::Tuple(ref tys) => {
1387 let fstr = field.as_str();
1388 if let Ok(index) = fstr.parse::<usize>() {
1389 if fstr == index.to_string() {
1390 if let Some(field_ty) = tys.get(index) {
1391 let adjustments = autoderef.adjust_steps(self, needs);
1392 self.apply_adjustments(base, adjustments);
1393 autoderef.finalize(self);
1395 self.write_field_index(expr.hir_id, index);
1396 return field_ty.expect_ty();
1404 autoderef.unambiguous_final_ty(self);
1406 if let Some((did, field_ty)) = private_candidate {
1407 self.ban_private_field_access(expr, expr_t, field, did);
1411 if field.name == kw::Invalid {
1412 } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1413 self.ban_take_value_of_method(expr, expr_t, field);
1414 } else if !expr_t.is_primitive_ty() {
1415 self.ban_nonexisting_field(field, base, expr, expr_t);
1422 "`{}` is a primitive type and therefore doesn't have fields",
1428 self.tcx().types.err
1431 fn ban_nonexisting_field(
1434 base: &'tcx hir::Expr,
1435 expr: &'tcx hir::Expr,
1438 let mut err = self.no_such_field_err(field.span, field, expr_t);
1440 match expr_t.peel_refs().kind {
1441 ty::Array(_, len) => {
1442 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1445 self.suggest_first_deref_field(&mut err, expr, base, field);
1447 ty::Adt(def, _) if !def.is_enum() => {
1448 self.suggest_fields_on_recordish(&mut err, def, field);
1450 ty::Param(param_ty) => {
1451 self.point_at_param_definition(&mut err, param_ty);
1456 if field.name == kw::Await {
1457 // We know by construction that `<expr>.await` is either on Rust 2015
1458 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1459 err.note("to `.await` a `Future`, switch to Rust 2018");
1460 err.help("set `edition = \"2018\"` in `Cargo.toml`");
1461 err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1467 fn ban_private_field_access(
1474 let struct_path = self.tcx().def_path_str(base_did);
1475 let kind_name = match self.tcx().def_kind(base_did) {
1476 Some(def_kind) => def_kind.descr(base_did),
1479 let mut err = struct_span_err!(
1483 "field `{}` of {} `{}` is private",
1488 // Also check if an accessible method exists, which is often what is meant.
1489 if self.method_exists(field, expr_t, expr.hir_id, false)
1490 && !self.expr_in_place(expr.hir_id)
1492 self.suggest_method_call(
1494 &format!("a method `{}` also exists, call it with parentheses", field),
1503 fn ban_take_value_of_method(&self, expr: &hir::Expr, expr_t: Ty<'tcx>, field: ast::Ident) {
1504 let mut err = type_error_struct!(
1509 "attempted to take value of method `{}` on type `{}`",
1514 if !self.expr_in_place(expr.hir_id) {
1515 self.suggest_method_call(
1517 "use parentheses to call the method",
1523 err.help("methods are immutable and cannot be assigned to");
1529 fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1530 let generics = self.tcx.generics_of(self.body_id.owner_def_id());
1531 let generic_param = generics.type_param(¶m, self.tcx);
1532 if let ty::GenericParamDefKind::Type{synthetic: Some(..), ..} = generic_param.kind {
1535 let param_def_id = generic_param.def_id;
1536 let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
1540 let param_span = self.tcx.hir().span(param_hir_id);
1541 let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1543 err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1546 fn suggest_fields_on_recordish(
1548 err: &mut DiagnosticBuilder<'_>,
1549 def: &'tcx ty::AdtDef,
1552 if let Some(suggested_field_name) =
1553 Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
1555 err.span_suggestion(
1557 "a field with a similar name exists",
1558 suggested_field_name.to_string(),
1559 Applicability::MaybeIncorrect,
1562 err.span_label(field.span, "unknown field");
1563 let struct_variant_def = def.non_enum_variant();
1564 let field_names = self.available_field_names(struct_variant_def);
1565 if !field_names.is_empty() {
1567 "available fields are: {}",
1568 self.name_series_display(field_names),
1574 fn maybe_suggest_array_indexing(
1576 err: &mut DiagnosticBuilder<'_>,
1580 len: &ty::Const<'tcx>,
1582 if let (Some(len), Ok(user_index)) = (
1583 len.try_eval_usize(self.tcx, self.param_env),
1584 field.as_str().parse::<u64>()
1586 let base = self.tcx.sess.source_map()
1587 .span_to_snippet(base.span)
1588 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1589 let help = "instead of using tuple indexing, use array indexing";
1590 let suggestion = format!("{}[{}]", base, field);
1591 let applicability = if len < user_index {
1592 Applicability::MachineApplicable
1594 Applicability::MaybeIncorrect
1596 err.span_suggestion(expr.span, help, suggestion, applicability);
1600 fn suggest_first_deref_field(
1602 err: &mut DiagnosticBuilder<'_>,
1607 let base = self.tcx.sess.source_map()
1608 .span_to_snippet(base.span)
1609 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1610 let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1611 let suggestion = format!("(*{}).{}", base, field);
1612 err.span_suggestion(
1616 Applicability::MaybeIncorrect,
1620 fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1621 -> DiagnosticBuilder<'_> {
1622 type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1623 "no field `{}` on type `{}`",
1627 fn check_expr_index(
1629 base: &'tcx hir::Expr,
1630 idx: &'tcx hir::Expr,
1632 expr: &'tcx hir::Expr,
1634 let base_t = self.check_expr_with_needs(&base, needs);
1635 let idx_t = self.check_expr(&idx);
1637 if base_t.references_error() {
1639 } else if idx_t.references_error() {
1642 let base_t = self.structurally_resolved_type(base.span, base_t);
1643 match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1644 Some((index_ty, element_ty)) => {
1645 // two-phase not needed because index_ty is never mutable
1646 self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1651 type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1652 "cannot index into a value of type `{}`",
1654 // Try to give some advice about indexing tuples.
1655 if let ty::Tuple(..) = base_t.kind {
1656 let mut needs_note = true;
1657 // If the index is an integer, we can show the actual
1658 // fixed expression:
1659 if let ExprKind::Lit(ref lit) = idx.kind {
1660 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1661 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1662 if let Ok(snip) = snip {
1663 err.span_suggestion(
1665 "to access tuple elements, use",
1666 format!("{}.{}", snip, i),
1667 Applicability::MachineApplicable,
1674 err.help("to access tuple elements, use tuple indexing \
1675 syntax (e.g., `tuple.0`)");
1685 fn check_expr_yield(
1687 value: &'tcx hir::Expr,
1688 expr: &'tcx hir::Expr,
1689 src: &'tcx hir::YieldSource
1691 match self.yield_ty {
1693 self.check_expr_coercable_to_type(&value, ty);
1695 // Given that this `yield` expression was generated as a result of lowering a `.await`,
1696 // we know that the yield type must be `()`; however, the context won't contain this
1697 // information. Hence, we check the source of the yield expression here and check its
1698 // value's type against `()` (this check should always hold).
1699 None if src == &hir::YieldSource::Await => {
1700 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1703 struct_span_err!(self.tcx.sess, expr.span, E0627,
1704 "yield statement outside of generator literal").emit();