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