]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/lib.rs
Rollup merge of #103339 - Rageking8:fix-some-typos, r=fee1-dead
[rust.git] / compiler / rustc_hir_typeck / src / lib.rs
1 #![feature(if_let_guard)]
2 #![feature(let_chains)]
3 #![feature(try_blocks)]
4 #![feature(never_type)]
5 #![feature(min_specialization)]
6 #![feature(control_flow_enum)]
7 #![feature(drain_filter)]
8 #![allow(rustc::potential_query_instability)]
9 #![recursion_limit = "256"]
10
11 #[macro_use]
12 extern crate tracing;
13
14 #[macro_use]
15 extern crate rustc_middle;
16
17 mod _match;
18 mod autoderef;
19 mod callee;
20 // Used by clippy;
21 pub mod cast;
22 mod check;
23 mod closure;
24 mod coercion;
25 mod demand;
26 mod diverges;
27 mod errors;
28 mod expectation;
29 mod expr;
30 // Used by clippy;
31 pub mod expr_use_visitor;
32 mod fallback;
33 mod fn_ctxt;
34 mod gather_locals;
35 mod generator_interior;
36 mod inherited;
37 mod intrinsicck;
38 mod mem_categorization;
39 mod method;
40 mod op;
41 mod pat;
42 mod place_op;
43 mod rvalue_scopes;
44 mod upvar;
45 mod writeback;
46
47 pub use diverges::Diverges;
48 pub use expectation::Expectation;
49 pub use fn_ctxt::*;
50 pub use inherited::{Inherited, InheritedBuilder};
51
52 use crate::check::check_fn;
53 use crate::coercion::DynamicCoerceMany;
54 use crate::gather_locals::GatherLocalsVisitor;
55 use rustc_data_structures::fx::FxHashSet;
56 use rustc_errors::{struct_span_err, MultiSpan};
57 use rustc_hir as hir;
58 use rustc_hir::def::Res;
59 use rustc_hir::intravisit::Visitor;
60 use rustc_hir::{HirIdMap, Node};
61 use rustc_hir_analysis::astconv::AstConv;
62 use rustc_hir_analysis::check::check_abi;
63 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
64 use rustc_middle::traits;
65 use rustc_middle::ty::query::Providers;
66 use rustc_middle::ty::{self, Ty, TyCtxt};
67 use rustc_session::config;
68 use rustc_session::Session;
69 use rustc_span::def_id::{DefId, LocalDefId};
70 use rustc_span::Span;
71
72 #[macro_export]
73 macro_rules! type_error_struct {
74     ($session:expr, $span:expr, $typ:expr, $code:ident, $($message:tt)*) => ({
75         let mut err = rustc_errors::struct_span_err!($session, $span, $code, $($message)*);
76
77         if $typ.references_error() {
78             err.downgrade_to_delayed_bug();
79         }
80
81         err
82     })
83 }
84
85 /// The type of a local binding, including the revealed type for anon types.
86 #[derive(Copy, Clone, Debug)]
87 pub struct LocalTy<'tcx> {
88     decl_ty: Ty<'tcx>,
89     revealed_ty: Ty<'tcx>,
90 }
91
92 #[derive(Copy, Clone)]
93 pub struct UnsafetyState {
94     pub def: hir::HirId,
95     pub unsafety: hir::Unsafety,
96     from_fn: bool,
97 }
98
99 impl UnsafetyState {
100     pub fn function(unsafety: hir::Unsafety, def: hir::HirId) -> UnsafetyState {
101         UnsafetyState { def, unsafety, from_fn: true }
102     }
103
104     pub fn recurse(self, blk: &hir::Block<'_>) -> UnsafetyState {
105         use hir::BlockCheckMode;
106         match self.unsafety {
107             // If this unsafe, then if the outer function was already marked as
108             // unsafe we shouldn't attribute the unsafe'ness to the block. This
109             // way the block can be warned about instead of ignoring this
110             // extraneous block (functions are never warned about).
111             hir::Unsafety::Unsafe if self.from_fn => self,
112
113             unsafety => {
114                 let (unsafety, def) = match blk.rules {
115                     BlockCheckMode::UnsafeBlock(..) => (hir::Unsafety::Unsafe, blk.hir_id),
116                     BlockCheckMode::DefaultBlock => (unsafety, self.def),
117                 };
118                 UnsafetyState { def, unsafety, from_fn: false }
119             }
120         }
121     }
122 }
123
124 /// If this `DefId` is a "primary tables entry", returns
125 /// `Some((body_id, body_ty, fn_sig))`. Otherwise, returns `None`.
126 ///
127 /// If this function returns `Some`, then `typeck_results(def_id)` will
128 /// succeed; if it returns `None`, then `typeck_results(def_id)` may or
129 /// may not succeed. In some cases where this function returns `None`
130 /// (notably closures), `typeck_results(def_id)` would wind up
131 /// redirecting to the owning function.
132 fn primary_body_of(
133     tcx: TyCtxt<'_>,
134     id: hir::HirId,
135 ) -> Option<(hir::BodyId, Option<&hir::Ty<'_>>, Option<&hir::FnSig<'_>>)> {
136     match tcx.hir().get(id) {
137         Node::Item(item) => match item.kind {
138             hir::ItemKind::Const(ty, body) | hir::ItemKind::Static(ty, _, body) => {
139                 Some((body, Some(ty), None))
140             }
141             hir::ItemKind::Fn(ref sig, .., body) => Some((body, None, Some(sig))),
142             _ => None,
143         },
144         Node::TraitItem(item) => match item.kind {
145             hir::TraitItemKind::Const(ty, Some(body)) => Some((body, Some(ty), None)),
146             hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
147                 Some((body, None, Some(sig)))
148             }
149             _ => None,
150         },
151         Node::ImplItem(item) => match item.kind {
152             hir::ImplItemKind::Const(ty, body) => Some((body, Some(ty), None)),
153             hir::ImplItemKind::Fn(ref sig, body) => Some((body, None, Some(sig))),
154             _ => None,
155         },
156         Node::AnonConst(constant) => Some((constant.body, None, None)),
157         _ => None,
158     }
159 }
160
161 fn has_typeck_results(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
162     // Closures' typeck results come from their outermost function,
163     // as they are part of the same "inference environment".
164     let typeck_root_def_id = tcx.typeck_root_def_id(def_id);
165     if typeck_root_def_id != def_id {
166         return tcx.has_typeck_results(typeck_root_def_id);
167     }
168
169     if let Some(def_id) = def_id.as_local() {
170         let id = tcx.hir().local_def_id_to_hir_id(def_id);
171         primary_body_of(tcx, id).is_some()
172     } else {
173         false
174     }
175 }
176
177 fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &FxHashSet<LocalDefId> {
178     &*tcx.typeck(def_id).used_trait_imports
179 }
180
181 fn typeck_item_bodies(tcx: TyCtxt<'_>, (): ()) {
182     tcx.hir().par_body_owners(|body_owner_def_id| tcx.ensure().typeck(body_owner_def_id));
183 }
184
185 fn typeck_const_arg<'tcx>(
186     tcx: TyCtxt<'tcx>,
187     (did, param_did): (LocalDefId, DefId),
188 ) -> &ty::TypeckResults<'tcx> {
189     let fallback = move || tcx.type_of(param_did);
190     typeck_with_fallback(tcx, did, fallback)
191 }
192
193 fn typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckResults<'tcx> {
194     if let Some(param_did) = tcx.opt_const_param_of(def_id) {
195         tcx.typeck_const_arg((def_id, param_did))
196     } else {
197         let fallback = move || tcx.type_of(def_id.to_def_id());
198         typeck_with_fallback(tcx, def_id, fallback)
199     }
200 }
201
202 /// Used only to get `TypeckResults` for type inference during error recovery.
203 /// Currently only used for type inference of `static`s and `const`s to avoid type cycle errors.
204 fn diagnostic_only_typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckResults<'tcx> {
205     let fallback = move || {
206         let span = tcx.hir().span(tcx.hir().local_def_id_to_hir_id(def_id));
207         tcx.ty_error_with_message(span, "diagnostic only typeck table used")
208     };
209     typeck_with_fallback(tcx, def_id, fallback)
210 }
211
212 fn typeck_with_fallback<'tcx>(
213     tcx: TyCtxt<'tcx>,
214     def_id: LocalDefId,
215     fallback: impl Fn() -> Ty<'tcx> + 'tcx,
216 ) -> &'tcx ty::TypeckResults<'tcx> {
217     // Closures' typeck results come from their outermost function,
218     // as they are part of the same "inference environment".
219     let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
220     if typeck_root_def_id != def_id {
221         return tcx.typeck(typeck_root_def_id);
222     }
223
224     let id = tcx.hir().local_def_id_to_hir_id(def_id);
225     let span = tcx.hir().span(id);
226
227     // Figure out what primary body this item has.
228     let (body_id, body_ty, fn_sig) = primary_body_of(tcx, id).unwrap_or_else(|| {
229         span_bug!(span, "can't type-check body of {:?}", def_id);
230     });
231     let body = tcx.hir().body(body_id);
232
233     let typeck_results = Inherited::build(tcx, def_id).enter(|inh| {
234         let param_env = tcx.param_env(def_id);
235         let mut fcx = if let Some(hir::FnSig { header, decl, .. }) = fn_sig {
236             let fn_sig = if rustc_hir_analysis::collect::get_infer_ret_ty(&decl.output).is_some() {
237                 let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id);
238                 <dyn AstConv<'_>>::ty_of_fn(&fcx, id, header.unsafety, header.abi, decl, None, None)
239             } else {
240                 tcx.fn_sig(def_id)
241             };
242
243             check_abi(tcx, id, span, fn_sig.abi());
244
245             // Compute the function signature from point of view of inside the fn.
246             let fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
247             let fn_sig = inh.normalize_associated_types_in(
248                 body.value.span,
249                 body_id.hir_id,
250                 param_env,
251                 fn_sig,
252             );
253             check_fn(&inh, param_env, fn_sig, decl, id, body, None, true).0
254         } else {
255             let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id);
256             let expected_type = body_ty
257                 .and_then(|ty| match ty.kind {
258                     hir::TyKind::Infer => Some(<dyn AstConv<'_>>::ast_ty_to_ty(&fcx, ty)),
259                     _ => None,
260                 })
261                 .unwrap_or_else(|| match tcx.hir().get(id) {
262                     Node::AnonConst(_) => match tcx.hir().get(tcx.hir().get_parent_node(id)) {
263                         Node::Expr(&hir::Expr {
264                             kind: hir::ExprKind::ConstBlock(ref anon_const),
265                             ..
266                         }) if anon_const.hir_id == id => fcx.next_ty_var(TypeVariableOrigin {
267                             kind: TypeVariableOriginKind::TypeInference,
268                             span,
269                         }),
270                         Node::Ty(&hir::Ty {
271                             kind: hir::TyKind::Typeof(ref anon_const), ..
272                         }) if anon_const.hir_id == id => fcx.next_ty_var(TypeVariableOrigin {
273                             kind: TypeVariableOriginKind::TypeInference,
274                             span,
275                         }),
276                         Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), .. })
277                         | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm(asm), .. }) => {
278                             let operand_ty = asm
279                                 .operands
280                                 .iter()
281                                 .filter_map(|(op, _op_sp)| match op {
282                                     hir::InlineAsmOperand::Const { anon_const }
283                                         if anon_const.hir_id == id =>
284                                     {
285                                         // Inline assembly constants must be integers.
286                                         Some(fcx.next_int_var())
287                                     }
288                                     hir::InlineAsmOperand::SymFn { anon_const }
289                                         if anon_const.hir_id == id =>
290                                     {
291                                         Some(fcx.next_ty_var(TypeVariableOrigin {
292                                             kind: TypeVariableOriginKind::MiscVariable,
293                                             span,
294                                         }))
295                                     }
296                                     _ => None,
297                                 })
298                                 .next();
299                             operand_ty.unwrap_or_else(fallback)
300                         }
301                         _ => fallback(),
302                     },
303                     _ => fallback(),
304                 });
305
306             let expected_type = fcx.normalize_associated_types_in(body.value.span, expected_type);
307             fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
308
309             // Gather locals in statics (because of block expressions).
310             GatherLocalsVisitor::new(&fcx).visit_body(body);
311
312             fcx.check_expr_coercable_to_type(&body.value, expected_type, None);
313
314             fcx.write_ty(id, expected_type);
315
316             fcx
317         };
318
319         let fallback_has_occurred = fcx.type_inference_fallback();
320
321         // Even though coercion casts provide type hints, we check casts after fallback for
322         // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
323         fcx.check_casts();
324         fcx.select_obligations_where_possible(fallback_has_occurred, |_| {});
325
326         // Closure and generator analysis may run after fallback
327         // because they don't constrain other type variables.
328         // Closure analysis only runs on closures. Therefore they only need to fulfill non-const predicates (as of now)
329         let prev_constness = fcx.param_env.constness();
330         fcx.param_env = fcx.param_env.without_const();
331         fcx.closure_analyze(body);
332         fcx.param_env = fcx.param_env.with_constness(prev_constness);
333         assert!(fcx.deferred_call_resolutions.borrow().is_empty());
334         // Before the generator analysis, temporary scopes shall be marked to provide more
335         // precise information on types to be captured.
336         fcx.resolve_rvalue_scopes(def_id.to_def_id());
337         fcx.resolve_generator_interiors(def_id.to_def_id());
338
339         for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
340             let ty = fcx.normalize_ty(span, ty);
341             fcx.require_type_is_sized(ty, span, code);
342         }
343
344         fcx.select_all_obligations_or_error();
345
346         if !fcx.infcx.is_tainted_by_errors() {
347             fcx.check_transmutes();
348         }
349
350         fcx.check_asms();
351
352         fcx.infcx.skip_region_resolution();
353
354         fcx.resolve_type_vars_in_body(body)
355     });
356
357     // Consistency check our TypeckResults instance can hold all ItemLocalIds
358     // it will need to hold.
359     assert_eq!(typeck_results.hir_owner, id.owner);
360
361     typeck_results
362 }
363
364 /// When `check_fn` is invoked on a generator (i.e., a body that
365 /// includes yield), it returns back some information about the yield
366 /// points.
367 struct GeneratorTypes<'tcx> {
368     /// Type of generator argument / values returned by `yield`.
369     resume_ty: Ty<'tcx>,
370
371     /// Type of value that is yielded.
372     yield_ty: Ty<'tcx>,
373
374     /// Types that are captured (see `GeneratorInterior` for more).
375     interior: Ty<'tcx>,
376
377     /// Indicates if the generator is movable or static (immovable).
378     movability: hir::Movability,
379 }
380
381 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
382 pub enum Needs {
383     MutPlace,
384     None,
385 }
386
387 impl Needs {
388     fn maybe_mut_place(m: hir::Mutability) -> Self {
389         match m {
390             hir::Mutability::Mut => Needs::MutPlace,
391             hir::Mutability::Not => Needs::None,
392         }
393     }
394 }
395
396 #[derive(Debug, Copy, Clone)]
397 pub enum PlaceOp {
398     Deref,
399     Index,
400 }
401
402 pub struct BreakableCtxt<'tcx> {
403     may_break: bool,
404
405     // this is `null` for loops where break with a value is illegal,
406     // such as `while`, `for`, and `while let`
407     coerce: Option<DynamicCoerceMany<'tcx>>,
408 }
409
410 pub struct EnclosingBreakables<'tcx> {
411     stack: Vec<BreakableCtxt<'tcx>>,
412     by_id: HirIdMap<usize>,
413 }
414
415 impl<'tcx> EnclosingBreakables<'tcx> {
416     fn find_breakable(&mut self, target_id: hir::HirId) -> &mut BreakableCtxt<'tcx> {
417         self.opt_find_breakable(target_id).unwrap_or_else(|| {
418             bug!("could not find enclosing breakable with id {}", target_id);
419         })
420     }
421
422     fn opt_find_breakable(&mut self, target_id: hir::HirId) -> Option<&mut BreakableCtxt<'tcx>> {
423         match self.by_id.get(&target_id) {
424             Some(ix) => Some(&mut self.stack[*ix]),
425             None => None,
426         }
427     }
428 }
429
430 fn report_unexpected_variant_res(tcx: TyCtxt<'_>, res: Res, qpath: &hir::QPath<'_>, span: Span) {
431     struct_span_err!(
432         tcx.sess,
433         span,
434         E0533,
435         "expected unit struct, unit variant or constant, found {} `{}`",
436         res.descr(),
437         rustc_hir_pretty::qpath_to_string(qpath),
438     )
439     .emit();
440 }
441
442 /// Controls whether the arguments are tupled. This is used for the call
443 /// operator.
444 ///
445 /// Tupling means that all call-side arguments are packed into a tuple and
446 /// passed as a single parameter. For example, if tupling is enabled, this
447 /// function:
448 /// ```
449 /// fn f(x: (isize, isize)) {}
450 /// ```
451 /// Can be called as:
452 /// ```ignore UNSOLVED (can this be done in user code?)
453 /// # fn f(x: (isize, isize)) {}
454 /// f(1, 2);
455 /// ```
456 /// Instead of:
457 /// ```
458 /// # fn f(x: (isize, isize)) {}
459 /// f((1, 2));
460 /// ```
461 #[derive(Clone, Eq, PartialEq)]
462 enum TupleArgumentsFlag {
463     DontTupleArguments,
464     TupleArguments,
465 }
466
467 fn fatally_break_rust(sess: &Session) {
468     let handler = sess.diagnostic();
469     handler.span_bug_no_panic(
470         MultiSpan::new(),
471         "It looks like you're trying to break rust; would you like some ICE?",
472     );
473     handler.note_without_error("the compiler expectedly panicked. this is a feature.");
474     handler.note_without_error(
475         "we would appreciate a joke overview: \
476          https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
477     );
478     handler.note_without_error(&format!(
479         "rustc {} running on {}",
480         option_env!("CFG_VERSION").unwrap_or("unknown_version"),
481         config::host_triple(),
482     ));
483 }
484
485 fn has_expected_num_generic_args<'tcx>(
486     tcx: TyCtxt<'tcx>,
487     trait_did: Option<DefId>,
488     expected: usize,
489 ) -> bool {
490     trait_did.map_or(true, |trait_did| {
491         let generics = tcx.generics_of(trait_did);
492         generics.count() == expected + if generics.has_self { 1 } else { 0 }
493     })
494 }
495
496 pub fn provide(providers: &mut Providers) {
497     method::provide(providers);
498     *providers = Providers {
499         typeck_item_bodies,
500         typeck_const_arg,
501         typeck,
502         diagnostic_only_typeck,
503         has_typeck_results,
504         used_trait_imports,
505         ..*providers
506     };
507 }