]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/check.rs
Rollup merge of #104771 - est31:if_let_chain_broken_mir_test, r=davidtwco
[rust.git] / compiler / rustc_hir_typeck / src / check.rs
1 use crate::coercion::CoerceMany;
2 use crate::gather_locals::GatherLocalsVisitor;
3 use crate::{FnCtxt, Inherited};
4 use crate::{GeneratorTypes, UnsafetyState};
5 use rustc_hir as hir;
6 use rustc_hir::def::DefKind;
7 use rustc_hir::intravisit::Visitor;
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir_analysis::check::fn_maybe_err;
10 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use rustc_infer::infer::RegionVariableOrigin;
12 use rustc_middle::ty::{self, Ty, TyCtxt};
13 use rustc_span::def_id::LocalDefId;
14 use rustc_trait_selection::traits;
15 use std::cell::RefCell;
16
17 /// Helper used for fns and closures. Does the grungy work of checking a function
18 /// body and returns the function context used for that purpose, since in the case of a fn item
19 /// there is still a bit more to do.
20 ///
21 /// * ...
22 /// * inherited: other fields inherited from the enclosing fn (if any)
23 #[instrument(skip(inherited, body), level = "debug")]
24 pub(super) fn check_fn<'a, 'tcx>(
25     inherited: &'a Inherited<'tcx>,
26     param_env: ty::ParamEnv<'tcx>,
27     fn_sig: ty::FnSig<'tcx>,
28     decl: &'tcx hir::FnDecl<'tcx>,
29     fn_def_id: LocalDefId,
30     body: &'tcx hir::Body<'tcx>,
31     can_be_generator: Option<hir::Movability>,
32 ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) {
33     let fn_id = inherited.tcx.hir().local_def_id_to_hir_id(fn_def_id);
34
35     // Create the function context. This is either derived from scratch or,
36     // in the case of closures, based on the outer context.
37     let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id);
38     fcx.ps.set(UnsafetyState::function(fn_sig.unsafety, fn_id));
39
40     let tcx = fcx.tcx;
41     let hir = tcx.hir();
42
43     let declared_ret_ty = fn_sig.output();
44
45     let ret_ty =
46         fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
47             declared_ret_ty,
48             body.value.hir_id,
49             decl.output.span(),
50             param_env,
51         ));
52
53     fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
54
55     let span = body.value.span;
56
57     fn_maybe_err(tcx, span, fn_sig.abi);
58
59     if body.generator_kind.is_some() && can_be_generator.is_some() {
60         let yield_ty = fcx
61             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
62         fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType);
63
64         // Resume type defaults to `()` if the generator has no argument.
65         let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| tcx.mk_unit());
66
67         fcx.resume_yield_tys = Some((resume_ty, yield_ty));
68     }
69
70     GatherLocalsVisitor::new(&fcx).visit_body(body);
71
72     // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
73     // (as it's created inside the body itself, not passed in from outside).
74     let maybe_va_list = if fn_sig.c_variadic {
75         let span = body.params.last().unwrap().span;
76         let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span));
77         let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span));
78
79         Some(tcx.bound_type_of(va_list_did).subst(tcx, &[region.into()]))
80     } else {
81         None
82     };
83
84     // Add formal parameters.
85     let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
86     let inputs_fn = fn_sig.inputs().iter().copied();
87     for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
88         // Check the pattern.
89         let ty_span = try { inputs_hir?.get(idx)?.span };
90         fcx.check_pat_top(&param.pat, param_ty, ty_span, false);
91
92         // Check that argument is Sized.
93         // The check for a non-trivial pattern is a hack to avoid duplicate warnings
94         // for simple cases like `fn foo(x: Trait)`,
95         // where we would error once on the parameter as a whole, and once on the binding `x`.
96         if param.pat.simple_ident().is_none() && !tcx.features().unsized_fn_params {
97             fcx.require_type_is_sized(param_ty, param.pat.span, traits::SizedArgumentType(ty_span));
98         }
99
100         fcx.write_ty(param.hir_id, param_ty);
101     }
102
103     inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
104
105     if let ty::Dynamic(_, _, ty::Dyn) = declared_ret_ty.kind() {
106         // FIXME: We need to verify that the return type is `Sized` after the return expression has
107         // been evaluated so that we have types available for all the nodes being returned, but that
108         // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this
109         // causes unsized errors caused by the `declared_ret_ty` to point at the return expression,
110         // while keeping the current ordering we will ignore the tail expression's type because we
111         // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr`
112         // because we will trigger "unreachable expression" lints unconditionally.
113         // Because of all of this, we perform a crude check to know whether the simplest `!Sized`
114         // case that a newcomer might make, returning a bare trait, and in that case we populate
115         // the tail expression's type so that the suggestion will be correct, but ignore all other
116         // possible cases.
117         fcx.check_expr(&body.value);
118         fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
119     } else {
120         fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
121         fcx.check_return_expr(&body.value, false);
122     }
123
124     // We insert the deferred_generator_interiors entry after visiting the body.
125     // This ensures that all nested generators appear before the entry of this generator.
126     // resolve_generator_interiors relies on this property.
127     let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) {
128         let interior = fcx
129             .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span });
130         fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind));
131
132         let (resume_ty, yield_ty) = fcx.resume_yield_tys.unwrap();
133         Some(GeneratorTypes {
134             resume_ty,
135             yield_ty,
136             interior,
137             movability: can_be_generator.unwrap(),
138         })
139     } else {
140         None
141     };
142
143     // Finalize the return check by taking the LUB of the return types
144     // we saw and assigning it to the expected return type. This isn't
145     // really expected to fail, since the coercions would have failed
146     // earlier when trying to find a LUB.
147     let coercion = fcx.ret_coercion.take().unwrap().into_inner();
148     let mut actual_return_ty = coercion.complete(&fcx);
149     debug!("actual_return_ty = {:?}", actual_return_ty);
150     if let ty::Dynamic(..) = declared_ret_ty.kind() {
151         // We have special-cased the case where the function is declared
152         // `-> dyn Foo` and we don't actually relate it to the
153         // `fcx.ret_coercion`, so just substitute a type variable.
154         actual_return_ty =
155             fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DynReturnFn, span });
156         debug!("actual_return_ty replaced with {:?}", actual_return_ty);
157     }
158
159     // HACK(oli-obk, compiler-errors): We should be comparing this against
160     // `declared_ret_ty`, but then anything uninferred would be inferred to
161     // the opaque type itself. That again would cause writeback to assume
162     // we have a recursive call site and do the sadly stabilized fallback to `()`.
163     fcx.demand_suptype(span, ret_ty, actual_return_ty);
164
165     // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
166     if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
167         && panic_impl_did == hir.local_def_id(fn_id).to_def_id()
168     {
169         check_panic_info_fn(tcx, panic_impl_did.expect_local(), fn_sig, decl, declared_ret_ty);
170     }
171
172     (fcx, gen_ty)
173 }
174
175 fn check_panic_info_fn(
176     tcx: TyCtxt<'_>,
177     fn_id: LocalDefId,
178     fn_sig: ty::FnSig<'_>,
179     decl: &hir::FnDecl<'_>,
180     declared_ret_ty: Ty<'_>,
181 ) {
182     let Some(panic_info_did) = tcx.lang_items().panic_info() else {
183         tcx.sess.err("language item required, but not found: `panic_info`");
184         return;
185     };
186
187     if *declared_ret_ty.kind() != ty::Never {
188         tcx.sess.span_err(decl.output.span(), "return type should be `!`");
189     }
190
191     let inputs = fn_sig.inputs();
192     if inputs.len() != 1 {
193         tcx.sess.span_err(tcx.def_span(fn_id), "function should have one argument");
194         return;
195     }
196
197     let arg_is_panic_info = match *inputs[0].kind() {
198         ty::Ref(region, ty, mutbl) => match *ty.kind() {
199             ty::Adt(ref adt, _) => {
200                 adt.did() == panic_info_did && mutbl == hir::Mutability::Not && !region.is_static()
201             }
202             _ => false,
203         },
204         _ => false,
205     };
206
207     if !arg_is_panic_info {
208         tcx.sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`");
209     }
210
211     let DefKind::Fn = tcx.def_kind(fn_id) else {
212         let span = tcx.def_span(fn_id);
213         tcx.sess.span_err(span, "should be a function");
214         return;
215     };
216
217     let generic_counts = tcx.generics_of(fn_id).own_counts();
218     if generic_counts.types != 0 {
219         let span = tcx.def_span(fn_id);
220         tcx.sess.span_err(span, "should have no type parameters");
221     }
222     if generic_counts.consts != 0 {
223         let span = tcx.def_span(fn_id);
224         tcx.sess.span_err(span, "should have no const parameters");
225     }
226 }