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