]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/expr.rs
compiletest: Do not run debuginfo tests with gdb on msvc targets
[rust.git] / src / librustc_typeck / check / expr.rs
1 //! Type checking expressions.
2 //!
3 //! See `mod.rs` for more context on type checking in general.
4
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;
18 use crate::util::common::ErrorReported;
19
20 use rustc::infer;
21 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
22 use rustc::middle::lang_items;
23 use rustc::traits::{self, ObligationCauseCode};
24 use rustc::ty;
25 use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
26 use rustc::ty::Ty;
27 use rustc::ty::TypeFoldable;
28 use rustc::ty::{AdtKind, Visibility};
29 use rustc_data_structures::fx::FxHashMap;
30 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId};
31 use rustc_hir as hir;
32 use rustc_hir::def::{CtorKind, DefKind, Res};
33 use rustc_hir::def_id::DefId;
34 use rustc_hir::{ExprKind, QPath};
35 use rustc_span::hygiene::DesugaringKind;
36 use rustc_span::source_map::Span;
37 use rustc_span::symbol::{kw, sym, Symbol};
38 use syntax::ast;
39 use syntax::util::lev_distance::find_best_match_for_name;
40
41 use std::fmt::Display;
42
43 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
44     fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
45         let ty = self.check_expr_with_hint(expr, expected);
46         self.demand_eqtype(expr.span, expected, ty);
47     }
48
49     pub fn check_expr_has_type_or_error(
50         &self,
51         expr: &'tcx hir::Expr<'tcx>,
52         expected: Ty<'tcx>,
53         extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
54     ) -> Ty<'tcx> {
55         self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
56     }
57
58     fn check_expr_meets_expectation_or_error(
59         &self,
60         expr: &'tcx hir::Expr<'tcx>,
61         expected: Expectation<'tcx>,
62         extend_err: impl Fn(&mut DiagnosticBuilder<'_>),
63     ) -> Ty<'tcx> {
64         let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
65         let mut ty = self.check_expr_with_expectation(expr, expected);
66
67         // While we don't allow *arbitrary* coercions here, we *do* allow
68         // coercions from ! to `expected`.
69         if ty.is_never() {
70             assert!(
71                 !self.tables.borrow().adjustments().contains_key(expr.hir_id),
72                 "expression with never type wound up being adjusted"
73             );
74             let adj_ty = self.next_diverging_ty_var(TypeVariableOrigin {
75                 kind: TypeVariableOriginKind::AdjustmentType,
76                 span: expr.span,
77             });
78             self.apply_adjustments(
79                 expr,
80                 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
81             );
82             ty = adj_ty;
83         }
84
85         if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
86             let expr = expr.peel_drop_temps();
87             self.suggest_ref_or_into(&mut err, expr, expected_ty, ty);
88             extend_err(&mut err);
89             // Error possibly reported in `check_assign` so avoid emitting error again.
90             err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
91         }
92         ty
93     }
94
95     pub(super) fn check_expr_coercable_to_type(
96         &self,
97         expr: &'tcx hir::Expr<'tcx>,
98         expected: Ty<'tcx>,
99     ) -> Ty<'tcx> {
100         let ty = self.check_expr_with_hint(expr, expected);
101         // checks don't need two phase
102         self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
103     }
104
105     pub(super) fn check_expr_with_hint(
106         &self,
107         expr: &'tcx hir::Expr<'tcx>,
108         expected: Ty<'tcx>,
109     ) -> Ty<'tcx> {
110         self.check_expr_with_expectation(expr, ExpectHasType(expected))
111     }
112
113     pub(super) fn check_expr_with_expectation(
114         &self,
115         expr: &'tcx hir::Expr<'tcx>,
116         expected: Expectation<'tcx>,
117     ) -> Ty<'tcx> {
118         self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
119     }
120
121     pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
122         self.check_expr_with_expectation(expr, NoExpectation)
123     }
124
125     pub(super) fn check_expr_with_needs(
126         &self,
127         expr: &'tcx hir::Expr<'tcx>,
128         needs: Needs,
129     ) -> Ty<'tcx> {
130         self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
131     }
132
133     /// Invariant:
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(
144         &self,
145         expr: &'tcx hir::Expr<'tcx>,
146         expected: Expectation<'tcx>,
147         needs: Needs,
148     ) -> Ty<'tcx> {
149         debug!(">> type-checking: expr={:?} expected={:?}", expr, expected);
150
151         // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
152         // without the final expr (e.g. `try { return; }`). We don't want to generate an
153         // unreachable_code lint for it since warnings for autogenerated code are confusing.
154         let is_try_block_generated_unit_expr = match expr.kind {
155             ExprKind::Call(_, ref args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
156                 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
157             }
158
159             _ => false,
160         };
161
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");
165         }
166
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);
172
173         let ty = self.check_expr_kind(expr, expected, needs);
174
175         // Warn for non-block expressions with diverging children.
176         match expr.kind {
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             }
185             ExprKind::MethodCall(_, ref span, _) => {
186                 self.warn_if_unreachable(expr.hir_id, *span, "call")
187             }
188             _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
189         }
190
191         // Any expression that produces a value of type `!` must have diverged
192         if ty.is_never() {
193             self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
194         }
195
196         // Record the type, which applies it effects.
197         // We need to do this after the warning above, so that
198         // we don't warn for the diverging expression itself.
199         self.write_ty(expr.hir_id, ty);
200
201         // Combine the diverging and has_error flags.
202         self.diverges.set(self.diverges.get() | old_diverges);
203         self.has_errors.set(self.has_errors.get() | old_has_errors);
204
205         debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
206         debug!("... {:?}, expected is {:?}", ty, expected);
207
208         ty
209     }
210
211     fn check_expr_kind(
212         &self,
213         expr: &'tcx hir::Expr<'tcx>,
214         expected: Expectation<'tcx>,
215         needs: Needs,
216     ) -> Ty<'tcx> {
217         debug!("check_expr_kind(expr={:?}, expected={:?}, needs={:?})", expr, expected, needs,);
218
219         let tcx = self.tcx;
220         match expr.kind {
221             ExprKind::Box(ref subexpr) => self.check_expr_box(subexpr, expected),
222             ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
223             ExprKind::Binary(op, ref lhs, ref rhs) => self.check_binop(expr, op, lhs, rhs),
224             ExprKind::Assign(ref lhs, ref rhs, ref span) => {
225                 self.check_expr_assign(expr, expected, lhs, rhs, span)
226             }
227             ExprKind::AssignOp(op, ref lhs, ref rhs) => self.check_binop_assign(expr, op, lhs, rhs),
228             ExprKind::Unary(unop, ref oprnd) => {
229                 self.check_expr_unary(unop, oprnd, expected, needs, expr)
230             }
231             ExprKind::AddrOf(kind, mutbl, ref oprnd) => {
232                 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
233             }
234             ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr),
235             ExprKind::InlineAsm(ref asm) => {
236                 for expr in asm.outputs_exprs.iter().chain(asm.inputs_exprs.iter()) {
237                     self.check_expr(expr);
238                 }
239                 tcx.mk_unit()
240             }
241             ExprKind::Break(destination, ref expr_opt) => {
242                 self.check_expr_break(destination, expr_opt.as_deref(), expr)
243             }
244             ExprKind::Continue(destination) => {
245                 if destination.target_id.is_ok() {
246                     tcx.types.never
247                 } else {
248                     // There was an error; make type-check fail.
249                     tcx.types.err
250                 }
251             }
252             ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
253             ExprKind::Loop(ref body, _, source) => {
254                 self.check_expr_loop(body, source, expected, expr)
255             }
256             ExprKind::Match(ref discrim, ref arms, match_src) => {
257                 self.check_match(expr, &discrim, arms, expected, match_src)
258             }
259             ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
260                 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
261             }
262             ExprKind::Block(ref body, _) => self.check_block_with_expected(&body, expected),
263             ExprKind::Call(ref callee, ref args) => self.check_call(expr, &callee, args, expected),
264             ExprKind::MethodCall(ref segment, span, ref args) => {
265                 self.check_method_call(expr, segment, span, args, expected, needs)
266             }
267             ExprKind::Cast(ref e, ref t) => self.check_expr_cast(e, t, expr),
268             ExprKind::Type(ref e, ref t) => {
269                 let ty = self.to_ty_saving_user_provided_ty(&t);
270                 self.check_expr_eq_type(&e, ty);
271                 ty
272             }
273             ExprKind::DropTemps(ref e) => self.check_expr_with_expectation(e, expected),
274             ExprKind::Array(ref args) => self.check_expr_array(args, expected, expr),
275             ExprKind::Repeat(ref element, ref count) => {
276                 self.check_expr_repeat(element, count, expected, expr)
277             }
278             ExprKind::Tup(ref elts) => self.check_expr_tuple(elts, expected, expr),
279             ExprKind::Struct(ref qpath, fields, ref base_expr) => {
280                 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
281             }
282             ExprKind::Field(ref base, field) => self.check_field(expr, needs, &base, field),
283             ExprKind::Index(ref base, ref idx) => self.check_expr_index(base, idx, needs, expr),
284             ExprKind::Yield(ref value, ref src) => self.check_expr_yield(value, expr, src),
285             hir::ExprKind::Err => tcx.types.err,
286         }
287     }
288
289     fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
290         let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind {
291             ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
292             _ => NoExpectation,
293         });
294         let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
295         self.tcx.mk_box(referent_ty)
296     }
297
298     fn check_expr_unary(
299         &self,
300         unop: hir::UnOp,
301         oprnd: &'tcx hir::Expr<'tcx>,
302         expected: Expectation<'tcx>,
303         needs: Needs,
304         expr: &'tcx hir::Expr<'tcx>,
305     ) -> Ty<'tcx> {
306         let tcx = self.tcx;
307         let expected_inner = match unop {
308             hir::UnOp::UnNot | hir::UnOp::UnNeg => expected,
309             hir::UnOp::UnDeref => NoExpectation,
310         };
311         let needs = match unop {
312             hir::UnOp::UnDeref => needs,
313             _ => Needs::None,
314         };
315         let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
316
317         if !oprnd_t.references_error() {
318             oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
319             match unop {
320                 hir::UnOp::UnDeref => {
321                     if let Some(mt) = oprnd_t.builtin_deref(true) {
322                         oprnd_t = mt.ty;
323                     } else if let Some(ok) = self.try_overloaded_deref(expr.span, oprnd_t, needs) {
324                         let method = self.register_infer_ok_obligations(ok);
325                         if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].kind {
326                             let mutbl = match mutbl {
327                                 hir::Mutability::Not => AutoBorrowMutability::Not,
328                                 hir::Mutability::Mut => AutoBorrowMutability::Mut {
329                                     // (It shouldn't actually matter for unary ops whether
330                                     // we enable two-phase borrows or not, since a unary
331                                     // op has no additional operands.)
332                                     allow_two_phase_borrow: AllowTwoPhase::No,
333                                 },
334                             };
335                             self.apply_adjustments(
336                                 oprnd,
337                                 vec![Adjustment {
338                                     kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
339                                     target: method.sig.inputs()[0],
340                                 }],
341                             );
342                         }
343                         oprnd_t = self.make_overloaded_place_return_type(method).ty;
344                         self.write_method_call(expr.hir_id, method);
345                     } else {
346                         let mut err = type_error_struct!(
347                             tcx.sess,
348                             expr.span,
349                             oprnd_t,
350                             E0614,
351                             "type `{}` cannot be dereferenced",
352                             oprnd_t,
353                         );
354                         let sp = tcx.sess.source_map().start_point(expr.span);
355                         if let Some(sp) =
356                             tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
357                         {
358                             tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp, None);
359                         }
360                         err.emit();
361                         oprnd_t = tcx.types.err;
362                     }
363                 }
364                 hir::UnOp::UnNot => {
365                     let result = self.check_user_unop(expr, oprnd_t, unop);
366                     // If it's builtin, we can reuse the type, this helps inference.
367                     if !(oprnd_t.is_integral() || oprnd_t.kind == ty::Bool) {
368                         oprnd_t = result;
369                     }
370                 }
371                 hir::UnOp::UnNeg => {
372                     let result = self.check_user_unop(expr, oprnd_t, unop);
373                     // If it's builtin, we can reuse the type, this helps inference.
374                     if !oprnd_t.is_numeric() {
375                         oprnd_t = result;
376                     }
377                 }
378             }
379         }
380         oprnd_t
381     }
382
383     fn check_expr_addr_of(
384         &self,
385         kind: hir::BorrowKind,
386         mutbl: hir::Mutability,
387         oprnd: &'tcx hir::Expr<'tcx>,
388         expected: Expectation<'tcx>,
389         expr: &'tcx hir::Expr<'tcx>,
390     ) -> Ty<'tcx> {
391         let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
392             match ty.kind {
393                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
394                     if oprnd.is_syntactic_place_expr() {
395                         // Places may legitimately have unsized types.
396                         // For example, dereferences of a fat pointer and
397                         // the last field of a struct can be unsized.
398                         ExpectHasType(ty)
399                     } else {
400                         Expectation::rvalue_hint(self, ty)
401                     }
402                 }
403                 _ => NoExpectation,
404             }
405         });
406         let needs = Needs::maybe_mut_place(mutbl);
407         let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
408
409         let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
410         match kind {
411             _ if tm.ty.references_error() => self.tcx.types.err,
412             hir::BorrowKind::Raw => {
413                 self.check_named_place_expr(oprnd);
414                 self.tcx.mk_ptr(tm)
415             }
416             hir::BorrowKind::Ref => {
417                 // Note: at this point, we cannot say what the best lifetime
418                 // is to use for resulting pointer.  We want to use the
419                 // shortest lifetime possible so as to avoid spurious borrowck
420                 // errors.  Moreover, the longest lifetime will depend on the
421                 // precise details of the value whose address is being taken
422                 // (and how long it is valid), which we don't know yet until
423                 // type inference is complete.
424                 //
425                 // Therefore, here we simply generate a region variable. The
426                 // region inferencer will then select a suitable value.
427                 // Finally, borrowck will infer the value of the region again,
428                 // this time with enough precision to check that the value
429                 // whose address was taken can actually be made to live as long
430                 // as it needs to live.
431                 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
432                 self.tcx.mk_ref(region, tm)
433             }
434         }
435     }
436
437     /// Does this expression refer to a place that either:
438     /// * Is based on a local or static.
439     /// * Contains a dereference
440     /// Note that the adjustments for the children of `expr` should already
441     /// have been resolved.
442     fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
443         let is_named = oprnd.is_place_expr(|base| {
444             // Allow raw borrows if there are any deref adjustments.
445             //
446             // const VAL: (i32,) = (0,);
447             // const REF: &(i32,) = &(0,);
448             //
449             // &raw const VAL.0;            // ERROR
450             // &raw const REF.0;            // OK, same as &raw const (*REF).0;
451             //
452             // This is maybe too permissive, since it allows
453             // `let u = &raw const Box::new((1,)).0`, which creates an
454             // immediately dangling raw pointer.
455             self.tables.borrow().adjustments().get(base.hir_id).map_or(false, |x| {
456                 x.iter().any(|adj| if let Adjust::Deref(_) = adj.kind { true } else { false })
457             })
458         });
459         if !is_named {
460             struct_span_err!(
461                 self.tcx.sess,
462                 oprnd.span,
463                 E0745,
464                 "cannot take address of a temporary"
465             )
466             .span_label(oprnd.span, "temporary value")
467             .emit();
468         }
469     }
470
471     fn check_expr_path(&self, qpath: &hir::QPath<'_>, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
472         let tcx = self.tcx;
473         let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
474         let ty = match res {
475             Res::Err => {
476                 self.set_tainted_by_errors();
477                 tcx.types.err
478             }
479             Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
480                 report_unexpected_variant_res(tcx, res, expr.span, qpath);
481                 tcx.types.err
482             }
483             _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
484         };
485
486         if let ty::FnDef(..) = ty.kind {
487             let fn_sig = ty.fn_sig(tcx);
488             if !tcx.features().unsized_locals {
489                 // We want to remove some Sized bounds from std functions,
490                 // but don't want to expose the removal to stable Rust.
491                 // i.e., we don't want to allow
492                 //
493                 // ```rust
494                 // drop as fn(str);
495                 // ```
496                 //
497                 // to work in stable even if the Sized bound on `drop` is relaxed.
498                 for i in 0..fn_sig.inputs().skip_binder().len() {
499                     // We just want to check sizedness, so instead of introducing
500                     // placeholder lifetimes with probing, we just replace higher lifetimes
501                     // with fresh vars.
502                     let input = self
503                         .replace_bound_vars_with_fresh_vars(
504                             expr.span,
505                             infer::LateBoundRegionConversionTime::FnCall,
506                             &fn_sig.input(i),
507                         )
508                         .0;
509                     self.require_type_is_sized_deferred(
510                         input,
511                         expr.span,
512                         traits::SizedArgumentType,
513                     );
514                 }
515             }
516             // Here we want to prevent struct constructors from returning unsized types.
517             // There were two cases this happened: fn pointer coercion in stable
518             // and usual function call in presence of unsized_locals.
519             // Also, as we just want to check sizedness, instead of introducing
520             // placeholder lifetimes with probing, we just replace higher lifetimes
521             // with fresh vars.
522             let output = self
523                 .replace_bound_vars_with_fresh_vars(
524                     expr.span,
525                     infer::LateBoundRegionConversionTime::FnCall,
526                     &fn_sig.output(),
527                 )
528                 .0;
529             self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
530         }
531
532         // We always require that the type provided as the value for
533         // a type parameter outlives the moment of instantiation.
534         let substs = self.tables.borrow().node_substs(expr.hir_id);
535         self.add_wf_bounds(substs, expr);
536
537         ty
538     }
539
540     fn check_expr_break(
541         &self,
542         destination: hir::Destination,
543         expr_opt: Option<&'tcx hir::Expr<'tcx>>,
544         expr: &'tcx hir::Expr<'tcx>,
545     ) -> Ty<'tcx> {
546         let tcx = self.tcx;
547         if let Ok(target_id) = destination.target_id {
548             let (e_ty, cause);
549             if let Some(ref e) = expr_opt {
550                 // If this is a break with a value, we need to type-check
551                 // the expression. Get an expected type from the loop context.
552                 let opt_coerce_to = {
553                     // We should release `enclosing_breakables` before the `check_expr_with_hint`
554                     // below, so can't move this block of code to the enclosing scope and share
555                     // `ctxt` with the second `encloding_breakables` borrow below.
556                     let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
557                     match enclosing_breakables.opt_find_breakable(target_id) {
558                         Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
559                         None => {
560                             // Avoid ICE when `break` is inside a closure (#65383).
561                             self.tcx.sess.delay_span_bug(
562                                 expr.span,
563                                 "break was outside loop, but no error was emitted",
564                             );
565                             return tcx.types.err;
566                         }
567                     }
568                 };
569
570                 // If the loop context is not a `loop { }`, then break with
571                 // a value is illegal, and `opt_coerce_to` will be `None`.
572                 // Just set expectation to error in that case.
573                 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
574
575                 // Recurse without `enclosing_breakables` borrowed.
576                 e_ty = self.check_expr_with_hint(e, coerce_to);
577                 cause = self.misc(e.span);
578             } else {
579                 // Otherwise, this is a break *without* a value. That's
580                 // always legal, and is equivalent to `break ()`.
581                 e_ty = tcx.mk_unit();
582                 cause = self.misc(expr.span);
583             }
584
585             // Now that we have type-checked `expr_opt`, borrow
586             // the `enclosing_loops` field and let's coerce the
587             // type of `expr_opt` into what is expected.
588             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
589             let ctxt = match enclosing_breakables.opt_find_breakable(target_id) {
590                 Some(ctxt) => ctxt,
591                 None => {
592                     // Avoid ICE when `break` is inside a closure (#65383).
593                     self.tcx.sess.delay_span_bug(
594                         expr.span,
595                         "break was outside loop, but no error was emitted",
596                     );
597                     return tcx.types.err;
598                 }
599             };
600
601             if let Some(ref mut coerce) = ctxt.coerce {
602                 if let Some(ref e) = expr_opt {
603                     coerce.coerce(self, &cause, e, e_ty);
604                 } else {
605                     assert!(e_ty.is_unit());
606                     let ty = coerce.expected_ty();
607                     coerce.coerce_forced_unit(
608                         self,
609                         &cause,
610                         &mut |mut err| {
611                             self.suggest_mismatched_types_on_tail(
612                                 &mut err, expr, ty, e_ty, cause.span, target_id,
613                             );
614                             if let Some(val) = ty_kind_suggestion(ty) {
615                                 let label = destination
616                                     .label
617                                     .map(|l| format!(" {}", l.ident))
618                                     .unwrap_or_else(String::new);
619                                 err.span_suggestion(
620                                     expr.span,
621                                     "give it a value of the expected type",
622                                     format!("break{} {}", label, val),
623                                     Applicability::HasPlaceholders,
624                                 );
625                             }
626                         },
627                         false,
628                     );
629                 }
630             } else {
631                 // If `ctxt.coerce` is `None`, we can just ignore
632                 // the type of the expression.  This is because
633                 // either this was a break *without* a value, in
634                 // which case it is always a legal type (`()`), or
635                 // else an error would have been flagged by the
636                 // `loops` pass for using break with an expression
637                 // where you are not supposed to.
638                 assert!(expr_opt.is_none() || self.tcx.sess.has_errors());
639             }
640
641             ctxt.may_break = true;
642
643             // the type of a `break` is always `!`, since it diverges
644             tcx.types.never
645         } else {
646             // Otherwise, we failed to find the enclosing loop;
647             // this can only happen if the `break` was not
648             // inside a loop at all, which is caught by the
649             // loop-checking pass.
650             self.tcx
651                 .sess
652                 .delay_span_bug(expr.span, "break was outside loop, but no error was emitted");
653
654             // We still need to assign a type to the inner expression to
655             // prevent the ICE in #43162.
656             if let Some(ref e) = expr_opt {
657                 self.check_expr_with_hint(e, tcx.types.err);
658
659                 // ... except when we try to 'break rust;'.
660                 // ICE this expression in particular (see #43162).
661                 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
662                     if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
663                         fatally_break_rust(self.tcx.sess);
664                     }
665                 }
666             }
667             // There was an error; make type-check fail.
668             tcx.types.err
669         }
670     }
671
672     fn check_expr_return(
673         &self,
674         expr_opt: Option<&'tcx hir::Expr<'tcx>>,
675         expr: &'tcx hir::Expr<'tcx>,
676     ) -> Ty<'tcx> {
677         if self.ret_coercion.is_none() {
678             struct_span_err!(
679                 self.tcx.sess,
680                 expr.span,
681                 E0572,
682                 "return statement outside of function body",
683             )
684             .emit();
685         } else if let Some(ref e) = expr_opt {
686             if self.ret_coercion_span.borrow().is_none() {
687                 *self.ret_coercion_span.borrow_mut() = Some(e.span);
688             }
689             self.check_return_expr(e);
690         } else {
691             let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
692             if self.ret_coercion_span.borrow().is_none() {
693                 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
694             }
695             let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
696             if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
697                 coercion.coerce_forced_unit(
698                     self,
699                     &cause,
700                     &mut |db| {
701                         db.span_label(
702                             fn_decl.output.span(),
703                             format!("expected `{}` because of this return type", fn_decl.output,),
704                         );
705                     },
706                     true,
707                 );
708             } else {
709                 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
710             }
711         }
712         self.tcx.types.never
713     }
714
715     pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr<'tcx>) {
716         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
717             span_bug!(return_expr.span, "check_return_expr called outside fn body")
718         });
719
720         let ret_ty = ret_coercion.borrow().expected_ty();
721         let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
722         ret_coercion.borrow_mut().coerce(
723             self,
724             &self.cause(return_expr.span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
725             return_expr,
726             return_expr_ty,
727         );
728     }
729
730     fn is_destructuring_place_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> bool {
731         match &expr.kind {
732             ExprKind::Array(comps) | ExprKind::Tup(comps) => {
733                 comps.iter().all(|e| self.is_destructuring_place_expr(e))
734             }
735             ExprKind::Struct(_path, fields, rest) => {
736                 rest.as_ref().map(|e| self.is_destructuring_place_expr(e)).unwrap_or(true)
737                     && fields.iter().all(|f| self.is_destructuring_place_expr(&f.expr))
738             }
739             _ => expr.is_syntactic_place_expr(),
740         }
741     }
742
743     pub(crate) fn check_lhs_assignable(
744         &self,
745         lhs: &'tcx hir::Expr<'tcx>,
746         err_code: &'static str,
747         expr_span: &Span,
748     ) {
749         if !lhs.is_syntactic_place_expr() {
750             let mut err = self.tcx.sess.struct_span_err_with_code(
751                 *expr_span,
752                 "invalid left-hand side of assignment",
753                 DiagnosticId::Error(err_code.into()),
754             );
755             err.span_label(lhs.span, "cannot assign to this expression");
756             if self.is_destructuring_place_expr(lhs) {
757                 err.note("destructuring assignments are not currently supported");
758                 err.note("for more information, see https://github.com/rust-lang/rfcs/issues/372");
759             }
760             err.emit();
761         }
762     }
763
764     /// Type check assignment expression `expr` of form `lhs = rhs`.
765     /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
766     fn check_expr_assign(
767         &self,
768         expr: &'tcx hir::Expr<'tcx>,
769         expected: Expectation<'tcx>,
770         lhs: &'tcx hir::Expr<'tcx>,
771         rhs: &'tcx hir::Expr<'tcx>,
772         span: &Span,
773     ) -> Ty<'tcx> {
774         let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
775         let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
776
777         let expected_ty = expected.coercion_target_type(self, expr.span);
778         if expected_ty == self.tcx.types.bool {
779             // The expected type is `bool` but this will result in `()` so we can reasonably
780             // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
781             // The likely cause of this is `if foo = bar { .. }`.
782             let actual_ty = self.tcx.mk_unit();
783             let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
784             let msg = "try comparing for equality";
785             let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
786             let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
787             if let (Ok(left), Ok(right)) = (left, right) {
788                 let help = format!("{} == {}", left, right);
789                 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
790             } else {
791                 err.help(msg);
792             }
793             err.emit();
794         } else {
795             self.check_lhs_assignable(lhs, "E0070", span);
796         }
797
798         self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
799
800         if lhs_ty.references_error() || rhs_ty.references_error() {
801             self.tcx.types.err
802         } else {
803             self.tcx.mk_unit()
804         }
805     }
806
807     fn check_expr_loop(
808         &self,
809         body: &'tcx hir::Block<'tcx>,
810         source: hir::LoopSource,
811         expected: Expectation<'tcx>,
812         expr: &'tcx hir::Expr<'tcx>,
813     ) -> Ty<'tcx> {
814         let coerce = match source {
815             // you can only use break with a value from a normal `loop { }`
816             hir::LoopSource::Loop => {
817                 let coerce_to = expected.coercion_target_type(self, body.span);
818                 Some(CoerceMany::new(coerce_to))
819             }
820
821             hir::LoopSource::While | hir::LoopSource::WhileLet | hir::LoopSource::ForLoop => None,
822         };
823
824         let ctxt = BreakableCtxt {
825             coerce,
826             may_break: false, // Will get updated if/when we find a `break`.
827         };
828
829         let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
830             self.check_block_no_value(&body);
831         });
832
833         if ctxt.may_break {
834             // No way to know whether it's diverging because
835             // of a `break` or an outer `break` or `return`.
836             self.diverges.set(Diverges::Maybe);
837         }
838
839         // If we permit break with a value, then result type is
840         // the LUB of the breaks (possibly ! if none); else, it
841         // is nil. This makes sense because infinite loops
842         // (which would have type !) are only possible iff we
843         // permit break with a value [1].
844         if ctxt.coerce.is_none() && !ctxt.may_break {
845             // [1]
846             self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
847         }
848         ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
849     }
850
851     /// Checks a method call.
852     fn check_method_call(
853         &self,
854         expr: &'tcx hir::Expr<'tcx>,
855         segment: &hir::PathSegment<'_>,
856         span: Span,
857         args: &'tcx [hir::Expr<'tcx>],
858         expected: Expectation<'tcx>,
859         needs: Needs,
860     ) -> Ty<'tcx> {
861         let rcvr = &args[0];
862         let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
863         // no need to check for bot/err -- callee does that
864         let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
865
866         let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) {
867             Ok(method) => {
868                 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
869                 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
870
871                 self.write_method_call(expr.hir_id, method);
872                 Ok(method)
873             }
874             Err(error) => {
875                 if segment.ident.name != kw::Invalid {
876                     self.report_extended_method_error(segment, span, args, rcvr_t, error);
877                 }
878                 Err(())
879             }
880         };
881
882         // Call the generic checker.
883         self.check_method_argument_types(
884             span,
885             expr,
886             method,
887             &args[1..],
888             DontTupleArguments,
889             expected,
890         )
891     }
892
893     fn report_extended_method_error(
894         &self,
895         segment: &hir::PathSegment<'_>,
896         span: Span,
897         args: &'tcx [hir::Expr<'tcx>],
898         rcvr_t: Ty<'tcx>,
899         error: MethodError<'tcx>,
900     ) {
901         let rcvr = &args[0];
902         let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, rcvr_t, lang_item| {
903             if let Some(new_rcvr_t) = self.tcx.mk_lang_item(rcvr_t, lang_item) {
904                 if let Ok(pick) = self.lookup_probe(
905                     span,
906                     segment.ident,
907                     new_rcvr_t,
908                     rcvr,
909                     probe::ProbeScope::AllTraits,
910                 ) {
911                     err.span_label(
912                         pick.item.ident.span,
913                         &format!("the method is available for `{}` here", new_rcvr_t),
914                     );
915                 }
916             }
917         };
918
919         if let Some(mut err) = self.report_method_error(
920             span,
921             rcvr_t,
922             segment.ident,
923             SelfSource::MethodCall(rcvr),
924             error,
925             Some(args),
926         ) {
927             if let ty::Adt(..) = rcvr_t.kind {
928                 // Try alternative arbitrary self types that could fulfill this call.
929                 // FIXME: probe for all types that *could* be arbitrary self-types, not
930                 // just this whitelist.
931                 try_alt_rcvr(&mut err, rcvr_t, lang_items::OwnedBoxLangItem);
932                 try_alt_rcvr(&mut err, rcvr_t, lang_items::PinTypeLangItem);
933                 try_alt_rcvr(&mut err, rcvr_t, lang_items::Arc);
934                 try_alt_rcvr(&mut err, rcvr_t, lang_items::Rc);
935             }
936             err.emit();
937         }
938     }
939
940     fn check_expr_cast(
941         &self,
942         e: &'tcx hir::Expr<'tcx>,
943         t: &'tcx hir::Ty<'tcx>,
944         expr: &'tcx hir::Expr<'tcx>,
945     ) -> Ty<'tcx> {
946         // Find the type of `e`. Supply hints based on the type we are casting to,
947         // if appropriate.
948         let t_cast = self.to_ty_saving_user_provided_ty(t);
949         let t_cast = self.resolve_vars_if_possible(&t_cast);
950         let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
951         let t_cast = self.resolve_vars_if_possible(&t_cast);
952
953         // Eagerly check for some obvious errors.
954         if t_expr.references_error() || t_cast.references_error() {
955             self.tcx.types.err
956         } else {
957             // Defer other checks until we're done type checking.
958             let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
959             match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
960                 Ok(cast_check) => {
961                     deferred_cast_checks.push(cast_check);
962                     t_cast
963                 }
964                 Err(ErrorReported) => self.tcx.types.err,
965             }
966         }
967     }
968
969     fn check_expr_array(
970         &self,
971         args: &'tcx [hir::Expr<'tcx>],
972         expected: Expectation<'tcx>,
973         expr: &'tcx hir::Expr<'tcx>,
974     ) -> Ty<'tcx> {
975         let uty = expected.to_option(self).and_then(|uty| match uty.kind {
976             ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
977             _ => None,
978         });
979
980         let element_ty = if !args.is_empty() {
981             let coerce_to = uty.unwrap_or_else(|| {
982                 self.next_ty_var(TypeVariableOrigin {
983                     kind: TypeVariableOriginKind::TypeInference,
984                     span: expr.span,
985                 })
986             });
987             let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
988             assert_eq!(self.diverges.get(), Diverges::Maybe);
989             for e in args {
990                 let e_ty = self.check_expr_with_hint(e, coerce_to);
991                 let cause = self.misc(e.span);
992                 coerce.coerce(self, &cause, e, e_ty);
993             }
994             coerce.complete(self)
995         } else {
996             self.next_ty_var(TypeVariableOrigin {
997                 kind: TypeVariableOriginKind::TypeInference,
998                 span: expr.span,
999             })
1000         };
1001         self.tcx.mk_array(element_ty, args.len() as u64)
1002     }
1003
1004     fn check_expr_repeat(
1005         &self,
1006         element: &'tcx hir::Expr<'tcx>,
1007         count: &'tcx hir::AnonConst,
1008         expected: Expectation<'tcx>,
1009         _expr: &'tcx hir::Expr<'tcx>,
1010     ) -> Ty<'tcx> {
1011         let tcx = self.tcx;
1012         let count_def_id = tcx.hir().local_def_id(count.hir_id);
1013         let count = if self.const_param_def_id(count).is_some() {
1014             Ok(self.to_const(count, tcx.type_of(count_def_id)))
1015         } else {
1016             tcx.const_eval_poly(count_def_id)
1017         };
1018
1019         let uty = match expected {
1020             ExpectHasType(uty) => match uty.kind {
1021                 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1022                 _ => None,
1023             },
1024             _ => None,
1025         };
1026
1027         let (element_ty, t) = match uty {
1028             Some(uty) => {
1029                 self.check_expr_coercable_to_type(&element, uty);
1030                 (uty, uty)
1031             }
1032             None => {
1033                 let ty = self.next_ty_var(TypeVariableOrigin {
1034                     kind: TypeVariableOriginKind::MiscVariable,
1035                     span: element.span,
1036                 });
1037                 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1038                 (element_ty, ty)
1039             }
1040         };
1041
1042         if element_ty.references_error() {
1043             tcx.types.err
1044         } else if let Ok(count) = count {
1045             tcx.mk_ty(ty::Array(t, count))
1046         } else {
1047             tcx.types.err
1048         }
1049     }
1050
1051     fn check_expr_tuple(
1052         &self,
1053         elts: &'tcx [hir::Expr<'tcx>],
1054         expected: Expectation<'tcx>,
1055         expr: &'tcx hir::Expr<'tcx>,
1056     ) -> Ty<'tcx> {
1057         let flds = expected.only_has_type(self).and_then(|ty| {
1058             let ty = self.resolve_vars_with_obligations(ty);
1059             match ty.kind {
1060                 ty::Tuple(ref flds) => Some(&flds[..]),
1061                 _ => None,
1062             }
1063         });
1064
1065         let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
1066             let t = match flds {
1067                 Some(ref fs) if i < fs.len() => {
1068                     let ety = fs[i].expect_ty();
1069                     self.check_expr_coercable_to_type(&e, ety);
1070                     ety
1071                 }
1072                 _ => self.check_expr_with_expectation(&e, NoExpectation),
1073             };
1074             t
1075         });
1076         let tuple = self.tcx.mk_tup(elt_ts_iter);
1077         if tuple.references_error() {
1078             self.tcx.types.err
1079         } else {
1080             self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1081             tuple
1082         }
1083     }
1084
1085     fn check_expr_struct(
1086         &self,
1087         expr: &hir::Expr<'_>,
1088         expected: Expectation<'tcx>,
1089         qpath: &QPath<'_>,
1090         fields: &'tcx [hir::Field<'tcx>],
1091         base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1092     ) -> Ty<'tcx> {
1093         // Find the relevant variant
1094         let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id)
1095         {
1096             variant_ty
1097         } else {
1098             self.check_struct_fields_on_error(fields, base_expr);
1099             return self.tcx.types.err;
1100         };
1101
1102         let path_span = match *qpath {
1103             QPath::Resolved(_, ref path) => path.span,
1104             QPath::TypeRelative(ref qself, _) => qself.span,
1105         };
1106
1107         // Prohibit struct expressions when non-exhaustive flag is set.
1108         let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1109         if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1110             struct_span_err!(
1111                 self.tcx.sess,
1112                 expr.span,
1113                 E0639,
1114                 "cannot create non-exhaustive {} using struct expression",
1115                 adt.variant_descr()
1116             )
1117             .emit();
1118         }
1119
1120         let error_happened = self.check_expr_struct_fields(
1121             adt_ty,
1122             expected,
1123             expr.hir_id,
1124             path_span,
1125             variant,
1126             fields,
1127             base_expr.is_none(),
1128         );
1129         if let &Some(ref base_expr) = base_expr {
1130             // If check_expr_struct_fields hit an error, do not attempt to populate
1131             // the fields with the base_expr. This could cause us to hit errors later
1132             // when certain fields are assumed to exist that in fact do not.
1133             if !error_happened {
1134                 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1135                 match adt_ty.kind {
1136                     ty::Adt(adt, substs) if adt.is_struct() => {
1137                         let fru_field_types = adt
1138                             .non_enum_variant()
1139                             .fields
1140                             .iter()
1141                             .map(|f| {
1142                                 self.normalize_associated_types_in(
1143                                     expr.span,
1144                                     &f.ty(self.tcx, substs),
1145                                 )
1146                             })
1147                             .collect();
1148
1149                         self.tables
1150                             .borrow_mut()
1151                             .fru_field_types_mut()
1152                             .insert(expr.hir_id, fru_field_types);
1153                     }
1154                     _ => {
1155                         struct_span_err!(
1156                             self.tcx.sess,
1157                             base_expr.span,
1158                             E0436,
1159                             "functional record update syntax requires a struct"
1160                         )
1161                         .emit();
1162                     }
1163                 }
1164             }
1165         }
1166         self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1167         adt_ty
1168     }
1169
1170     fn check_expr_struct_fields(
1171         &self,
1172         adt_ty: Ty<'tcx>,
1173         expected: Expectation<'tcx>,
1174         expr_id: hir::HirId,
1175         span: Span,
1176         variant: &'tcx ty::VariantDef,
1177         ast_fields: &'tcx [hir::Field<'tcx>],
1178         check_completeness: bool,
1179     ) -> bool {
1180         let tcx = self.tcx;
1181
1182         let adt_ty_hint = self
1183             .expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1184             .get(0)
1185             .cloned()
1186             .unwrap_or(adt_ty);
1187         // re-link the regions that EIfEO can erase.
1188         self.demand_eqtype(span, adt_ty_hint, adt_ty);
1189
1190         let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1191             &ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()),
1192             _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"),
1193         };
1194
1195         let mut remaining_fields = variant
1196             .fields
1197             .iter()
1198             .enumerate()
1199             .map(|(i, field)| (field.ident.modern(), (i, field)))
1200             .collect::<FxHashMap<_, _>>();
1201
1202         let mut seen_fields = FxHashMap::default();
1203
1204         let mut error_happened = false;
1205
1206         // Type-check each field.
1207         for field in ast_fields {
1208             let ident = tcx.adjust_ident(field.ident, variant.def_id);
1209             let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1210                 seen_fields.insert(ident, field.span);
1211                 self.write_field_index(field.hir_id, i);
1212
1213                 // We don't look at stability attributes on
1214                 // struct-like enums (yet...), but it's definitely not
1215                 // a bug to have constructed one.
1216                 if adt_kind != AdtKind::Enum {
1217                     tcx.check_stability(v_field.did, Some(expr_id), field.span);
1218                 }
1219
1220                 self.field_ty(field.span, v_field, substs)
1221             } else {
1222                 error_happened = true;
1223                 if let Some(prev_span) = seen_fields.get(&ident) {
1224                     let mut err = struct_span_err!(
1225                         self.tcx.sess,
1226                         field.ident.span,
1227                         E0062,
1228                         "field `{}` specified more than once",
1229                         ident
1230                     );
1231
1232                     err.span_label(field.ident.span, "used more than once");
1233                     err.span_label(*prev_span, format!("first use of `{}`", ident));
1234
1235                     err.emit();
1236                 } else {
1237                     self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1238                 }
1239
1240                 tcx.types.err
1241             };
1242
1243             // Make sure to give a type to the field even if there's
1244             // an error, so we can continue type-checking.
1245             self.check_expr_coercable_to_type(&field.expr, field_type);
1246         }
1247
1248         // Make sure the programmer specified correct number of fields.
1249         if kind_name == "union" {
1250             if ast_fields.len() != 1 {
1251                 tcx.sess.span_err(span, "union expressions should have exactly one field");
1252             }
1253         } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1254             let len = remaining_fields.len();
1255
1256             let mut displayable_field_names =
1257                 remaining_fields.keys().map(|ident| ident.as_str()).collect::<Vec<_>>();
1258
1259             displayable_field_names.sort();
1260
1261             let truncated_fields_error = if len <= 3 {
1262                 String::new()
1263             } else {
1264                 format!(" and {} other field{}", (len - 3), if len - 3 == 1 { "" } else { "s" })
1265             };
1266
1267             let remaining_fields_names = displayable_field_names
1268                 .iter()
1269                 .take(3)
1270                 .map(|n| format!("`{}`", n))
1271                 .collect::<Vec<_>>()
1272                 .join(", ");
1273
1274             struct_span_err!(
1275                 tcx.sess,
1276                 span,
1277                 E0063,
1278                 "missing field{} {}{} in initializer of `{}`",
1279                 pluralize!(remaining_fields.len()),
1280                 remaining_fields_names,
1281                 truncated_fields_error,
1282                 adt_ty
1283             )
1284             .span_label(
1285                 span,
1286                 format!("missing {}{}", remaining_fields_names, truncated_fields_error),
1287             )
1288             .emit();
1289         }
1290         error_happened
1291     }
1292
1293     fn check_struct_fields_on_error(
1294         &self,
1295         fields: &'tcx [hir::Field<'tcx>],
1296         base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1297     ) {
1298         for field in fields {
1299             self.check_expr(&field.expr);
1300         }
1301         if let Some(ref base) = *base_expr {
1302             self.check_expr(&base);
1303         }
1304     }
1305
1306     fn report_unknown_field(
1307         &self,
1308         ty: Ty<'tcx>,
1309         variant: &'tcx ty::VariantDef,
1310         field: &hir::Field<'_>,
1311         skip_fields: &[hir::Field<'_>],
1312         kind_name: &str,
1313         ty_span: Span,
1314     ) {
1315         if variant.recovered {
1316             return;
1317         }
1318         let mut err = self.type_error_struct_with_diag(
1319             field.ident.span,
1320             |actual| match ty.kind {
1321                 ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
1322                     self.tcx.sess,
1323                     field.ident.span,
1324                     E0559,
1325                     "{} `{}::{}` has no field named `{}`",
1326                     kind_name,
1327                     actual,
1328                     variant.ident,
1329                     field.ident
1330                 ),
1331                 _ => struct_span_err!(
1332                     self.tcx.sess,
1333                     field.ident.span,
1334                     E0560,
1335                     "{} `{}` has no field named `{}`",
1336                     kind_name,
1337                     actual,
1338                     field.ident
1339                 ),
1340             },
1341             ty,
1342         );
1343         match variant.ctor_kind {
1344             CtorKind::Fn => {
1345                 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt = ty));
1346                 err.span_label(field.ident.span, "field does not exist");
1347                 err.span_label(
1348                     ty_span,
1349                     format!(
1350                         "`{adt}` is a tuple {kind_name}, \
1351                          use the appropriate syntax: `{adt}(/* fields */)`",
1352                         adt = ty,
1353                         kind_name = kind_name
1354                     ),
1355                 );
1356             }
1357             _ => {
1358                 // prevent all specified fields from being suggested
1359                 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1360                 if let Some(field_name) =
1361                     Self::suggest_field_name(variant, &field.ident.as_str(), skip_fields.collect())
1362                 {
1363                     err.span_suggestion(
1364                         field.ident.span,
1365                         "a field with a similar name exists",
1366                         field_name.to_string(),
1367                         Applicability::MaybeIncorrect,
1368                     );
1369                 } else {
1370                     match ty.kind {
1371                         ty::Adt(adt, ..) => {
1372                             if adt.is_enum() {
1373                                 err.span_label(
1374                                     field.ident.span,
1375                                     format!("`{}::{}` does not have this field", ty, variant.ident),
1376                                 );
1377                             } else {
1378                                 err.span_label(
1379                                     field.ident.span,
1380                                     format!("`{}` does not have this field", ty),
1381                                 );
1382                             }
1383                             let available_field_names = self.available_field_names(variant);
1384                             if !available_field_names.is_empty() {
1385                                 err.note(&format!(
1386                                     "available fields are: {}",
1387                                     self.name_series_display(available_field_names)
1388                                 ));
1389                             }
1390                         }
1391                         _ => bug!("non-ADT passed to report_unknown_field"),
1392                     }
1393                 };
1394             }
1395         }
1396         err.emit();
1397     }
1398
1399     // Return an hint about the closest match in field names
1400     fn suggest_field_name(
1401         variant: &'tcx ty::VariantDef,
1402         field: &str,
1403         skip: Vec<Symbol>,
1404     ) -> Option<Symbol> {
1405         let names = variant.fields.iter().filter_map(|field| {
1406             // ignore already set fields and private fields from non-local crates
1407             if skip.iter().any(|&x| x == field.ident.name)
1408                 || (!variant.def_id.is_local() && field.vis != Visibility::Public)
1409             {
1410                 None
1411             } else {
1412                 Some(&field.ident.name)
1413             }
1414         });
1415
1416         find_best_match_for_name(names, field, None)
1417     }
1418
1419     fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1420         variant
1421             .fields
1422             .iter()
1423             .filter(|field| {
1424                 let def_scope = self
1425                     .tcx
1426                     .adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id)
1427                     .1;
1428                 field.vis.is_accessible_from(def_scope, self.tcx)
1429             })
1430             .map(|field| field.ident.name)
1431             .collect()
1432     }
1433
1434     fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1435         // dynamic limit, to never omit just one field
1436         let limit = if names.len() == 6 { 6 } else { 5 };
1437         let mut display =
1438             names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1439         if names.len() > limit {
1440             display = format!("{} ... and {} others", display, names.len() - limit);
1441         }
1442         display
1443     }
1444
1445     // Check field access expressions
1446     fn check_field(
1447         &self,
1448         expr: &'tcx hir::Expr<'tcx>,
1449         needs: Needs,
1450         base: &'tcx hir::Expr<'tcx>,
1451         field: ast::Ident,
1452     ) -> Ty<'tcx> {
1453         let expr_t = self.check_expr_with_needs(base, needs);
1454         let expr_t = self.structurally_resolved_type(base.span, expr_t);
1455         let mut private_candidate = None;
1456         let mut autoderef = self.autoderef(expr.span, expr_t);
1457         while let Some((base_t, _)) = autoderef.next() {
1458             match base_t.kind {
1459                 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1460                     debug!("struct named {:?}", base_t);
1461                     let (ident, def_scope) =
1462                         self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1463                     let fields = &base_def.non_enum_variant().fields;
1464                     if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1465                         let field = &fields[index];
1466                         let field_ty = self.field_ty(expr.span, field, substs);
1467                         // Save the index of all fields regardless of their visibility in case
1468                         // of error recovery.
1469                         self.write_field_index(expr.hir_id, index);
1470                         if field.vis.is_accessible_from(def_scope, self.tcx) {
1471                             let adjustments = autoderef.adjust_steps(self, needs);
1472                             self.apply_adjustments(base, adjustments);
1473                             autoderef.finalize(self);
1474
1475                             self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1476                             return field_ty;
1477                         }
1478                         private_candidate = Some((base_def.did, field_ty));
1479                     }
1480                 }
1481                 ty::Tuple(ref tys) => {
1482                     let fstr = field.as_str();
1483                     if let Ok(index) = fstr.parse::<usize>() {
1484                         if fstr == index.to_string() {
1485                             if let Some(field_ty) = tys.get(index) {
1486                                 let adjustments = autoderef.adjust_steps(self, needs);
1487                                 self.apply_adjustments(base, adjustments);
1488                                 autoderef.finalize(self);
1489
1490                                 self.write_field_index(expr.hir_id, index);
1491                                 return field_ty.expect_ty();
1492                             }
1493                         }
1494                     }
1495                 }
1496                 _ => {}
1497             }
1498         }
1499         autoderef.unambiguous_final_ty(self);
1500
1501         if let Some((did, field_ty)) = private_candidate {
1502             self.ban_private_field_access(expr, expr_t, field, did);
1503             return field_ty;
1504         }
1505
1506         if field.name == kw::Invalid {
1507         } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1508             self.ban_take_value_of_method(expr, expr_t, field);
1509         } else if !expr_t.is_primitive_ty() {
1510             self.ban_nonexisting_field(field, base, expr, expr_t);
1511         } else {
1512             type_error_struct!(
1513                 self.tcx().sess,
1514                 field.span,
1515                 expr_t,
1516                 E0610,
1517                 "`{}` is a primitive type and therefore doesn't have fields",
1518                 expr_t
1519             )
1520             .emit();
1521         }
1522
1523         self.tcx().types.err
1524     }
1525
1526     fn ban_nonexisting_field(
1527         &self,
1528         field: ast::Ident,
1529         base: &'tcx hir::Expr<'tcx>,
1530         expr: &'tcx hir::Expr<'tcx>,
1531         expr_t: Ty<'tcx>,
1532     ) {
1533         let mut err = self.no_such_field_err(field.span, field, expr_t);
1534
1535         match expr_t.peel_refs().kind {
1536             ty::Array(_, len) => {
1537                 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1538             }
1539             ty::RawPtr(..) => {
1540                 self.suggest_first_deref_field(&mut err, expr, base, field);
1541             }
1542             ty::Adt(def, _) if !def.is_enum() => {
1543                 self.suggest_fields_on_recordish(&mut err, def, field);
1544             }
1545             ty::Param(param_ty) => {
1546                 self.point_at_param_definition(&mut err, param_ty);
1547             }
1548             _ => {}
1549         }
1550
1551         if field.name == kw::Await {
1552             // We know by construction that `<expr>.await` is either on Rust 2015
1553             // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1554             err.note("to `.await` a `Future`, switch to Rust 2018");
1555             err.help("set `edition = \"2018\"` in `Cargo.toml`");
1556             err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1557         }
1558
1559         err.emit();
1560     }
1561
1562     fn ban_private_field_access(
1563         &self,
1564         expr: &hir::Expr<'_>,
1565         expr_t: Ty<'tcx>,
1566         field: ast::Ident,
1567         base_did: DefId,
1568     ) {
1569         let struct_path = self.tcx().def_path_str(base_did);
1570         let kind_name = match self.tcx().def_kind(base_did) {
1571             Some(def_kind) => def_kind.descr(base_did),
1572             _ => " ",
1573         };
1574         let mut err = struct_span_err!(
1575             self.tcx().sess,
1576             expr.span,
1577             E0616,
1578             "field `{}` of {} `{}` is private",
1579             field,
1580             kind_name,
1581             struct_path
1582         );
1583         // Also check if an accessible method exists, which is often what is meant.
1584         if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
1585         {
1586             self.suggest_method_call(
1587                 &mut err,
1588                 &format!("a method `{}` also exists, call it with parentheses", field),
1589                 field,
1590                 expr_t,
1591                 expr.hir_id,
1592             );
1593         }
1594         err.emit();
1595     }
1596
1597     fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: ast::Ident) {
1598         let mut err = type_error_struct!(
1599             self.tcx().sess,
1600             field.span,
1601             expr_t,
1602             E0615,
1603             "attempted to take value of method `{}` on type `{}`",
1604             field,
1605             expr_t
1606         );
1607
1608         if !self.expr_in_place(expr.hir_id) {
1609             self.suggest_method_call(
1610                 &mut err,
1611                 "use parentheses to call the method",
1612                 field,
1613                 expr_t,
1614                 expr.hir_id,
1615             );
1616         } else {
1617             err.help("methods are immutable and cannot be assigned to");
1618         }
1619
1620         err.emit();
1621     }
1622
1623     fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1624         let generics = self.tcx.generics_of(self.body_id.owner_def_id());
1625         let generic_param = generics.type_param(&param, self.tcx);
1626         if let ty::GenericParamDefKind::Type { synthetic: Some(..), .. } = generic_param.kind {
1627             return;
1628         }
1629         let param_def_id = generic_param.def_id;
1630         let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
1631             Some(x) => x,
1632             None => return,
1633         };
1634         let param_span = self.tcx.hir().span(param_hir_id);
1635         let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1636
1637         err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1638     }
1639
1640     fn suggest_fields_on_recordish(
1641         &self,
1642         err: &mut DiagnosticBuilder<'_>,
1643         def: &'tcx ty::AdtDef,
1644         field: ast::Ident,
1645     ) {
1646         if let Some(suggested_field_name) =
1647             Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
1648         {
1649             err.span_suggestion(
1650                 field.span,
1651                 "a field with a similar name exists",
1652                 suggested_field_name.to_string(),
1653                 Applicability::MaybeIncorrect,
1654             );
1655         } else {
1656             err.span_label(field.span, "unknown field");
1657             let struct_variant_def = def.non_enum_variant();
1658             let field_names = self.available_field_names(struct_variant_def);
1659             if !field_names.is_empty() {
1660                 err.note(&format!(
1661                     "available fields are: {}",
1662                     self.name_series_display(field_names),
1663                 ));
1664             }
1665         }
1666     }
1667
1668     fn maybe_suggest_array_indexing(
1669         &self,
1670         err: &mut DiagnosticBuilder<'_>,
1671         expr: &hir::Expr<'_>,
1672         base: &hir::Expr<'_>,
1673         field: ast::Ident,
1674         len: &ty::Const<'tcx>,
1675     ) {
1676         if let (Some(len), Ok(user_index)) =
1677             (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
1678         {
1679             let base = self
1680                 .tcx
1681                 .sess
1682                 .source_map()
1683                 .span_to_snippet(base.span)
1684                 .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1685             let help = "instead of using tuple indexing, use array indexing";
1686             let suggestion = format!("{}[{}]", base, field);
1687             let applicability = if len < user_index {
1688                 Applicability::MachineApplicable
1689             } else {
1690                 Applicability::MaybeIncorrect
1691             };
1692             err.span_suggestion(expr.span, help, suggestion, applicability);
1693         }
1694     }
1695
1696     fn suggest_first_deref_field(
1697         &self,
1698         err: &mut DiagnosticBuilder<'_>,
1699         expr: &hir::Expr<'_>,
1700         base: &hir::Expr<'_>,
1701         field: ast::Ident,
1702     ) {
1703         let base = self
1704             .tcx
1705             .sess
1706             .source_map()
1707             .span_to_snippet(base.span)
1708             .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1709         let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1710         let suggestion = format!("(*{}).{}", base, field);
1711         err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
1712     }
1713
1714     fn no_such_field_err<T: Display>(
1715         &self,
1716         span: Span,
1717         field: T,
1718         expr_t: &ty::TyS<'_>,
1719     ) -> DiagnosticBuilder<'_> {
1720         type_error_struct!(
1721             self.tcx().sess,
1722             span,
1723             expr_t,
1724             E0609,
1725             "no field `{}` on type `{}`",
1726             field,
1727             expr_t
1728         )
1729     }
1730
1731     fn check_expr_index(
1732         &self,
1733         base: &'tcx hir::Expr<'tcx>,
1734         idx: &'tcx hir::Expr<'tcx>,
1735         needs: Needs,
1736         expr: &'tcx hir::Expr<'tcx>,
1737     ) -> Ty<'tcx> {
1738         let base_t = self.check_expr_with_needs(&base, needs);
1739         let idx_t = self.check_expr(&idx);
1740
1741         if base_t.references_error() {
1742             base_t
1743         } else if idx_t.references_error() {
1744             idx_t
1745         } else {
1746             let base_t = self.structurally_resolved_type(base.span, base_t);
1747             match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1748                 Some((index_ty, element_ty)) => {
1749                     // two-phase not needed because index_ty is never mutable
1750                     self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1751                     element_ty
1752                 }
1753                 None => {
1754                     let mut err = type_error_struct!(
1755                         self.tcx.sess,
1756                         expr.span,
1757                         base_t,
1758                         E0608,
1759                         "cannot index into a value of type `{}`",
1760                         base_t
1761                     );
1762                     // Try to give some advice about indexing tuples.
1763                     if let ty::Tuple(..) = base_t.kind {
1764                         let mut needs_note = true;
1765                         // If the index is an integer, we can show the actual
1766                         // fixed expression:
1767                         if let ExprKind::Lit(ref lit) = idx.kind {
1768                             if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1769                                 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1770                                 if let Ok(snip) = snip {
1771                                     err.span_suggestion(
1772                                         expr.span,
1773                                         "to access tuple elements, use",
1774                                         format!("{}.{}", snip, i),
1775                                         Applicability::MachineApplicable,
1776                                     );
1777                                     needs_note = false;
1778                                 }
1779                             }
1780                         }
1781                         if needs_note {
1782                             err.help(
1783                                 "to access tuple elements, use tuple indexing \
1784                                         syntax (e.g., `tuple.0`)",
1785                             );
1786                         }
1787                     }
1788                     err.emit();
1789                     self.tcx.types.err
1790                 }
1791             }
1792         }
1793     }
1794
1795     fn check_expr_yield(
1796         &self,
1797         value: &'tcx hir::Expr<'tcx>,
1798         expr: &'tcx hir::Expr<'tcx>,
1799         src: &'tcx hir::YieldSource,
1800     ) -> Ty<'tcx> {
1801         match self.yield_ty {
1802             Some(ty) => {
1803                 self.check_expr_coercable_to_type(&value, ty);
1804             }
1805             // Given that this `yield` expression was generated as a result of lowering a `.await`,
1806             // we know that the yield type must be `()`; however, the context won't contain this
1807             // information. Hence, we check the source of the yield expression here and check its
1808             // value's type against `()` (this check should always hold).
1809             None if src == &hir::YieldSource::Await => {
1810                 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1811             }
1812             _ => {
1813                 struct_span_err!(
1814                     self.tcx.sess,
1815                     expr.span,
1816                     E0627,
1817                     "yield expression outside of generator literal"
1818                 )
1819                 .emit();
1820             }
1821         }
1822         self.tcx.mk_unit()
1823     }
1824 }
1825
1826 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1827     Some(match ty.kind {
1828         ty::Bool => "true",
1829         ty::Char => "'a'",
1830         ty::Int(_) | ty::Uint(_) => "42",
1831         ty::Float(_) => "3.14159",
1832         ty::Error | ty::Never => return None,
1833         _ => "value",
1834     })
1835 }