rustc_hir_typeck/
lib.rs

1// tidy-alphabetical-start
2#![allow(rustc::diagnostic_outside_of_impl)]
3#![allow(rustc::untranslatable_diagnostic)]
4#![feature(assert_matches)]
5#![feature(box_patterns)]
6#![feature(if_let_guard)]
7#![feature(iter_intersperse)]
8#![feature(iter_order_by)]
9#![feature(never_type)]
10// tidy-alphabetical-end
11
12mod _match;
13mod autoderef;
14mod callee;
15// Used by clippy;
16pub mod cast;
17mod check;
18mod closure;
19mod coercion;
20mod demand;
21mod diverges;
22mod errors;
23mod expectation;
24mod expr;
25mod inline_asm;
26// Used by clippy;
27pub mod expr_use_visitor;
28mod fallback;
29mod fn_ctxt;
30mod gather_locals;
31mod intrinsicck;
32mod loops;
33mod method;
34mod naked_functions;
35mod op;
36mod opaque_types;
37mod pat;
38mod place_op;
39mod rvalue_scopes;
40mod typeck_root_ctxt;
41mod upvar;
42mod writeback;
43
44pub use coercion::can_coerce;
45use fn_ctxt::FnCtxt;
46use rustc_data_structures::unord::UnordSet;
47use rustc_errors::codes::*;
48use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err};
49use rustc_hir as hir;
50use rustc_hir::def::{DefKind, Res};
51use rustc_hir::{HirId, HirIdMap, Node};
52use rustc_hir_analysis::check::{check_abi, check_custom_abi};
53use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
54use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc};
55use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
56use rustc_middle::query::Providers;
57use rustc_middle::ty::{self, Ty, TyCtxt};
58use rustc_middle::{bug, span_bug};
59use rustc_session::config;
60use rustc_span::Span;
61use rustc_span::def_id::LocalDefId;
62use tracing::{debug, instrument};
63use typeck_root_ctxt::TypeckRootCtxt;
64
65use crate::check::check_fn;
66use crate::coercion::DynamicCoerceMany;
67use crate::diverges::Diverges;
68use crate::expectation::Expectation;
69use crate::fn_ctxt::LoweredTy;
70use crate::gather_locals::GatherLocalsVisitor;
71
72rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
73
74#[macro_export]
75macro_rules! type_error_struct {
76    ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({
77        let mut err = rustc_errors::struct_span_code_err!($dcx, $span, $code, $($message)*);
78
79        if $typ.references_error() {
80            err.downgrade_to_delayed_bug();
81        }
82
83        err
84    })
85}
86
87fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> {
88    &tcx.typeck(def_id).used_trait_imports
89}
90
91fn typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
92    typeck_with_inspect(tcx, def_id, None)
93}
94
95/// Same as `typeck` but `inspect` is invoked on evaluation of each root obligation.
96/// Inspecting obligations only works with the new trait solver.
97/// This function is *only to be used* by external tools, it should not be
98/// called from within rustc. Note, this is not a query, and thus is not cached.
99pub fn inspect_typeck<'tcx>(
100    tcx: TyCtxt<'tcx>,
101    def_id: LocalDefId,
102    inspect: ObligationInspector<'tcx>,
103) -> &'tcx ty::TypeckResults<'tcx> {
104    typeck_with_inspect(tcx, def_id, Some(inspect))
105}
106
107#[instrument(level = "debug", skip(tcx, inspector), ret)]
108fn typeck_with_inspect<'tcx>(
109    tcx: TyCtxt<'tcx>,
110    def_id: LocalDefId,
111    inspector: Option<ObligationInspector<'tcx>>,
112) -> &'tcx ty::TypeckResults<'tcx> {
113    // Closures' typeck results come from their outermost function,
114    // as they are part of the same "inference environment".
115    let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
116    if typeck_root_def_id != def_id {
117        return tcx.typeck(typeck_root_def_id);
118    }
119
120    let id = tcx.local_def_id_to_hir_id(def_id);
121    let node = tcx.hir_node(id);
122    let span = tcx.def_span(def_id);
123
124    // Figure out what primary body this item has.
125    let body_id = node.body_id().unwrap_or_else(|| {
126        span_bug!(span, "can't type-check body of {:?}", def_id);
127    });
128    let body = tcx.hir_body(body_id);
129
130    let param_env = tcx.param_env(def_id);
131
132    let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
133    if let Some(inspector) = inspector {
134        root_ctxt.infcx.attach_obligation_inspector(inspector);
135    }
136    let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
137
138    if let hir::Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
139        // Check the fake body of a global ASM. There's not much to do here except
140        // for visit the asm expr of the body.
141        let ty = fcx.check_expr(body.value);
142        fcx.write_ty(id, ty);
143    } else if let Some(hir::FnSig { header, decl, span: fn_sig_span }) = node.fn_sig() {
144        let fn_sig = if decl.output.is_suggestable_infer_ty().is_some() {
145            // In the case that we're recovering `fn() -> W<_>` or some other return
146            // type that has an infer in it, lower the type directly so that it'll
147            // be correctly filled with infer. We'll use this inference to provide
148            // a suggestion later on.
149            fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi, decl, None, None)
150        } else {
151            tcx.fn_sig(def_id).instantiate_identity()
152        };
153
154        check_abi(tcx, id, span, fn_sig.abi());
155        check_custom_abi(tcx, def_id, fn_sig.skip_binder(), *fn_sig_span);
156
157        loops::check(tcx, def_id, body);
158
159        // Compute the function signature from point of view of inside the fn.
160        let mut fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
161
162        // Normalize the input and output types one at a time, using a different
163        // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
164        // on the entire `FnSig`, since this would use the same `WellFormedLoc`
165        // for each type, preventing the HIR wf check from generating
166        // a nice error message.
167        let arg_span =
168            |idx| decl.inputs.get(idx).map_or(decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
169
170        fn_sig.inputs_and_output = tcx.mk_type_list_from_iter(
171            fn_sig
172                .inputs_and_output
173                .iter()
174                .enumerate()
175                .map(|(idx, ty)| fcx.normalize(arg_span(idx), ty)),
176        );
177
178        if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) {
179            naked_functions::typeck_naked_fn(tcx, def_id, body);
180        }
181
182        check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params());
183    } else {
184        let expected_type = if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
185            infer_ty
186        } else if let Some(ty) = node.ty()
187            && ty.is_suggestable_infer_ty()
188        {
189            // In the case that we're recovering `const X: [T; _]` or some other
190            // type that has an infer in it, lower the type directly so that it'll
191            // be correctly filled with infer. We'll use this inference to provide
192            // a suggestion later on.
193            fcx.lowerer().lower_ty(ty)
194        } else {
195            tcx.type_of(def_id).instantiate_identity()
196        };
197
198        loops::check(tcx, def_id, body);
199
200        let expected_type = fcx.normalize(body.value.span, expected_type);
201
202        let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id)));
203        fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code);
204
205        fcx.check_expr_coercible_to_type(body.value, expected_type, None);
206
207        fcx.write_ty(id, expected_type);
208    };
209
210    // Whether to check repeat exprs before/after inference fallback is somewhat
211    // arbitrary of a decision as neither option is strictly more permissive than
212    // the other. However, we opt to check repeat exprs first as errors from not
213    // having inferred array lengths yet seem less confusing than errors from inference
214    // fallback arbitrarily inferring something incompatible with `Copy` inference
215    // side effects.
216    //
217    // FIXME(#140855): This should also be forwards compatible with moving
218    // repeat expr checks to a custom goal kind or using marker traits in
219    // the future.
220    fcx.check_repeat_exprs();
221
222    // We need to handle opaque types before emitting ambiguity errors as applying
223    // defining uses may guide type inference.
224    if fcx.next_trait_solver() {
225        fcx.try_handle_opaque_type_uses_next();
226    }
227
228    fcx.type_inference_fallback();
229
230    // Even though coercion casts provide type hints, we check casts after fallback for
231    // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
232    fcx.check_casts();
233    fcx.select_obligations_where_possible(|_| {});
234
235    // Closure and coroutine analysis may run after fallback
236    // because they don't constrain other type variables.
237    fcx.closure_analyze(body);
238    assert!(fcx.deferred_call_resolutions.borrow().is_empty());
239    // Before the coroutine analysis, temporary scopes shall be marked to provide more
240    // precise information on types to be captured.
241    fcx.resolve_rvalue_scopes(def_id.to_def_id());
242
243    for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
244        let ty = fcx.normalize(span, ty);
245        fcx.require_type_is_sized(ty, span, code);
246    }
247
248    fcx.select_obligations_where_possible(|_| {});
249
250    debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
251
252    // We need to handle opaque types before emitting ambiguity errors as applying
253    // defining uses may guide type inference.
254    if fcx.next_trait_solver() {
255        fcx.handle_opaque_type_uses_next();
256    }
257
258    // This must be the last thing before `report_ambiguity_errors` below except `select_obligations_where_possible`.
259    // So don't put anything after this.
260    fcx.drain_stalled_coroutine_obligations();
261    if fcx.infcx.tainted_by_errors().is_none() {
262        fcx.report_ambiguity_errors();
263    }
264
265    fcx.check_asms();
266
267    let typeck_results = fcx.resolve_type_vars_in_body(body);
268
269    fcx.detect_opaque_types_added_during_writeback();
270
271    // Consistency check our TypeckResults instance can hold all ItemLocalIds
272    // it will need to hold.
273    assert_eq!(typeck_results.hir_owner, id.owner);
274
275    typeck_results
276}
277
278fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
279    let tcx = fcx.tcx;
280    let def_id = fcx.body_id;
281    let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
282    {
283        if let Some(item) = tcx.opt_associated_item(def_id.into())
284            && let ty::AssocKind::Const { .. } = item.kind
285            && let ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container
286        {
287            let impl_def_id = item.container_id(tcx);
288            let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity();
289            let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
290                tcx,
291                impl_def_id,
292                impl_trait_ref.args,
293            );
294            tcx.check_args_compatible(trait_item_def_id, args)
295                .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args))
296        } else {
297            Some(fcx.next_ty_var(span))
298        }
299    } else if let Node::AnonConst(_) = node {
300        let id = tcx.local_def_id_to_hir_id(def_id);
301        match tcx.parent_hir_node(id) {
302            Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(anon_const), span, .. })
303                if anon_const.hir_id == id =>
304            {
305                Some(fcx.next_ty_var(span))
306            }
307            Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
308            | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
309                asm.operands.iter().find_map(|(op, _op_sp)| match op {
310                    hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
311                        Some(fcx.next_ty_var(span))
312                    }
313                    _ => None,
314                })
315            }
316            _ => None,
317        }
318    } else {
319        None
320    };
321    expected_type
322}
323
324/// When `check_fn` is invoked on a coroutine (i.e., a body that
325/// includes yield), it returns back some information about the yield
326/// points.
327#[derive(Debug, PartialEq, Copy, Clone)]
328struct CoroutineTypes<'tcx> {
329    /// Type of coroutine argument / values returned by `yield`.
330    resume_ty: Ty<'tcx>,
331
332    /// Type of value that is yielded.
333    yield_ty: Ty<'tcx>,
334}
335
336#[derive(Copy, Clone, Debug, PartialEq, Eq)]
337pub enum Needs {
338    MutPlace,
339    None,
340}
341
342impl Needs {
343    fn maybe_mut_place(m: hir::Mutability) -> Self {
344        match m {
345            hir::Mutability::Mut => Needs::MutPlace,
346            hir::Mutability::Not => Needs::None,
347        }
348    }
349}
350
351#[derive(Debug, Copy, Clone)]
352pub enum PlaceOp {
353    Deref,
354    Index,
355}
356
357pub struct BreakableCtxt<'tcx> {
358    may_break: bool,
359
360    // this is `null` for loops where break with a value is illegal,
361    // such as `while`, `for`, and `while let`
362    coerce: Option<DynamicCoerceMany<'tcx>>,
363}
364
365pub struct EnclosingBreakables<'tcx> {
366    stack: Vec<BreakableCtxt<'tcx>>,
367    by_id: HirIdMap<usize>,
368}
369
370impl<'tcx> EnclosingBreakables<'tcx> {
371    fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
372        self.opt_find_breakable(target_id).unwrap_or_else(|| {
373            bug!("could not find enclosing breakable with id {}", target_id);
374        })
375    }
376
377    fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
378        match self.by_id.get(&target_id) {
379            Some(ix) => Some(&mut self.stack[*ix]),
380            None => None,
381        }
382    }
383}
384
385fn report_unexpected_variant_res(
386    tcx: TyCtxt<'_>,
387    res: Res,
388    expr: Option<&hir::Expr<'_>>,
389    qpath: &hir::QPath<'_>,
390    span: Span,
391    err_code: ErrCode,
392    expected: &str,
393) -> ErrorGuaranteed {
394    let res_descr = match res {
395        Res::Def(DefKind::Variant, _) => "struct variant",
396        _ => res.descr(),
397    };
398    let path_str = rustc_hir_pretty::qpath_to_string(&tcx, qpath);
399    let mut err = tcx
400        .dcx()
401        .struct_span_err(span, format!("expected {expected}, found {res_descr} `{path_str}`"))
402        .with_code(err_code);
403    match res {
404        Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
405            let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
406            err.with_span_label(span, "`fn` calls are not allowed in patterns")
407                .with_help(format!("for more information, visit {patterns_url}"))
408        }
409        Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
410            err.span_label(span, format!("not a {expected}"));
411            let variant = tcx.expect_variant_res(res);
412            let sugg = if variant.fields.is_empty() {
413                " {}".to_string()
414            } else {
415                format!(
416                    " {{ {} }}",
417                    variant
418                        .fields
419                        .iter()
420                        .map(|f| format!("{}: /* value */", f.name))
421                        .collect::<Vec<_>>()
422                        .join(", ")
423                )
424            };
425            let descr = "you might have meant to create a new value of the struct";
426            let mut suggestion = vec![];
427            match tcx.parent_hir_node(expr.hir_id) {
428                hir::Node::Expr(hir::Expr {
429                    kind: hir::ExprKind::Call(..),
430                    span: call_span,
431                    ..
432                }) => {
433                    suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
434                }
435                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(..), hir_id, .. }) => {
436                    suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
437                    if let hir::Node::Expr(parent) = tcx.parent_hir_node(*hir_id)
438                        && let hir::ExprKind::If(condition, block, None) = parent.kind
439                        && condition.hir_id == *hir_id
440                        && let hir::ExprKind::Block(block, _) = block.kind
441                        && block.stmts.is_empty()
442                        && let Some(expr) = block.expr
443                        && let hir::ExprKind::Path(..) = expr.kind
444                    {
445                        // Special case: you can incorrectly write an equality condition:
446                        // if foo == Struct { field } { /* if body */ }
447                        // which should have been written
448                        // if foo == (Struct { field }) { /* if body */ }
449                        suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
450                    } else {
451                        suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
452                    }
453                }
454                _ => {
455                    suggestion.push((span.shrink_to_hi(), sugg));
456                }
457            }
458
459            err.multipart_suggestion_verbose(descr, suggestion, Applicability::HasPlaceholders);
460            err
461        }
462        Res::Def(DefKind::Variant, _) if expr.is_none() => {
463            err.span_label(span, format!("not a {expected}"));
464
465            let fields = &tcx.expect_variant_res(res).fields.raw;
466            let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
467            let (msg, sugg) = if fields.is_empty() {
468                ("use the struct variant pattern syntax".to_string(), " {}".to_string())
469            } else {
470                let msg = format!(
471                    "the struct variant's field{s} {are} being ignored",
472                    s = pluralize!(fields.len()),
473                    are = pluralize!("is", fields.len())
474                );
475                let fields = fields
476                    .iter()
477                    .map(|field| format!("{}: _", field.ident(tcx)))
478                    .collect::<Vec<_>>()
479                    .join(", ");
480                let sugg = format!(" {{ {} }}", fields);
481                (msg, sugg)
482            };
483
484            err.span_suggestion_verbose(
485                qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
486                msg,
487                sugg,
488                Applicability::HasPlaceholders,
489            );
490            err
491        }
492        _ => err.with_span_label(span, format!("not a {expected}")),
493    }
494    .emit()
495}
496
497/// Controls whether the arguments are tupled. This is used for the call
498/// operator.
499///
500/// Tupling means that all call-side arguments are packed into a tuple and
501/// passed as a single parameter. For example, if tupling is enabled, this
502/// function:
503/// ```
504/// fn f(x: (isize, isize)) {}
505/// ```
506/// Can be called as:
507/// ```ignore UNSOLVED (can this be done in user code?)
508/// # fn f(x: (isize, isize)) {}
509/// f(1, 2);
510/// ```
511/// Instead of:
512/// ```
513/// # fn f(x: (isize, isize)) {}
514/// f((1, 2));
515/// ```
516#[derive(Copy, Clone, Eq, PartialEq)]
517enum TupleArgumentsFlag {
518    DontTupleArguments,
519    TupleArguments,
520}
521
522fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
523    let dcx = tcx.dcx();
524    let mut diag = dcx.struct_span_bug(
525        span,
526        "It looks like you're trying to break rust; would you like some ICE?",
527    );
528    diag.note("the compiler expectedly panicked. this is a feature.");
529    diag.note(
530        "we would appreciate a joke overview: \
531         https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
532    );
533    diag.note(format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_tuple(),));
534    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
535        diag.note(format!("compiler flags: {}", flags.join(" ")));
536        if excluded_cargo_defaults {
537            diag.note("some of the compiler flags provided by cargo are hidden");
538        }
539    }
540    diag.emit()
541}
542
543/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
544pub fn provide(providers: &mut Providers) {
545    *providers = Providers {
546        method_autoderef_steps: method::probe::method_autoderef_steps,
547        typeck,
548        used_trait_imports,
549        check_transmutes: intrinsicck::check_transmutes,
550        ..*providers
551    };
552}