rustc_hir_typeck/
lib.rs

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