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 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;
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};
57use rustc_middle::{bug, span_bug};
58use rustc_session::config;
59use rustc_span::def_id::LocalDefId;
60use rustc_span::{Span, sym};
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, .. }) = 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, span, fn_sig.abi());
154
155        // Compute the function signature from point of view of inside the fn.
156        let mut fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
157
158        // Normalize the input and output types one at a time, using a different
159        // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
160        // on the entire `FnSig`, since this would use the same `WellFormedLoc`
161        // for each type, preventing the HIR wf check from generating
162        // a nice error message.
163        let arg_span =
164            |idx| decl.inputs.get(idx).map_or(decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
165
166        fn_sig.inputs_and_output = tcx.mk_type_list_from_iter(
167            fn_sig
168                .inputs_and_output
169                .iter()
170                .enumerate()
171                .map(|(idx, ty)| fcx.normalize(arg_span(idx), ty)),
172        );
173
174        if tcx.has_attr(def_id, sym::naked) {
175            naked_functions::typeck_naked_fn(tcx, def_id, body);
176        }
177
178        check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params());
179    } else {
180        let expected_type = if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
181            infer_ty
182        } else if let Some(ty) = node.ty()
183            && ty.is_suggestable_infer_ty()
184        {
185            // In the case that we're recovering `const X: [T; _]` or some other
186            // type that has an infer in it, lower the type directly so that it'll
187            // be correctly filled with infer. We'll use this inference to provide
188            // a suggestion later on.
189            fcx.lowerer().lower_ty(ty)
190        } else {
191            tcx.type_of(def_id).instantiate_identity()
192        };
193
194        let expected_type = fcx.normalize(body.value.span, expected_type);
195
196        let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id)));
197        fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code);
198
199        fcx.check_expr_coercible_to_type(body.value, expected_type, None);
200
201        fcx.write_ty(id, expected_type);
202    };
203
204    // Whether to check repeat exprs before/after inference fallback is somewhat
205    // arbitrary of a decision as neither option is strictly more permissive than
206    // the other. However, we opt to check repeat exprs first as errors from not
207    // having inferred array lengths yet seem less confusing than errors from inference
208    // fallback arbitrarily inferring something incompatible with `Copy` inference
209    // side effects.
210    //
211    // FIXME(#140855): This should also be forwards compatible with moving
212    // repeat expr checks to a custom goal kind or using marker traits in
213    // the future.
214    fcx.check_repeat_exprs();
215
216    fcx.type_inference_fallback();
217
218    // Even though coercion casts provide type hints, we check casts after fallback for
219    // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
220    fcx.check_casts();
221    fcx.select_obligations_where_possible(|_| {});
222
223    // Closure and coroutine analysis may run after fallback
224    // because they don't constrain other type variables.
225    fcx.closure_analyze(body);
226    assert!(fcx.deferred_call_resolutions.borrow().is_empty());
227    // Before the coroutine analysis, temporary scopes shall be marked to provide more
228    // precise information on types to be captured.
229    fcx.resolve_rvalue_scopes(def_id.to_def_id());
230
231    for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
232        let ty = fcx.normalize(span, ty);
233        fcx.require_type_is_sized(ty, span, code);
234    }
235
236    fcx.select_obligations_where_possible(|_| {});
237
238    debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
239
240    // This must be the last thing before `report_ambiguity_errors`.
241    fcx.resolve_coroutine_interiors();
242
243    debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
244
245    if let None = fcx.infcx.tainted_by_errors() {
246        fcx.report_ambiguity_errors();
247    }
248
249    if let None = fcx.infcx.tainted_by_errors() {
250        fcx.check_transmutes();
251    }
252
253    fcx.check_asms();
254
255    let typeck_results = fcx.resolve_type_vars_in_body(body);
256
257    fcx.detect_opaque_types_added_during_writeback();
258
259    // Consistency check our TypeckResults instance can hold all ItemLocalIds
260    // it will need to hold.
261    assert_eq!(typeck_results.hir_owner, id.owner);
262
263    typeck_results
264}
265
266fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
267    let tcx = fcx.tcx;
268    let def_id = fcx.body_id;
269    let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
270    {
271        if let Some(item) = tcx.opt_associated_item(def_id.into())
272            && let ty::AssocKind::Const { .. } = item.kind
273            && let ty::AssocItemContainer::Impl = item.container
274            && let Some(trait_item_def_id) = item.trait_item_def_id
275        {
276            let impl_def_id = item.container_id(tcx);
277            let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity();
278            let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
279                tcx,
280                impl_def_id,
281                impl_trait_ref.args,
282            );
283            tcx.check_args_compatible(trait_item_def_id, args)
284                .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args))
285        } else {
286            Some(fcx.next_ty_var(span))
287        }
288    } else if let Node::AnonConst(_) = node {
289        let id = tcx.local_def_id_to_hir_id(def_id);
290        match tcx.parent_hir_node(id) {
291            Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(ref anon_const), span, .. })
292                if anon_const.hir_id == id =>
293            {
294                Some(fcx.next_ty_var(span))
295            }
296            Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
297            | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
298                asm.operands.iter().find_map(|(op, _op_sp)| match op {
299                    hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
300                        Some(fcx.next_ty_var(span))
301                    }
302                    _ => None,
303                })
304            }
305            _ => None,
306        }
307    } else {
308        None
309    };
310    expected_type
311}
312
313/// When `check_fn` is invoked on a coroutine (i.e., a body that
314/// includes yield), it returns back some information about the yield
315/// points.
316#[derive(Debug, PartialEq, Copy, Clone)]
317struct CoroutineTypes<'tcx> {
318    /// Type of coroutine argument / values returned by `yield`.
319    resume_ty: Ty<'tcx>,
320
321    /// Type of value that is yielded.
322    yield_ty: Ty<'tcx>,
323}
324
325#[derive(Copy, Clone, Debug, PartialEq, Eq)]
326pub enum Needs {
327    MutPlace,
328    None,
329}
330
331impl Needs {
332    fn maybe_mut_place(m: hir::Mutability) -> Self {
333        match m {
334            hir::Mutability::Mut => Needs::MutPlace,
335            hir::Mutability::Not => Needs::None,
336        }
337    }
338}
339
340#[derive(Debug, Copy, Clone)]
341pub enum PlaceOp {
342    Deref,
343    Index,
344}
345
346pub struct BreakableCtxt<'tcx> {
347    may_break: bool,
348
349    // this is `null` for loops where break with a value is illegal,
350    // such as `while`, `for`, and `while let`
351    coerce: Option<DynamicCoerceMany<'tcx>>,
352}
353
354pub struct EnclosingBreakables<'tcx> {
355    stack: Vec<BreakableCtxt<'tcx>>,
356    by_id: HirIdMap<usize>,
357}
358
359impl<'tcx> EnclosingBreakables<'tcx> {
360    fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
361        self.opt_find_breakable(target_id).unwrap_or_else(|| {
362            bug!("could not find enclosing breakable with id {}", target_id);
363        })
364    }
365
366    fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
367        match self.by_id.get(&target_id) {
368            Some(ix) => Some(&mut self.stack[*ix]),
369            None => None,
370        }
371    }
372}
373
374fn report_unexpected_variant_res(
375    tcx: TyCtxt<'_>,
376    res: Res,
377    expr: Option<&hir::Expr<'_>>,
378    qpath: &hir::QPath<'_>,
379    span: Span,
380    err_code: ErrCode,
381    expected: &str,
382) -> ErrorGuaranteed {
383    let res_descr = match res {
384        Res::Def(DefKind::Variant, _) => "struct variant",
385        _ => res.descr(),
386    };
387    let path_str = rustc_hir_pretty::qpath_to_string(&tcx, qpath);
388    let mut err = tcx
389        .dcx()
390        .struct_span_err(span, format!("expected {expected}, found {res_descr} `{path_str}`"))
391        .with_code(err_code);
392    match res {
393        Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
394            let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
395            err.with_span_label(span, "`fn` calls are not allowed in patterns")
396                .with_help(format!("for more information, visit {patterns_url}"))
397        }
398        Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
399            err.span_label(span, format!("not a {expected}"));
400            let variant = tcx.expect_variant_res(res);
401            let sugg = if variant.fields.is_empty() {
402                " {}".to_string()
403            } else {
404                format!(
405                    " {{ {} }}",
406                    variant
407                        .fields
408                        .iter()
409                        .map(|f| format!("{}: /* value */", f.name))
410                        .collect::<Vec<_>>()
411                        .join(", ")
412                )
413            };
414            let descr = "you might have meant to create a new value of the struct";
415            let mut suggestion = vec![];
416            match tcx.parent_hir_node(expr.hir_id) {
417                hir::Node::Expr(hir::Expr {
418                    kind: hir::ExprKind::Call(..),
419                    span: call_span,
420                    ..
421                }) => {
422                    suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
423                }
424                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(..), hir_id, .. }) => {
425                    suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
426                    if let hir::Node::Expr(drop_temps) = tcx.parent_hir_node(*hir_id)
427                        && let hir::ExprKind::DropTemps(_) = drop_temps.kind
428                        && let hir::Node::Expr(parent) = tcx.parent_hir_node(drop_temps.hir_id)
429                        && let hir::ExprKind::If(condition, block, None) = parent.kind
430                        && condition.hir_id == drop_temps.hir_id
431                        && let hir::ExprKind::Block(block, _) = block.kind
432                        && block.stmts.is_empty()
433                        && let Some(expr) = block.expr
434                        && let hir::ExprKind::Path(..) = expr.kind
435                    {
436                        // Special case: you can incorrectly write an equality condition:
437                        // if foo == Struct { field } { /* if body */ }
438                        // which should have been written
439                        // if foo == (Struct { field }) { /* if body */ }
440                        suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
441                    } else {
442                        suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
443                    }
444                }
445                _ => {
446                    suggestion.push((span.shrink_to_hi(), sugg));
447                }
448            }
449
450            err.multipart_suggestion_verbose(descr, suggestion, Applicability::HasPlaceholders);
451            err
452        }
453        Res::Def(DefKind::Variant, _) if expr.is_none() => {
454            err.span_label(span, format!("not a {expected}"));
455
456            let fields = &tcx.expect_variant_res(res).fields.raw;
457            let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
458            let (msg, sugg) = if fields.is_empty() {
459                ("use the struct variant pattern syntax".to_string(), " {}".to_string())
460            } else {
461                let msg = format!(
462                    "the struct variant's field{s} {are} being ignored",
463                    s = pluralize!(fields.len()),
464                    are = pluralize!("is", fields.len())
465                );
466                let fields = fields
467                    .iter()
468                    .map(|field| format!("{}: _", field.ident(tcx)))
469                    .collect::<Vec<_>>()
470                    .join(", ");
471                let sugg = format!(" {{ {} }}", fields);
472                (msg, sugg)
473            };
474
475            err.span_suggestion_verbose(
476                qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
477                msg,
478                sugg,
479                Applicability::HasPlaceholders,
480            );
481            err
482        }
483        _ => err.with_span_label(span, format!("not a {expected}")),
484    }
485    .emit()
486}
487
488/// Controls whether the arguments are tupled. This is used for the call
489/// operator.
490///
491/// Tupling means that all call-side arguments are packed into a tuple and
492/// passed as a single parameter. For example, if tupling is enabled, this
493/// function:
494/// ```
495/// fn f(x: (isize, isize)) {}
496/// ```
497/// Can be called as:
498/// ```ignore UNSOLVED (can this be done in user code?)
499/// # fn f(x: (isize, isize)) {}
500/// f(1, 2);
501/// ```
502/// Instead of:
503/// ```
504/// # fn f(x: (isize, isize)) {}
505/// f((1, 2));
506/// ```
507#[derive(Copy, Clone, Eq, PartialEq)]
508enum TupleArgumentsFlag {
509    DontTupleArguments,
510    TupleArguments,
511}
512
513fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
514    let dcx = tcx.dcx();
515    let mut diag = dcx.struct_span_bug(
516        span,
517        "It looks like you're trying to break rust; would you like some ICE?",
518    );
519    diag.note("the compiler expectedly panicked. this is a feature.");
520    diag.note(
521        "we would appreciate a joke overview: \
522         https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
523    );
524    diag.note(format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_tuple(),));
525    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
526        diag.note(format!("compiler flags: {}", flags.join(" ")));
527        if excluded_cargo_defaults {
528            diag.note("some of the compiler flags provided by cargo are hidden");
529        }
530    }
531    diag.emit()
532}
533
534pub fn provide(providers: &mut Providers) {
535    method::provide(providers);
536    *providers = Providers { typeck, used_trait_imports, ..*providers };
537}