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