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