rustc_hir_typeck/
lib.rs

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