rustc_hir_typeck/
lib.rs

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