Skip to main content

rustc_hir_typeck/
lib.rs

1// tidy-alphabetical-start
2#![cfg_attr(bootstrap, feature(assert_matches))]
3#![feature(box_patterns)]
4#![feature(iter_intersperse)]
5#![feature(iter_order_by)]
6#![feature(never_type)]
7#![feature(trim_prefix_suffix)]
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 typeck_root_ctxt;
38mod upvar;
39mod writeback;
40
41pub use coercion::can_coerce;
42use fn_ctxt::FnCtxt;
43use rustc_data_structures::unord::UnordSet;
44use rustc_errors::codes::*;
45use rustc_errors::{Applicability, Diag, ErrorGuaranteed, pluralize, struct_span_code_err};
46use rustc_hir as hir;
47use rustc_hir::def::{DefKind, Res};
48use rustc_hir::{HirId, HirIdMap, Node};
49use rustc_hir_analysis::check::{check_abi, check_custom_abi};
50use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
51use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc};
52use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
53use rustc_middle::query::Providers;
54use rustc_middle::ty::{self, Ty, TyCtxt};
55use rustc_middle::{bug, span_bug};
56use rustc_session::config;
57use rustc_span::Span;
58use rustc_span::def_id::LocalDefId;
59use tracing::{debug, instrument};
60use typeck_root_ctxt::TypeckRootCtxt;
61
62use crate::check::check_fn;
63use crate::coercion::CoerceMany;
64use crate::diverges::Diverges;
65use crate::expectation::Expectation;
66use crate::fn_ctxt::LoweredTy;
67use crate::gather_locals::GatherLocalsVisitor;
68
69#[macro_export]
70macro_rules! type_error_struct {
71    ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({
72        let mut err = rustc_errors::struct_span_code_err!($dcx, $span, $code, $($message)*);
73
74        if $typ.references_error() {
75            err.downgrade_to_delayed_bug();
76        }
77
78        err
79    })
80}
81
82fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> {
83    &tcx.typeck(def_id).used_trait_imports
84}
85
86fn typeck_root<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
87    typeck_with_inspect(tcx, def_id, None)
88}
89
90/// Same as `typeck` but `inspect` is invoked on evaluation of each root obligation.
91/// Inspecting obligations only works with the new trait solver.
92/// This function is *only to be used* by external tools, it should not be
93/// called from within rustc. Note, this is not a query, and thus is not cached.
94pub fn inspect_typeck<'tcx>(
95    tcx: TyCtxt<'tcx>,
96    def_id: LocalDefId,
97    inspect: ObligationInspector<'tcx>,
98) -> &'tcx ty::TypeckResults<'tcx> {
99    // Closures' typeck results come from their outermost function,
100    // as they are part of the same "inference environment".
101    let typeck_root_def_id = tcx.typeck_root_def_id_local(def_id);
102    if typeck_root_def_id != def_id {
103        return tcx.typeck(typeck_root_def_id);
104    }
105
106    typeck_with_inspect(tcx, def_id, Some(inspect))
107}
108
109x;#[instrument(level = "debug", skip(tcx, inspector), ret)]
110fn typeck_with_inspect<'tcx>(
111    tcx: TyCtxt<'tcx>,
112    def_id: LocalDefId,
113    inspector: Option<ObligationInspector<'tcx>>,
114) -> &'tcx ty::TypeckResults<'tcx> {
115    assert!(!tcx.is_typeck_child(def_id.to_def_id()));
116
117    let id = tcx.local_def_id_to_hir_id(def_id);
118    let node = tcx.hir_node(id);
119    let span = tcx.def_span(def_id);
120
121    // Figure out what primary body this item has.
122    let body_id = node.body_id().unwrap_or_else(|| {
123        span_bug!(span, "can't type-check body of {:?}", def_id);
124    });
125    let body = tcx.hir_body(body_id);
126
127    let param_env = tcx.param_env(def_id);
128
129    let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
130    if let Some(inspector) = inspector {
131        root_ctxt.infcx.attach_obligation_inspector(inspector);
132    }
133    let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
134
135    if let hir::Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
136        // Check the fake body of a global ASM. There's not much to do here except
137        // for visit the asm expr of the body.
138        let ty = fcx.check_expr(body.value);
139        fcx.write_ty(id, ty);
140    } else if let Some(hir::FnSig { header, decl, span: fn_sig_span }) = node.fn_sig() {
141        let fn_sig = if decl.output.is_suggestable_infer_ty().is_some() {
142            // In the case that we're recovering `fn() -> W<_>` or some other return
143            // type that has an infer in it, lower the type directly so that it'll
144            // be correctly filled with infer. We'll use this inference to provide
145            // a suggestion later on.
146            fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi, decl, None, None)
147        } else {
148            tcx.fn_sig(def_id).instantiate_identity()
149        };
150
151        check_abi(tcx, id, span, fn_sig.abi());
152        check_custom_abi(tcx, def_id, fn_sig.skip_binder(), *fn_sig_span);
153
154        loops::check(tcx, def_id, body);
155
156        // Compute the function signature from point of view of inside the fn.
157        let mut fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
158
159        // Normalize the input and output types one at a time, using a different
160        // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
161        // on the entire `FnSig`, since this would use the same `WellFormedLoc`
162        // for each type, preventing the HIR wf check from generating
163        // a nice error message.
164        let arg_span =
165            |idx| decl.inputs.get(idx).map_or(decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
166
167        fn_sig.inputs_and_output = tcx.mk_type_list_from_iter(
168            fn_sig
169                .inputs_and_output
170                .iter()
171                .enumerate()
172                .map(|(idx, ty)| fcx.normalize(arg_span(idx), ty)),
173        );
174
175        if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) {
176            naked_functions::typeck_naked_fn(tcx, def_id, body);
177        }
178
179        check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params());
180    } else {
181        let expected_type = if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
182            infer_ty
183        } else if let Some(ty) = node.ty()
184            && ty.is_suggestable_infer_ty()
185        {
186            // In the case that we're recovering `const X: [T; _]` or some other
187            // type that has an infer in it, lower the type directly so that it'll
188            // be correctly filled with infer. We'll use this inference to provide
189            // a suggestion later on.
190            fcx.lowerer().lower_ty(ty)
191        } else {
192            tcx.type_of(def_id).instantiate_identity()
193        };
194
195        loops::check(tcx, def_id, body);
196
197        let expected_type = fcx.normalize(body.value.span, expected_type);
198
199        let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id)));
200        fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code);
201
202        if let hir::Node::AnonConst(_) = node {
203            fcx.require_type_is_sized(
204                expected_type,
205                body.value.span,
206                ObligationCauseCode::SizedConstOrStatic,
207            );
208        }
209
210        fcx.check_expr_coercible_to_type_or_error(body.value, expected_type, None, |err, _| {
211            extend_err_with_const_context(err, tcx, node, expected_type);
212        });
213
214        fcx.write_ty(id, expected_type);
215    };
216
217    // Whether to check repeat exprs before/after inference fallback is somewhat
218    // arbitrary of a decision as neither option is strictly more permissive than
219    // the other. However, we opt to check repeat exprs first as errors from not
220    // having inferred array lengths yet seem less confusing than errors from inference
221    // fallback arbitrarily inferring something incompatible with `Copy` inference
222    // side effects.
223    //
224    // FIXME(#140855): This should also be forwards compatible with moving
225    // repeat expr checks to a custom goal kind or using marker traits in
226    // the future.
227    fcx.check_repeat_exprs();
228
229    // We need to handle opaque types before emitting ambiguity errors as applying
230    // defining uses may guide type inference.
231    if fcx.next_trait_solver() {
232        fcx.try_handle_opaque_type_uses_next();
233    }
234
235    fcx.type_inference_fallback();
236
237    // Even though coercion casts provide type hints, we check casts after fallback for
238    // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
239    fcx.check_casts();
240    fcx.select_obligations_where_possible(|_| {});
241
242    // Closure and coroutine analysis may run after fallback
243    // because they don't constrain other type variables.
244    fcx.closure_analyze(body);
245    assert!(fcx.deferred_call_resolutions.borrow().is_empty());
246
247    for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
248        let ty = fcx.normalize(span, ty);
249        fcx.require_type_is_sized(ty, span, code);
250    }
251
252    fcx.select_obligations_where_possible(|_| {});
253
254    debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
255
256    // We need to handle opaque types before emitting ambiguity errors as applying
257    // defining uses may guide type inference.
258    if fcx.next_trait_solver() {
259        fcx.handle_opaque_type_uses_next();
260    }
261
262    // This must be the last thing before `report_ambiguity_errors` below except `select_obligations_where_possible`.
263    // So don't put anything after this.
264    fcx.drain_stalled_coroutine_obligations();
265    if fcx.infcx.tainted_by_errors().is_none() {
266        fcx.report_ambiguity_errors();
267    }
268
269    fcx.check_asms();
270
271    let typeck_results = fcx.resolve_type_vars_in_body(body);
272
273    fcx.detect_opaque_types_added_during_writeback();
274
275    // Consistency check our TypeckResults instance can hold all ItemLocalIds
276    // it will need to hold.
277    assert_eq!(typeck_results.hir_owner, id.owner);
278
279    typeck_results
280}
281
282fn extend_err_with_const_context(
283    err: &mut Diag<'_>,
284    tcx: TyCtxt<'_>,
285    node: hir::Node<'_>,
286    expected_ty: Ty<'_>,
287) {
288    match node {
289        hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), .. })
290        | hir::Node::TraitItem(hir::TraitItem {
291            kind: hir::TraitItemKind::Const(ty, _, _), ..
292        }) => {
293            // Point at the `Type` in `const NAME: Type = value;`.
294            err.span_label(ty.span, "expected because of the type of the associated constant");
295        }
296        hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
297            // Point at the `Type` in `const NAME: Type = value;`.
298            err.span_label(ty.span, "expected because of the type of the constant");
299        }
300        hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(_, _, ty, _), .. }) => {
301            // Point at the `Type` in `static NAME: Type = value;`.
302            err.span_label(ty.span, "expected because of the type of the static");
303        }
304        hir::Node::AnonConst(anon)
305            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
306                && let hir::Node::Ty(parent) = tcx.parent_hir_node(parent.hir_id)
307                && let hir::TyKind::Array(_ty, _len) = parent.kind =>
308        {
309            // `[type; len]` in type context.
310            err.note("array length can only be `usize`");
311        }
312        hir::Node::AnonConst(anon)
313            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
314                && let hir::Node::Expr(parent) = tcx.parent_hir_node(parent.hir_id)
315                && let hir::ExprKind::Repeat(_ty, _len) = parent.kind =>
316        {
317            // `[type; len]` in expr context.
318            err.note("array length can only be `usize`");
319        }
320        // FIXME: support method calls too.
321        hir::Node::AnonConst(anon)
322            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
323                && let hir::Node::Expr(expr) = tcx.parent_hir_node(parent.hir_id)
324                && let hir::ExprKind::Path(path) = expr.kind
325                && let hir::QPath::Resolved(_, path) = path
326                && let Res::Def(_, def_id) = path.res =>
327        {
328            // `foo<N>()` in expression context, point at `foo`'s const parameter.
329            if let Some(i) =
330                path.segments.iter().last().and_then(|segment| segment.args).and_then(|args| {
331                    args.args.iter().position(|arg| {
332                        #[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)
333                    })
334                })
335            {
336                let generics = tcx.generics_of(def_id);
337                let param = &generics.param_at(i, tcx);
338                let sp = tcx.def_span(param.def_id);
339                err.span_note(sp, "expected because of the type of the const parameter");
340            }
341        }
342        hir::Node::AnonConst(anon)
343            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
344                && let hir::Node::Ty(ty) = tcx.parent_hir_node(parent.hir_id)
345                && let hir::TyKind::Path(path) = ty.kind
346                && let hir::QPath::Resolved(_, path) = path
347                && let Res::Def(_, def_id) = path.res =>
348        {
349            // `Foo<N>` in type context, point at `Foo`'s const parameter.
350            if let Some(i) =
351                path.segments.iter().last().and_then(|segment| segment.args).and_then(|args| {
352                    args.args.iter().position(|arg| {
353                        #[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)
354                    })
355                })
356            {
357                let generics = tcx.generics_of(def_id);
358                let param = &generics.param_at(i, tcx);
359                let sp = tcx.def_span(param.def_id);
360                err.span_note(sp, "expected because of the type of the const parameter");
361            }
362        }
363        hir::Node::AnonConst(anon)
364            if let hir::Node::Variant(_variant) = tcx.parent_hir_node(anon.hir_id) =>
365        {
366            // FIXME: point at `repr` when present in the type.
367            err.note(
368                "enum variant discriminant can only be of a primitive type compatible with the \
369                 enum's `repr`",
370            );
371        }
372        hir::Node::AnonConst(anon)
373            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
374                && let hir::Node::GenericParam(param) = tcx.parent_hir_node(parent.hir_id)
375                && let hir::GenericParamKind::Const { ty, .. } = param.kind =>
376        {
377            // `fn foo<const N: usize = ()>` point at the `usize`.
378            err.span_label(ty.span, "expected because of the type of the const parameter");
379        }
380        hir::Node::AnonConst(anon)
381            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
382                && let hir::Node::TyPat(ty_pat) = tcx.parent_hir_node(parent.hir_id)
383                && let hir::Node::Ty(ty) = tcx.parent_hir_node(ty_pat.hir_id)
384                && let hir::TyKind::Pat(ty, _) = ty.kind =>
385        {
386            // Point at `char` in `pattern_type!(char is 1..=1)`.
387            err.span_label(ty.span, "the pattern must match the type");
388        }
389        hir::Node::AnonConst(anon)
390            if let hir::Node::Field(_) = tcx.parent_hir_node(anon.hir_id)
391                && let ty::Param(_) = expected_ty.kind() =>
392        {
393            err.note(
394                "the type of default fields referencing type parameters can't be assumed inside \
395                 the struct defining them",
396            );
397        }
398        _ => {}
399    }
400}
401
402fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
403    let tcx = fcx.tcx;
404    let def_id = fcx.body_id;
405    let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
406    {
407        if let Some(item) = tcx.opt_associated_item(def_id.into())
408            && let ty::AssocKind::Const { .. } = item.kind
409            && let ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container
410        {
411            let impl_def_id = item.container_id(tcx);
412            let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate_identity();
413            let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
414                tcx,
415                impl_def_id,
416                impl_trait_ref.args,
417            );
418            tcx.check_args_compatible(trait_item_def_id, args)
419                .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args))
420        } else {
421            Some(fcx.next_ty_var(span))
422        }
423    } else if let Node::AnonConst(_) = node {
424        let id = tcx.local_def_id_to_hir_id(def_id);
425        match tcx.parent_hir_node(id) {
426            Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
427            | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
428                asm.operands.iter().find_map(|(op, _op_sp)| match op {
429                    hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
430                        Some(fcx.next_ty_var(span))
431                    }
432                    _ => None,
433                })
434            }
435            _ => None,
436        }
437    } else {
438        None
439    };
440    expected_type
441}
442
443/// When `check_fn` is invoked on a coroutine (i.e., a body that
444/// includes yield), it returns back some information about the yield
445/// points.
446#[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)]
447struct CoroutineTypes<'tcx> {
448    /// Type of coroutine argument / values returned by `yield`.
449    resume_ty: Ty<'tcx>,
450
451    /// Type of value that is yielded.
452    yield_ty: Ty<'tcx>,
453}
454
455#[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)]
456pub enum Needs {
457    MutPlace,
458    None,
459}
460
461impl Needs {
462    fn maybe_mut_place(m: hir::Mutability) -> Self {
463        match m {
464            hir::Mutability::Mut => Needs::MutPlace,
465            hir::Mutability::Not => Needs::None,
466        }
467    }
468}
469
470#[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)]
471pub enum PlaceOp {
472    Deref,
473    Index,
474}
475
476pub struct BreakableCtxt<'tcx> {
477    may_break: bool,
478
479    // this is `null` for loops where break with a value is illegal,
480    // such as `while`, `for`, and `while let`
481    coerce: Option<CoerceMany<'tcx>>,
482}
483
484pub struct EnclosingBreakables<'tcx> {
485    stack: Vec<BreakableCtxt<'tcx>>,
486    by_id: HirIdMap<usize>,
487}
488
489impl<'tcx> EnclosingBreakables<'tcx> {
490    fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
491        self.opt_find_breakable(target_id).unwrap_or_else(|| {
492            ::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);
493        })
494    }
495
496    fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
497        match self.by_id.get(&target_id) {
498            Some(ix) => Some(&mut self.stack[*ix]),
499            None => None,
500        }
501    }
502}
503
504fn report_unexpected_variant_res(
505    tcx: TyCtxt<'_>,
506    res: Res,
507    expr: Option<&hir::Expr<'_>>,
508    qpath: &hir::QPath<'_>,
509    span: Span,
510    err_code: ErrCode,
511    expected: &str,
512) -> ErrorGuaranteed {
513    let res_descr = match res {
514        Res::Def(DefKind::Variant, _) => "struct variant",
515        _ => res.descr(),
516    };
517    let path_str = rustc_hir_pretty::qpath_to_string(&tcx, qpath);
518    let mut err = tcx
519        .dcx()
520        .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}`"))
521        .with_code(err_code);
522    match res {
523        Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
524            let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
525            err.with_span_label(span, "`fn` calls are not allowed in patterns")
526                .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}"))
527        }
528        Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
529            err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"));
530            let variant = tcx.expect_variant_res(res);
531            let sugg = if variant.fields.is_empty() {
532                " {}".to_string()
533            } else {
534                ::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!(
535                    " {{ {} }}",
536                    variant
537                        .fields
538                        .iter()
539                        .map(|f| format!("{}: /* value */", f.name))
540                        .collect::<Vec<_>>()
541                        .join(", ")
542                )
543            };
544            let descr = "you might have meant to create a new value of the struct";
545            let mut suggestion = ::alloc::vec::Vec::new()vec![];
546            match tcx.parent_hir_node(expr.hir_id) {
547                hir::Node::Expr(hir::Expr {
548                    kind: hir::ExprKind::Call(..),
549                    span: call_span,
550                    ..
551                }) => {
552                    suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
553                }
554                hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(..), hir_id, .. }) => {
555                    suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
556                    if let hir::Node::Expr(parent) = tcx.parent_hir_node(*hir_id)
557                        && let hir::ExprKind::If(condition, block, None) = parent.kind
558                        && condition.hir_id == *hir_id
559                        && let hir::ExprKind::Block(block, _) = block.kind
560                        && block.stmts.is_empty()
561                        && let Some(expr) = block.expr
562                        && let hir::ExprKind::Path(..) = expr.kind
563                    {
564                        // Special case: you can incorrectly write an equality condition:
565                        // if foo == Struct { field } { /* if body */ }
566                        // which should have been written
567                        // if foo == (Struct { field }) { /* if body */ }
568                        suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
569                    } else {
570                        suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
571                    }
572                }
573                _ => {
574                    suggestion.push((span.shrink_to_hi(), sugg));
575                }
576            }
577
578            err.multipart_suggestion(descr, suggestion, Applicability::HasPlaceholders);
579            err
580        }
581        Res::Def(DefKind::Variant, _) if expr.is_none() => {
582            err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"));
583
584            let fields = &tcx.expect_variant_res(res).fields.raw;
585            let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
586            let (msg, sugg) = if fields.is_empty() {
587                ("use the struct variant pattern syntax".to_string(), " {}".to_string())
588            } else {
589                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the struct variant\'s field{0} {1} being ignored",
                if fields.len() == 1 { "" } else { "s" },
                if fields.len() == 1 { "is" } else { "are" }))
    })format!(
590                    "the struct variant's field{s} {are} being ignored",
591                    s = pluralize!(fields.len()),
592                    are = pluralize!("is", fields.len())
593                );
594                let fields = fields
595                    .iter()
596                    .map(|field| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: _", field.ident(tcx)))
    })format!("{}: _", field.ident(tcx)))
597                    .collect::<Vec<_>>()
598                    .join(", ");
599                let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0} }}", fields))
    })format!(" {{ {} }}", fields);
600                (msg, sugg)
601            };
602
603            err.span_suggestion_verbose(
604                qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
605                msg,
606                sugg,
607                Applicability::HasPlaceholders,
608            );
609            err
610        }
611        _ => err.with_span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}")),
612    }
613    .emit()
614}
615
616/// Controls whether the arguments are tupled. This is used for the call
617/// operator.
618///
619/// Tupling means that all call-side arguments are packed into a tuple and
620/// passed as a single parameter. For example, if tupling is enabled, this
621/// function:
622/// ```
623/// fn f(x: (isize, isize)) {}
624/// ```
625/// Can be called as:
626/// ```ignore UNSOLVED (can this be done in user code?)
627/// # fn f(x: (isize, isize)) {}
628/// f(1, 2);
629/// ```
630/// Instead of:
631/// ```
632/// # fn f(x: (isize, isize)) {}
633/// f((1, 2));
634/// ```
635#[derive(#[automatically_derived]
impl ::core::marker::Copy for TupleArgumentsFlag { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TupleArgumentsFlag {
    #[inline]
    fn clone(&self) -> TupleArgumentsFlag { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for TupleArgumentsFlag {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}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
    }
}PartialEq)]
636enum TupleArgumentsFlag {
637    DontTupleArguments,
638    TupleArguments,
639}
640
641fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
642    let dcx = tcx.dcx();
643    let mut diag = dcx.struct_span_bug(
644        span,
645        "It looks like you're trying to break rust; would you like some ICE?",
646    );
647    diag.note("the compiler expectedly panicked. this is a feature.");
648    diag.note(
649        "we would appreciate a joke overview: \
650         https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
651    );
652    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(),));
653    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
654        diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("compiler flags: {0}",
                flags.join(" ")))
    })format!("compiler flags: {}", flags.join(" ")));
655        if excluded_cargo_defaults {
656            diag.note("some of the compiler flags provided by cargo are hidden");
657        }
658    }
659    diag.emit()
660}
661
662/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
663pub fn provide(providers: &mut Providers) {
664    *providers = Providers {
665        method_autoderef_steps: method::probe::method_autoderef_steps,
666        typeck_root,
667        used_trait_imports,
668        check_transmutes: intrinsicck::check_transmutes,
669        ..*providers
670    };
671}