rustc_hir_typeck/
lib.rs

1// tidy-alphabetical-start
2#![allow(rustc::diagnostic_outside_of_impl)]
3#![allow(rustc::untranslatable_diagnostic)]
4#![feature(array_windows)]
5#![feature(assert_matches)]
6#![feature(box_patterns)]
7#![feature(if_let_guard)]
8#![feature(iter_intersperse)]
9#![feature(never_type)]
10#![feature(try_blocks)]
11// tidy-alphabetical-end
12
13mod _match;
14mod autoderef;
15mod callee;
16// Used by clippy;
17pub mod cast;
18mod check;
19mod closure;
20mod coercion;
21mod demand;
22mod diverges;
23mod errors;
24mod expectation;
25mod expr;
26mod inline_asm;
27// Used by clippy;
28pub mod expr_use_visitor;
29mod fallback;
30mod fn_ctxt;
31mod gather_locals;
32mod intrinsicck;
33mod method;
34mod op;
35mod opaque_types;
36mod pat;
37mod place_op;
38mod rvalue_scopes;
39mod typeck_root_ctxt;
40mod upvar;
41mod writeback;
42
43pub use coercion::can_coerce;
44use fn_ctxt::FnCtxt;
45use rustc_data_structures::unord::UnordSet;
46use rustc_errors::codes::*;
47use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err};
48use rustc_hir as hir;
49use rustc_hir::def::{DefKind, Res};
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.def_span(def_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        fcx.check_expr_coercible_to_type(body.value, expected_type, None);
195
196        fcx.write_ty(id, expected_type);
197    };
198
199    // Whether to check repeat exprs before/after inference fallback is somewhat
200    // arbitrary of a decision as neither option is strictly more permissive than
201    // the other. However, we opt to check repeat exprs first as errors from not
202    // having inferred array lengths yet seem less confusing than errors from inference
203    // fallback arbitrarily inferring something incompatible with `Copy` inference
204    // side effects.
205    //
206    // FIXME(#140855): This should also be forwards compatible with moving
207    // repeat expr checks to a custom goal kind or using marker traits in
208    // 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    fcx.detect_opaque_types_added_during_writeback();
253
254    // Consistency check our TypeckResults instance can hold all ItemLocalIds
255    // it will need to hold.
256    assert_eq!(typeck_results.hir_owner, id.owner);
257
258    typeck_results
259}
260
261fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
262    let tcx = fcx.tcx;
263    let def_id = fcx.body_id;
264    let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
265    {
266        if let Some(item) = tcx.opt_associated_item(def_id.into())
267            && let ty::AssocKind::Const { .. } = item.kind
268            && let ty::AssocItemContainer::Impl = item.container
269            && let Some(trait_item_def_id) = item.trait_item_def_id
270        {
271            let impl_def_id = item.container_id(tcx);
272            let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity();
273            let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
274                tcx,
275                impl_def_id,
276                impl_trait_ref.args,
277            );
278            tcx.check_args_compatible(trait_item_def_id, args)
279                .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args))
280        } else {
281            Some(fcx.next_ty_var(span))
282        }
283    } else if let Node::AnonConst(_) = node {
284        let id = tcx.local_def_id_to_hir_id(def_id);
285        match tcx.parent_hir_node(id) {
286            Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(ref anon_const), span, .. })
287                if anon_const.hir_id == id =>
288            {
289                Some(fcx.next_ty_var(span))
290            }
291            Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
292            | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
293                asm.operands.iter().find_map(|(op, _op_sp)| match op {
294                    hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
295                        Some(fcx.next_ty_var(span))
296                    }
297                    _ => None,
298                })
299            }
300            _ => None,
301        }
302    } else {
303        None
304    };
305    expected_type
306}
307
308/// When `check_fn` is invoked on a coroutine (i.e., a body that
309/// includes yield), it returns back some information about the yield
310/// points.
311#[derive(Debug, PartialEq, Copy, Clone)]
312struct CoroutineTypes<'tcx> {
313    /// Type of coroutine argument / values returned by `yield`.
314    resume_ty: Ty<'tcx>,
315
316    /// Type of value that is yielded.
317    yield_ty: Ty<'tcx>,
318}
319
320#[derive(Copy, Clone, Debug, PartialEq, Eq)]
321pub enum Needs {
322    MutPlace,
323    None,
324}
325
326impl Needs {
327    fn maybe_mut_place(m: hir::Mutability) -> Self {
328        match m {
329            hir::Mutability::Mut => Needs::MutPlace,
330            hir::Mutability::Not => Needs::None,
331        }
332    }
333}
334
335#[derive(Debug, Copy, Clone)]
336pub enum PlaceOp {
337    Deref,
338    Index,
339}
340
341pub struct BreakableCtxt<'tcx> {
342    may_break: bool,
343
344    // this is `null` for loops where break with a value is illegal,
345    // such as `while`, `for`, and `while let`
346    coerce: Option<DynamicCoerceMany<'tcx>>,
347}
348
349pub struct EnclosingBreakables<'tcx> {
350    stack: Vec<BreakableCtxt<'tcx>>,
351    by_id: HirIdMap<usize>,
352}
353
354impl<'tcx> EnclosingBreakables<'tcx> {
355    fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
356        self.opt_find_breakable(target_id).unwrap_or_else(|| {
357            bug!("could not find enclosing breakable with id {}", target_id);
358        })
359    }
360
361    fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
362        match self.by_id.get(&target_id) {
363            Some(ix) => Some(&mut self.stack[*ix]),
364            None => None,
365        }
366    }
367}
368
369fn report_unexpected_variant_res(
370    tcx: TyCtxt<'_>,
371    res: Res,
372    expr: Option<&hir::Expr<'_>>,
373    qpath: &hir::QPath<'_>,
374    span: Span,
375    err_code: ErrCode,
376    expected: &str,
377) -> ErrorGuaranteed {
378    let res_descr = match res {
379        Res::Def(DefKind::Variant, _) => "struct variant",
380        _ => res.descr(),
381    };
382    let path_str = rustc_hir_pretty::qpath_to_string(&tcx, qpath);
383    let mut err = tcx
384        .dcx()
385        .struct_span_err(span, format!("expected {expected}, found {res_descr} `{path_str}`"))
386        .with_code(err_code);
387    match res {
388        Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
389            let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
390            err.with_span_label(span, "`fn` calls are not allowed in patterns")
391                .with_help(format!("for more information, visit {patterns_url}"))
392        }
393        Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
394            err.span_label(span, format!("not a {expected}"));
395            let variant = tcx.expect_variant_res(res);
396            let sugg = if variant.fields.is_empty() {
397                " {}".to_string()
398            } else {
399                format!(
400                    " {{ {} }}",
401                    variant
402                        .fields
403                        .iter()
404                        .map(|f| format!("{}: /* value */", f.name))
405                        .collect::<Vec<_>>()
406                        .join(", ")
407                )
408            };
409            let descr = "you might have meant to create a new value of the struct";
410            let mut suggestion = vec![];
411            match tcx.parent_hir_node(expr.hir_id) {
412                hir::Node::Expr(hir::Expr {
413                    kind: hir::ExprKind::Call(..),
414                    span: call_span,
415                    ..
416                }) => {
417                    suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
418                }
419                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(..), hir_id, .. }) => {
420                    suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
421                    if let hir::Node::Expr(drop_temps) = tcx.parent_hir_node(*hir_id)
422                        && let hir::ExprKind::DropTemps(_) = drop_temps.kind
423                        && let hir::Node::Expr(parent) = tcx.parent_hir_node(drop_temps.hir_id)
424                        && let hir::ExprKind::If(condition, block, None) = parent.kind
425                        && condition.hir_id == drop_temps.hir_id
426                        && let hir::ExprKind::Block(block, _) = block.kind
427                        && block.stmts.is_empty()
428                        && let Some(expr) = block.expr
429                        && let hir::ExprKind::Path(..) = expr.kind
430                    {
431                        // Special case: you can incorrectly write an equality condition:
432                        // if foo == Struct { field } { /* if body */ }
433                        // which should have been written
434                        // if foo == (Struct { field }) { /* if body */ }
435                        suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
436                    } else {
437                        suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
438                    }
439                }
440                _ => {
441                    suggestion.push((span.shrink_to_hi(), sugg));
442                }
443            }
444
445            err.multipart_suggestion_verbose(descr, suggestion, Applicability::HasPlaceholders);
446            err
447        }
448        Res::Def(DefKind::Variant, _) if expr.is_none() => {
449            err.span_label(span, format!("not a {expected}"));
450
451            let fields = &tcx.expect_variant_res(res).fields.raw;
452            let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
453            let (msg, sugg) = if fields.is_empty() {
454                ("use the struct variant pattern syntax".to_string(), " {}".to_string())
455            } else {
456                let msg = format!(
457                    "the struct variant's field{s} {are} being ignored",
458                    s = pluralize!(fields.len()),
459                    are = pluralize!("is", fields.len())
460                );
461                let fields = fields
462                    .iter()
463                    .map(|field| format!("{}: _", field.ident(tcx)))
464                    .collect::<Vec<_>>()
465                    .join(", ");
466                let sugg = format!(" {{ {} }}", fields);
467                (msg, sugg)
468            };
469
470            err.span_suggestion_verbose(
471                qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
472                msg,
473                sugg,
474                Applicability::HasPlaceholders,
475            );
476            err
477        }
478        _ => err.with_span_label(span, format!("not a {expected}")),
479    }
480    .emit()
481}
482
483/// Controls whether the arguments are tupled. This is used for the call
484/// operator.
485///
486/// Tupling means that all call-side arguments are packed into a tuple and
487/// passed as a single parameter. For example, if tupling is enabled, this
488/// function:
489/// ```
490/// fn f(x: (isize, isize)) {}
491/// ```
492/// Can be called as:
493/// ```ignore UNSOLVED (can this be done in user code?)
494/// # fn f(x: (isize, isize)) {}
495/// f(1, 2);
496/// ```
497/// Instead of:
498/// ```
499/// # fn f(x: (isize, isize)) {}
500/// f((1, 2));
501/// ```
502#[derive(Copy, Clone, Eq, PartialEq)]
503enum TupleArgumentsFlag {
504    DontTupleArguments,
505    TupleArguments,
506}
507
508fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
509    let dcx = tcx.dcx();
510    let mut diag = dcx.struct_span_bug(
511        span,
512        "It looks like you're trying to break rust; would you like some ICE?",
513    );
514    diag.note("the compiler expectedly panicked. this is a feature.");
515    diag.note(
516        "we would appreciate a joke overview: \
517         https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
518    );
519    diag.note(format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_tuple(),));
520    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
521        diag.note(format!("compiler flags: {}", flags.join(" ")));
522        if excluded_cargo_defaults {
523            diag.note("some of the compiler flags provided by cargo are hidden");
524        }
525    }
526    diag.emit()
527}
528
529pub fn provide(providers: &mut Providers) {
530    method::provide(providers);
531    *providers = Providers { typeck, used_trait_imports, ..*providers };
532}