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