Skip to main content

rustc_hir_typeck/
lib.rs

1// tidy-alphabetical-start
2#![feature(deref_patterns)]
3#![feature(iter_intersperse)]
4#![feature(iter_order_by)]
5#![feature(never_type)]
6#![feature(option_into_flat_iter)]
7#![feature(option_reference_flattening)]
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 diagnostics;
21mod diverges;
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, Diag, ErrorGuaranteed, 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, FnSigKind, Ty, TyCtxt, Unnormalized};
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
70#[macro_export]
71macro_rules! type_error_struct {
72    ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({
73        let mut err = rustc_errors::struct_span_code_err!($dcx, $span, $code, $($message)*);
74
75        if $typ.references_error() {
76            err.downgrade_to_delayed_bug();
77        }
78
79        err
80    })
81}
82
83fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> {
84    &tcx.typeck(def_id).used_trait_imports
85}
86
87fn typeck_root<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
88    typeck_with_inspect(tcx, def_id, None)
89}
90
91/// Same as `typeck` but `inspect` is invoked on evaluation of each root obligation.
92/// Inspecting obligations only works with the new trait solver.
93/// This function is *only to be used* by external tools, it should not be
94/// called from within rustc. Note, this is not a query, and thus is not cached.
95pub fn inspect_typeck<'tcx>(
96    tcx: TyCtxt<'tcx>,
97    def_id: LocalDefId,
98    inspect: ObligationInspector<'tcx>,
99) -> &'tcx ty::TypeckResults<'tcx> {
100    // Closures' typeck results come from their outermost function,
101    // as they are part of the same "inference environment".
102    let typeck_root_def_id = tcx.typeck_root_def_id_local(def_id);
103    if typeck_root_def_id != def_id {
104        return tcx.typeck(typeck_root_def_id);
105    }
106
107    typeck_with_inspect(tcx, def_id, Some(inspect))
108}
109
110x;#[instrument(level = "debug", skip(tcx, inspector), ret)]
111fn typeck_with_inspect<'tcx>(
112    tcx: TyCtxt<'tcx>,
113    def_id: LocalDefId,
114    inspector: Option<ObligationInspector<'tcx>>,
115) -> &'tcx ty::TypeckResults<'tcx> {
116    assert!(!tcx.is_typeck_child(def_id.to_def_id()));
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().skip_norm_wip()
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), Unnormalized::new_wip(ty))),
174        );
175
176        if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::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().skip_norm_wip()
194        };
195
196        loops::check(tcx, def_id, body);
197
198        let expected_type = fcx.normalize(body.value.span, Unnormalized::new_wip(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        if let hir::Node::AnonConst(_) = node {
204            fcx.require_type_is_sized(
205                expected_type,
206                body.value.span,
207                ObligationCauseCode::SizedConstOrStatic,
208            );
209        }
210
211        fcx.check_expr_coercible_to_type_or_error(body.value, expected_type, None, |err, _| {
212            extend_err_with_const_context(err, tcx, node, expected_type);
213        });
214
215        fcx.write_ty(id, expected_type);
216    };
217
218    // Whether to check repeat exprs before/after inference fallback is somewhat
219    // arbitrary of a decision as neither option is strictly more permissive than
220    // the other. However, we opt to check repeat exprs first as errors from not
221    // having inferred array lengths yet seem less confusing than errors from inference
222    // fallback arbitrarily inferring something incompatible with `Copy` inference
223    // side effects.
224    //
225    // FIXME(#140855): This should also be forwards compatible with moving
226    // repeat expr checks to a custom goal kind or using marker traits in
227    // the future.
228    fcx.check_repeat_exprs();
229
230    // We need to handle opaque types before emitting ambiguity errors as applying
231    // defining uses may guide type inference.
232    if fcx.next_trait_solver() {
233        fcx.try_handle_opaque_type_uses_next();
234    }
235
236    fcx.type_inference_fallback();
237
238    // Even though coercion casts provide type hints, we check casts after fallback for
239    // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
240    fcx.check_casts();
241    fcx.select_obligations_where_possible(|_| {});
242
243    // Closure and coroutine analysis may run after fallback
244    // because they don't constrain other type variables.
245    fcx.closure_analyze(body);
246    assert!(fcx.deferred_call_resolutions.borrow().is_empty());
247
248    for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
249        let ty = fcx.normalize(span, Unnormalized::new_wip(ty));
250        fcx.require_type_is_sized(ty, span, code);
251    }
252
253    fcx.select_obligations_where_possible(|_| {});
254
255    debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
256
257    // We need to handle opaque types before emitting ambiguity errors as applying
258    // defining uses may guide type inference.
259    if fcx.next_trait_solver() {
260        fcx.handle_opaque_type_uses_next();
261    }
262
263    // This must be the last thing before `report_ambiguity_errors` below except `select_obligations_where_possible`.
264    // So don't put anything after this.
265    fcx.drain_stalled_coroutine_obligations();
266    if fcx.infcx.tainted_by_errors().is_none() {
267        fcx.report_ambiguity_errors();
268    }
269
270    fcx.check_asms();
271
272    let typeck_results = fcx.resolve_type_vars_in_body(body);
273
274    fcx.detect_opaque_types_added_during_writeback();
275
276    // Consistency check our TypeckResults instance can hold all ItemLocalIds
277    // it will need to hold.
278    assert_eq!(typeck_results.hir_owner, id.owner);
279
280    typeck_results
281}
282
283fn extend_err_with_const_context(
284    err: &mut Diag<'_>,
285    tcx: TyCtxt<'_>,
286    node: hir::Node<'_>,
287    expected_ty: Ty<'_>,
288) {
289    match node {
290        hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), .. })
291        | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Const(ty, _), .. }) => {
292            // Point at the `Type` in `const NAME: Type = value;`.
293            err.span_label(ty.span, "expected because of the type of the associated constant");
294        }
295        hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
296            // Point at the `Type` in `const NAME: Type = value;`.
297            err.span_label(ty.span, "expected because of the type of the constant");
298        }
299        hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(_, _, ty, _), .. }) => {
300            // Point at the `Type` in `static NAME: Type = value;`.
301            err.span_label(ty.span, "expected because of the type of the static");
302        }
303        hir::Node::AnonConst(anon)
304            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
305                && let hir::Node::Ty(parent) = tcx.parent_hir_node(parent.hir_id)
306                && let hir::TyKind::Array(_ty, _len) = parent.kind =>
307        {
308            // `[type; len]` in type context.
309            err.note("array length can only be `usize`");
310        }
311        hir::Node::AnonConst(anon)
312            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
313                && let hir::Node::Expr(parent) = tcx.parent_hir_node(parent.hir_id)
314                && let hir::ExprKind::Repeat(_ty, _len) = parent.kind =>
315        {
316            // `[type; len]` in expr context.
317            err.note("array length can only be `usize`");
318        }
319        // FIXME: support method calls too.
320        hir::Node::AnonConst(anon)
321            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
322                && let Some(path) = tcx.parent_hir_node(parent.hir_id).path()
323                && let hir::QPath::Resolved(_, path) = path
324                && let Res::Def(_, def_id) = path.res =>
325        {
326            // `foo<N>()`, point at the const parameter in the definition of `foo`.
327            if let Some(i) =
328                path.segments.iter().last().and_then(|segment| segment.args).and_then(|args| {
329                    args.args.iter().position(|arg| {
330                        #[allow(non_exhaustive_omitted_patterns)] match arg {
    hir::GenericArg::Const(arg) if arg.hir_id == parent.hir_id => true,
    _ => false,
}matches!(arg, hir::GenericArg::Const(arg) if arg.hir_id == parent.hir_id)
331                    })
332                })
333            {
334                let generics = tcx.generics_of(def_id);
335                let param = &generics.param_at(i, tcx);
336                let sp = tcx.def_span(param.def_id);
337                err.span_note(sp, "expected because of the type of the const parameter");
338            }
339        }
340        hir::Node::AnonConst(anon)
341            if let hir::Node::Variant(_variant) = tcx.parent_hir_node(anon.hir_id) =>
342        {
343            // FIXME: point at `repr` when present in the type.
344            err.note(
345                "enum variant discriminant can only be of a primitive type compatible with the \
346                 enum's `repr`",
347            );
348        }
349        hir::Node::AnonConst(anon)
350            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
351                && let hir::Node::GenericParam(param) = tcx.parent_hir_node(parent.hir_id)
352                && let hir::GenericParamKind::Const { ty, .. } = param.kind =>
353        {
354            // `fn foo<const N: usize = ()>` point at the `usize`.
355            err.span_label(ty.span, "expected because of the type of the const parameter");
356        }
357        hir::Node::AnonConst(anon)
358            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
359                && let hir::Node::TyPat(ty_pat) = tcx.parent_hir_node(parent.hir_id)
360                && let hir::Node::Ty(ty) = tcx.parent_hir_node(ty_pat.hir_id)
361                && let hir::TyKind::Pat(ty, _) = ty.kind =>
362        {
363            // Point at `char` in `pattern_type!(char is 1..=1)`.
364            err.span_label(ty.span, "the pattern must match the type");
365        }
366        hir::Node::AnonConst(anon)
367            if let hir::Node::Field(_) = tcx.parent_hir_node(anon.hir_id)
368                && let ty::Param(_) = expected_ty.kind() =>
369        {
370            err.note(
371                "the type of default fields referencing type parameters can't be assumed inside \
372                 the struct defining them",
373            );
374        }
375        _ => {}
376    }
377}
378
379fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
380    let tcx = fcx.tcx;
381    let def_id = fcx.body_def_id;
382    let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
383    {
384        if let Some(item) = tcx.opt_associated_item(def_id.into())
385            && let ty::AssocKind::Const { .. } = item.kind
386            && let ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container
387        {
388            let impl_def_id = item.container_id(tcx);
389            let impl_trait_ref =
390                tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
391            let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
392                tcx,
393                impl_def_id,
394                impl_trait_ref.args,
395            );
396            tcx.check_args_compatible(trait_item_def_id, args)
397                .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args).skip_norm_wip())
398        } else {
399            Some(fcx.next_ty_var(span))
400        }
401    } else if let Node::AnonConst(_) = node {
402        let id = tcx.local_def_id_to_hir_id(def_id);
403        match tcx.parent_hir_node(id) {
404            Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
405            | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
406                asm.operands.iter().find_map(|(op, _op_sp)| match op {
407                    hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
408                        Some(fcx.next_ty_var(span))
409                    }
410                    _ => None,
411                })
412            }
413            _ => None,
414        }
415    } else {
416        None
417    };
418    expected_type
419}
420
421/// When `check_fn` is invoked on a coroutine (i.e., a body that
422/// includes yield), it returns back some information about the yield
423/// points.
424#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CoroutineTypes<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "CoroutineTypes", "resume_ty", &self.resume_ty, "yield_ty",
            &&self.yield_ty)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for CoroutineTypes<'tcx> {
    #[inline]
    fn eq(&self, other: &CoroutineTypes<'tcx>) -> bool {
        self.resume_ty == other.resume_ty && self.yield_ty == other.yield_ty
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for CoroutineTypes<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for CoroutineTypes<'tcx> {
    #[inline]
    fn clone(&self) -> CoroutineTypes<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone)]
425struct CoroutineTypes<'tcx> {
426    /// Type of coroutine argument / values returned by `yield`.
427    resume_ty: Ty<'tcx>,
428
429    /// Type of value that is yielded.
430    yield_ty: Ty<'tcx>,
431}
432
433#[derive(#[automatically_derived]
impl ::core::marker::Copy for Needs { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Needs {
    #[inline]
    fn clone(&self) -> Needs { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Needs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Needs::MutPlace => "MutPlace",
                Needs::None => "None",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Needs {
    #[inline]
    fn eq(&self, other: &Needs) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Needs {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
434pub enum Needs {
435    MutPlace,
436    None,
437}
438
439impl Needs {
440    fn maybe_mut_place(m: hir::Mutability) -> Self {
441        match m {
442            hir::Mutability::Mut => Needs::MutPlace,
443            hir::Mutability::Not => Needs::None,
444        }
445    }
446}
447
448#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PlaceOp {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PlaceOp::Deref => "Deref",
                PlaceOp::Index => "Index",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for PlaceOp { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PlaceOp {
    #[inline]
    fn clone(&self) -> PlaceOp { *self }
}Clone)]
449pub enum PlaceOp {
450    Deref,
451    Index,
452}
453
454pub struct BreakableCtxt<'tcx> {
455    may_break: bool,
456
457    // this is `null` for loops where break with a value is illegal,
458    // such as `while`, `for`, and `while let`
459    coerce: Option<CoerceMany<'tcx>>,
460}
461
462pub struct EnclosingBreakables<'tcx> {
463    stack: Vec<BreakableCtxt<'tcx>>,
464    by_id: HirIdMap<usize>,
465}
466
467impl<'tcx> EnclosingBreakables<'tcx> {
468    fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
469        self.opt_find_breakable(target_id).unwrap_or_else(|| {
470            ::rustc_middle::util::bug::bug_fmt(format_args!("could not find enclosing breakable with id {0}",
        target_id));bug!("could not find enclosing breakable with id {}", target_id);
471        })
472    }
473
474    fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
475        match self.by_id.get(&target_id) {
476            Some(ix) => Some(&mut self.stack[*ix]),
477            None => None,
478        }
479    }
480}
481
482fn report_unexpected_variant_res(
483    tcx: TyCtxt<'_>,
484    res: Res,
485    expr: Option<&hir::Expr<'_>>,
486    sub_pats: &[hir::Pat<'_>],
487    qpath: &hir::QPath<'_>,
488    span: Span,
489    err_code: ErrCode,
490    expected: &str,
491) -> ErrorGuaranteed {
492    let res_descr = match res {
493        Res::Def(DefKind::Variant, _) => "struct variant",
494        _ => res.descr(),
495    };
496    let path_str = rustc_hir_pretty::qpath_to_string(&tcx, qpath);
497    let mut err = tcx
498        .dcx()
499        .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}`",
                expected, res_descr, path_str))
    })format!("expected {expected}, found {res_descr} `{path_str}`"))
500        .with_code(err_code);
501    match res {
502        Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
503            let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
504            err.with_span_label(span, "`fn` calls are not allowed in patterns")
505                .with_help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("for more information, visit {0}",
                patterns_url))
    })format!("for more information, visit {patterns_url}"))
506        }
507        Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
508            err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"));
509            let variant = tcx.expect_variant_res(res);
510            let sugg = if variant.fields.is_empty() {
511                " {}".to_string()
512            } else {
513                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0} }}",
                variant.fields.iter().map(|f|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0}: /* value */",
                                                f.name))
                                    })).collect::<Vec<_>>().join(", ")))
    })format!(
514                    " {{ {} }}",
515                    variant
516                        .fields
517                        .iter()
518                        .map(|f| format!("{}: /* value */", f.name))
519                        .collect::<Vec<_>>()
520                        .join(", ")
521                )
522            };
523            let descr = "you might have meant to create a new value of the struct";
524            let mut suggestion = ::alloc::vec::Vec::new()vec![];
525            match tcx.parent_hir_node(expr.hir_id) {
526                hir::Node::Expr(hir::Expr {
527                    kind: hir::ExprKind::Call(..),
528                    span: call_span,
529                    ..
530                }) => {
531                    suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
532                }
533                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(..), hir_id, .. }) => {
534                    suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
535                    if let hir::Node::Expr(parent) = tcx.parent_hir_node(*hir_id)
536                        && let hir::ExprKind::If(condition, block, None) = parent.kind
537                        && condition.hir_id == *hir_id
538                        && let hir::ExprKind::Block(block, _) = block.kind
539                        && block.stmts.is_empty()
540                        && let Some(expr) = block.expr
541                        && let hir::ExprKind::Path(..) = expr.kind
542                    {
543                        // Special case: you can incorrectly write an equality condition:
544                        // if foo == Struct { field } { /* if body */ }
545                        // which should have been written
546                        // if foo == (Struct { field }) { /* if body */ }
547                        suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
548                    } else {
549                        suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
550                    }
551                }
552                _ => {
553                    suggestion.push((span.shrink_to_hi(), sugg));
554                }
555            }
556
557            err.multipart_suggestion(descr, suggestion, Applicability::HasPlaceholders);
558            err
559        }
560        Res::Def(DefKind::Variant, _) if expr.is_none() => {
561            err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"));
562
563            let fields = &tcx.expect_variant_res(res).fields.raw;
564            let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
565            let (msg, sugg) = if fields.is_empty() {
566                ("use the struct variant pattern syntax", " {}".to_string())
567            } else {
568                let msg = if fields.is_empty() {
569                    "use struct variant pattern syntax"
570                } else {
571                    "add the names to match a struct variant's fields"
572                };
573                let fields_sugg = fields
574                    .iter()
575                    .enumerate()
576                    .map(|(i, field)| {
577                        let field_name = field.ident(tcx).to_string();
578
579                        let pat_snippet = sub_pats
580                            .get(i)
581                            .and_then(|sub_pat| {
582                                tcx.sess.source_map().span_to_snippet(sub_pat.span).ok()
583                            })
584                            .unwrap_or_else(|| "_".to_string());
585
586                        if field_name == pat_snippet {
587                            field_name
588                        } else {
589                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", field_name,
                pat_snippet))
    })format!("{field_name}: {pat_snippet}")
590                        }
591                    })
592                    .collect::<Vec<_>>()
593                    .join(", ");
594                let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0} }}", fields_sugg))
    })format!(" {{ {} }}", fields_sugg);
595                (msg, sugg)
596            };
597
598            err.span_suggestion_verbose(
599                qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
600                msg,
601                sugg,
602                Applicability::HasPlaceholders,
603            );
604            err
605        }
606        _ => err.with_span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}")),
607    }
608    .emit()
609}
610
611/// Controls whether all arguments are tupled. This is used for the call operator only.
612///
613/// Tupling means that all call-side arguments are packed into a tuple and passed as a single
614/// parameter. For example, if tupling is enabled, this function:
615/// ```
616/// fn f(x: (isize, isize)) {}
617/// ```
618/// Can be called as:
619/// ```ignore UNSOLVED (can this be done in user code?)
620/// # fn f(x: (isize, isize)) {}
621/// f(1, 2);
622/// ```
623/// Instead of:
624/// ```
625/// # fn f(x: (isize, isize)) {}
626/// f((1, 2));
627/// ```
628///
629/// Note: splatted arguments are handled separately.
630#[derive(#[automatically_derived]
impl ::core::marker::Copy for TupleArgumentsFlag { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TupleArgumentsFlag {
    #[inline]
    fn clone(&self) -> TupleArgumentsFlag {
        let _: ::core::clone::AssertParamIsClone<u8>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TupleArgumentsFlag {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TupleArgumentsFlag::DontTupleArguments =>
                ::core::fmt::Formatter::write_str(f, "DontTupleArguments"),
            TupleArgumentsFlag::TupleAllCallArgs =>
                ::core::fmt::Formatter::write_str(f, "TupleAllCallArgs"),
            TupleArgumentsFlag::TupleSplattedSelfArg =>
                ::core::fmt::Formatter::write_str(f, "TupleSplattedSelfArg"),
            TupleArgumentsFlag::TupleSplattedArg(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TupleSplattedArg", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for TupleArgumentsFlag {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u8>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for TupleArgumentsFlag {
    #[inline]
    fn eq(&self, other: &TupleArgumentsFlag) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (TupleArgumentsFlag::TupleSplattedArg(__self_0),
                    TupleArgumentsFlag::TupleSplattedArg(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
631enum TupleArgumentsFlag {
632    /// Arguments are typechecked unchanged.
633    DontTupleArguments,
634    /// This is a call operator: all caller arguments are tupled before typechecking.
635    /// Set based on the "rust-call" ABI and Fn* traits.
636    TupleAllCallArgs,
637    /// The `self` method argument is splatted, so `Self` should be tupled before typechecking.
638    TupleSplattedSelfArg,
639    /// A non-self argument is splatted, so that argument should be tupled before typechecking.
640    TupleSplattedArg(u8),
641}
642
643impl TupleArgumentsFlag {
644    /// Returns the TupleArgumentsFlag for a known RustCall function.
645    fn rust_fn_trait_call() -> Self {
646        Self::TupleAllCallArgs
647    }
648
649    /// Returns the appropriate TupleArgumentsFlag for the given FnSigKind and method flag.
650    fn with_fn_sig_kind<'tcx>(fn_sig_kind: FnSigKind<'tcx>, is_method: bool) -> Self {
651        if let Some(splatted_arg_index) = fn_sig_kind.splatted() {
652            if is_method {
653                if let Some(splatted_arg_index) = splatted_arg_index.checked_sub(1) {
654                    return Self::TupleSplattedArg(splatted_arg_index);
655                } else {
656                    // In `check_argument_types`, this is effectively `TupleSplattedArg(-1)`
657                    return Self::TupleSplattedSelfArg;
658                }
659            }
660
661            return Self::TupleSplattedArg(splatted_arg_index);
662        }
663
664        Self::DontTupleArguments
665    }
666
667    /// Returns true if the arguments are tupled through "rust-call" or splatting.
668    fn is_tupled(self) -> bool {
669        match self {
670            Self::DontTupleArguments => false,
671            Self::TupleAllCallArgs | Self::TupleSplattedSelfArg | Self::TupleSplattedArg(_) => true,
672        }
673    }
674
675    /// Returns true if the arguments are tupled through splatting.
676    /// (But false if they are "rust-call" or not tupled.)
677    fn is_splatted(self) -> bool {
678        match self {
679            Self::TupleSplattedSelfArg | Self::TupleSplattedArg(_) => true,
680            Self::DontTupleArguments | Self::TupleAllCallArgs => false,
681        }
682    }
683
684    /// Returns the tupled argument index, and whether the `self` argument is splatted.
685    /// Returns `None` if the arguments are not tupled, or if the `self` argument is splatted.
686    fn tupled_arg_index(self) -> (Option<u16>, bool /* is_self_splatted */) {
687        match self {
688            Self::TupleSplattedArg(index) => (Some(u16::from(index)), false),
689            Self::TupleAllCallArgs => (Some(0), false),
690            Self::TupleSplattedSelfArg => (None, true),
691            Self::DontTupleArguments => (None, false),
692        }
693    }
694}
695
696fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
697    let dcx = tcx.dcx();
698    let mut diag = dcx.struct_span_bug(
699        span,
700        "It looks like you're trying to break rust; would you like some ICE?",
701    );
702    diag.note("the compiler expectedly panicked. this is a feature.");
703    diag.note(
704        "we would appreciate a joke overview: \
705         https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
706    );
707    diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc {0} running on {1}",
                tcx.sess.cfg_version, config::host_tuple()))
    })format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_tuple(),));
708    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
709        diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("compiler flags: {0}",
                flags.join(" ")))
    })format!("compiler flags: {}", flags.join(" ")));
710        if excluded_cargo_defaults {
711            diag.note("some of the compiler flags provided by cargo are hidden");
712        }
713    }
714    diag.emit()
715}
716
717/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
718pub fn provide(providers: &mut Providers) {
719    *providers = Providers {
720        method_autoderef_steps: method::probe::method_autoderef_steps,
721        typeck_root,
722        used_trait_imports,
723        check_transmutes: intrinsicck::check_transmutes,
724        check_offloads: intrinsicck::check_offloads,
725        ..*providers
726    };
727}