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(option_into_flat_iter)]
6#![feature(option_reference_flattening)]
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, 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;
49use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
50use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, TraitEngine, WellFormedLoc};
51use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
52use rustc_middle::query::Providers;
53use rustc_middle::ty::{self, FnSigKind, Ty, TyCtxt, Unnormalized};
54use rustc_session::config;
55use rustc_span::def_id::LocalDefId;
56use rustc_span::{Span, bug, span_bug};
57use tracing::{debug, instrument};
58use typeck_root_ctxt::TypeckRootCtxt;
59
60use crate::check::check_fn;
61use crate::coercion::CoerceMany;
62use crate::diverges::Diverges;
63use crate::expectation::Expectation;
64use crate::fn_ctxt::LoweredTy;
65use crate::gather_locals::GatherLocalsVisitor;
66
67#[macro_export]
68macro_rules! type_error_struct {
69    ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({
70        let mut err = rustc_errors::struct_span_code_err!($dcx, $span, $code, $($message)*);
71
72        if $typ.references_error() {
73            err.downgrade_to_delayed_bug();
74        }
75
76        err
77    })
78}
79
80fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> {
81    &tcx.typeck(def_id).used_trait_imports
82}
83
84fn typeck_root<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
85    typeck_with_inspect(tcx, def_id, None)
86}
87
88/// Same as `typeck` but `inspect` is invoked on evaluation of each root obligation.
89/// Inspecting obligations only works with the new trait solver.
90/// This function is *only to be used* by external tools, it should not be
91/// called from within rustc. Note, this is not a query, and thus is not cached.
92pub fn inspect_typeck<'tcx>(
93    tcx: TyCtxt<'tcx>,
94    def_id: LocalDefId,
95    inspect: ObligationInspector<'tcx>,
96) -> &'tcx ty::TypeckResults<'tcx> {
97    // Closures' typeck results come from their outermost function,
98    // as they are part of the same "inference environment".
99    let typeck_root_def_id = tcx.typeck_root_def_id_local(def_id);
100    if typeck_root_def_id != def_id {
101        return tcx.typeck(typeck_root_def_id);
102    }
103
104    typeck_with_inspect(tcx, def_id, Some(inspect))
105}
106
107{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("typeck_with_inspect",
                                "rustc_hir_typeck", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_hir_typeck/src/lib.rs"),
                                ::tracing_core::__macro_support::Option::Some(107u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                &'tcx ty::TypeckResults<'tcx> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if !!tcx.is_typeck_child(def_id.to_def_id()) {
                            ::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def_id.to_def_id())")
                        };
                        let id = tcx.local_def_id_to_hir_id(def_id);
                        let node = tcx.hir_node(id);
                        let span = tcx.def_span(def_id);
                        let body_id =
                            node.body_id().unwrap_or_else(||
                                    {
                                        ::rustc_span::macros::bug_impl(Some(span),
                                            format_args!("can\'t type-check body of {0:?}", def_id),
                                            Location::caller());
                                    });
                        let body = tcx.hir_body(body_id);
                        let param_env = tcx.param_env(def_id);
                        let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
                        if let Some(inspector) = inspector {
                            root_ctxt.infcx.attach_obligation_inspector(inspector);
                        }
                        let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
                        if let hir::Node::Item(hir::Item {
                                kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
                            let ty = fcx.check_expr(body.value);
                            fcx.write_ty(id, ty);
                        } else if let Some(hir::FnSig { header, decl, span: _ }) =
                                node.fn_sig() {
                            let fn_sig =
                                if decl.output.is_suggestable_infer_ty().is_some() {
                                    fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi,
                                        decl, None, None)
                                } else {
                                    tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip()
                                };
                            check_abi(tcx, id, span, fn_sig.abi());
                            loops::check(tcx, def_id, body);
                            let mut fn_sig =
                                tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
                            let arg_span =
                                |idx|
                                    decl.inputs.get(idx).map_or(decl.output.span(),
                                        |arg: &hir::Ty<'_>| arg.span);
                            fn_sig.inputs_and_output =
                                tcx.mk_type_list_from_iter(fn_sig.inputs().iter().enumerate().map(|(idx,
                                                    ty)|
                                                fcx.normalize(arg_span(idx),
                                                    Unnormalized::new_wip(*ty))).chain([fcx.normalize_with_cause(decl.output.span(),
                                                    Unnormalized::new_wip(fn_sig.output()),
                                                    ObligationCauseCode::ReturnType)]));
                            if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED)
                                {
                                naked_functions::typeck_naked_fn(tcx, def_id, body);
                            }
                            check_fn(&mut fcx, fn_sig, None, decl, def_id, body,
                                tcx.features().unsized_fn_params());
                        } else {
                            let expected_type =
                                if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
                                    infer_ty
                                } else if let Some(ty) = node.ty() &&
                                        ty.is_suggestable_infer_ty() {
                                    fcx.lowerer().lower_ty(ty)
                                } else {
                                    tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
                                };
                            loops::check(tcx, def_id, body);
                            let expected_type =
                                fcx.normalize_with_cause(body.value.span,
                                    Unnormalized::new_wip(expected_type),
                                    ObligationCauseCode::BlockTailExpression(body.value.hir_id,
                                        hir::MatchSource::Normal));
                            let wf_code =
                                ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id));
                            fcx.register_wf_obligation(expected_type.into(),
                                body.value.span, wf_code);
                            if let hir::Node::AnonConst(_) = node {
                                fcx.require_type_is_sized(expected_type, body.value.span,
                                    ObligationCauseCode::SizedConstOrStatic);
                            }
                            fcx.check_expr_coercible_to_type_or_error(body.value,
                                expected_type, None,
                                |err, _|
                                    {
                                        extend_err_with_const_context(err, tcx, node,
                                            expected_type);
                                    });
                            fcx.write_ty(id, expected_type);
                        };
                        fcx.check_repeat_exprs();
                        if fcx.next_trait_solver() {
                            fcx.try_handle_opaque_type_uses_next();
                        }
                        fcx.type_inference_fallback();
                        fcx.check_casts();
                        fcx.select_obligations_where_possible(|_| {});
                        fcx.closure_analyze(body);
                        if !fcx.deferred_call_resolutions.borrow().is_empty() {
                            ::core::panicking::panic("assertion failed: fcx.deferred_call_resolutions.borrow().is_empty()")
                        };
                        for (ty, span, code) in
                            fcx.deferred_sized_obligations.borrow_mut().drain(..) {
                            let ty = fcx.normalize(span, Unnormalized::new_wip(ty));
                            fcx.require_type_is_sized(ty, span, code);
                        }
                        fcx.select_obligations_where_possible(|_| {});
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_hir_typeck/src/lib.rs:260",
                                                "rustc_hir_typeck", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_hir_typeck/src/lib.rs"),
                                                ::tracing_core::__macro_support::Option::Some(260u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("pending_obligations")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("pending_obligations");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fcx.fulfillment_cx.borrow().pending_obligations())
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        if fcx.next_trait_solver() {
                            fcx.handle_opaque_type_uses_next();
                        }
                        fcx.drain_stalled_coroutine_obligations();
                        if fcx.infcx.tainted_by_errors().is_none() {
                            fcx.report_ambiguity_errors();
                        }
                        fcx.check_asms();
                        let typeck_results = fcx.resolve_type_vars_in_body(body);
                        fcx.detect_opaque_types_added_during_writeback();
                        {
                            match (&typeck_results.hir_owner, &id.owner) {
                                (left_val, right_val) => {
                                    if !(*left_val == *right_val) {
                                        let kind = ::core::panicking::AssertKind::Eq;
                                        ::core::panicking::assert_failed(kind, &*left_val,
                                            &*right_val, ::core::option::Option::None);
                                    }
                                }
                            }
                        };
                        typeck_results
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_hir_typeck/src/lib.rs:107",
                        "rustc_hir_typeck", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_hir_typeck/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(107u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx, inspector), ret)]
108fn typeck_with_inspect<'tcx>(
109    tcx: TyCtxt<'tcx>,
110    def_id: LocalDefId,
111    inspector: Option<ObligationInspector<'tcx>>,
112) -> &'tcx ty::TypeckResults<'tcx> {
113    assert!(!tcx.is_typeck_child(def_id.to_def_id()));
114
115    let id = tcx.local_def_id_to_hir_id(def_id);
116    let node = tcx.hir_node(id);
117    let span = tcx.def_span(def_id);
118
119    // Figure out what primary body this item has.
120    let body_id = node.body_id().unwrap_or_else(|| {
121        span_bug!(span, "can't type-check body of {:?}", def_id);
122    });
123    let body = tcx.hir_body(body_id);
124
125    let param_env = tcx.param_env(def_id);
126
127    let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
128    if let Some(inspector) = inspector {
129        root_ctxt.infcx.attach_obligation_inspector(inspector);
130    }
131    let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
132
133    if let hir::Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
134        // Check the fake body of a global ASM. There's not much to do here except
135        // for visit the asm expr of the body.
136        let ty = fcx.check_expr(body.value);
137        fcx.write_ty(id, ty);
138    } else if let Some(hir::FnSig { header, decl, span: _ }) = node.fn_sig() {
139        let fn_sig = if decl.output.is_suggestable_infer_ty().is_some() {
140            // In the case that we're recovering `fn() -> W<_>` or some other return
141            // type that has an infer in it, lower the type directly so that it'll
142            // be correctly filled with infer. We'll use this inference to provide
143            // a suggestion later on.
144            fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi, decl, None, None)
145        } else {
146            tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip()
147        };
148
149        check_abi(tcx, id, span, fn_sig.abi());
150
151        loops::check(tcx, def_id, body);
152
153        // Compute the function signature from point of view of inside the fn.
154        let mut fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
155
156        // Normalize the input and output types one at a time, using a different
157        // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
158        // on the entire `FnSig`, since this would use the same `WellFormedLoc`
159        // for each type, preventing the HIR wf check from generating
160        // a nice error message.
161        let arg_span =
162            |idx| decl.inputs.get(idx).map_or(decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
163
164        fn_sig.inputs_and_output = tcx.mk_type_list_from_iter(
165            fn_sig
166                .inputs()
167                .iter()
168                .enumerate()
169                .map(|(idx, ty)| fcx.normalize(arg_span(idx), Unnormalized::new_wip(*ty)))
170                .chain([fcx.normalize_with_cause(
171                    decl.output.span(),
172                    Unnormalized::new_wip(fn_sig.output()),
173                    ObligationCauseCode::ReturnType,
174                )]),
175        );
176
177        if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) {
178            naked_functions::typeck_naked_fn(tcx, def_id, body);
179        }
180
181        check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params());
182    } else {
183        let expected_type = if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
184            infer_ty
185        } else if let Some(ty) = node.ty()
186            && ty.is_suggestable_infer_ty()
187        {
188            // In the case that we're recovering `const X: [T; _]` or some other
189            // type that has an infer in it, lower the type directly so that it'll
190            // be correctly filled with infer. We'll use this inference to provide
191            // a suggestion later on.
192            fcx.lowerer().lower_ty(ty)
193        } else {
194            tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
195        };
196
197        loops::check(tcx, def_id, body);
198
199        let expected_type = fcx.normalize_with_cause(
200            body.value.span,
201            Unnormalized::new_wip(expected_type),
202            ObligationCauseCode::BlockTailExpression(body.value.hir_id, hir::MatchSource::Normal),
203        );
204
205        let wf_code = ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id));
206        fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code);
207
208        if let hir::Node::AnonConst(_) = node {
209            fcx.require_type_is_sized(
210                expected_type,
211                body.value.span,
212                ObligationCauseCode::SizedConstOrStatic,
213            );
214        }
215
216        fcx.check_expr_coercible_to_type_or_error(body.value, expected_type, None, |err, _| {
217            extend_err_with_const_context(err, tcx, node, expected_type);
218        });
219
220        fcx.write_ty(id, expected_type);
221    };
222
223    // Whether to check repeat exprs before/after inference fallback is somewhat
224    // arbitrary of a decision as neither option is strictly more permissive than
225    // the other. However, we opt to check repeat exprs first as errors from not
226    // having inferred array lengths yet seem less confusing than errors from inference
227    // fallback arbitrarily inferring something incompatible with `Copy` inference
228    // side effects.
229    //
230    // FIXME(#140855): This should also be forwards compatible with moving
231    // repeat expr checks to a custom goal kind or using marker traits in
232    // the future.
233    fcx.check_repeat_exprs();
234
235    // We need to handle opaque types before emitting ambiguity errors as applying
236    // defining uses may guide type inference.
237    if fcx.next_trait_solver() {
238        fcx.try_handle_opaque_type_uses_next();
239    }
240
241    fcx.type_inference_fallback();
242
243    // Even though coercion casts provide type hints, we check casts after fallback for
244    // backwards compatibility. This makes fallback a stronger type hint than a cast coercion.
245    fcx.check_casts();
246    fcx.select_obligations_where_possible(|_| {});
247
248    // Closure and coroutine analysis may run after fallback
249    // because they don't constrain other type variables.
250    fcx.closure_analyze(body);
251    assert!(fcx.deferred_call_resolutions.borrow().is_empty());
252
253    for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
254        let ty = fcx.normalize(span, Unnormalized::new_wip(ty));
255        fcx.require_type_is_sized(ty, span, code);
256    }
257
258    fcx.select_obligations_where_possible(|_| {});
259
260    debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
261
262    // We need to handle opaque types before emitting ambiguity errors as applying
263    // defining uses may guide type inference.
264    if fcx.next_trait_solver() {
265        fcx.handle_opaque_type_uses_next();
266    }
267
268    // This must be the last thing before `report_ambiguity_errors` below except `select_obligations_where_possible`.
269    // So don't put anything after this.
270    fcx.drain_stalled_coroutine_obligations();
271    if fcx.infcx.tainted_by_errors().is_none() {
272        fcx.report_ambiguity_errors();
273    }
274
275    fcx.check_asms();
276
277    let typeck_results = fcx.resolve_type_vars_in_body(body);
278
279    fcx.detect_opaque_types_added_during_writeback();
280
281    // Consistency check our TypeckResults instance can hold all ItemLocalIds
282    // it will need to hold.
283    assert_eq!(typeck_results.hir_owner, id.owner);
284
285    typeck_results
286}
287
288fn extend_err_with_const_context(
289    err: &mut Diag<'_>,
290    tcx: TyCtxt<'_>,
291    node: hir::Node<'_>,
292    expected_ty: Ty<'_>,
293) {
294    match node {
295        hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), .. })
296        | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::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 associated constant");
299        }
300        hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
301            // Point at the `Type` in `const NAME: Type = value;`.
302            err.span_label(ty.span, "expected because of the type of the constant");
303        }
304        hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(_, _, ty, _), .. }) => {
305            // Point at the `Type` in `static NAME: Type = value;`.
306            err.span_label(ty.span, "expected because of the type of the static");
307        }
308        hir::Node::AnonConst(anon)
309            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
310                && let hir::Node::Ty(parent) = tcx.parent_hir_node(parent.hir_id)
311                && let hir::TyKind::Array(_ty, _len) = parent.kind =>
312        {
313            // `[type; len]` in type context.
314            err.note("array length can only be `usize`");
315        }
316        hir::Node::AnonConst(anon)
317            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
318                && let hir::Node::Expr(parent) = tcx.parent_hir_node(parent.hir_id)
319                && let hir::ExprKind::Repeat(_ty, _len) = parent.kind =>
320        {
321            // `[type; len]` in expr context.
322            err.note("array length can only be `usize`");
323        }
324        // FIXME: support method calls too.
325        hir::Node::AnonConst(anon)
326            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
327                && let Some(path) = tcx.parent_hir_node(parent.hir_id).path()
328                && let hir::QPath::Resolved(_, path) = path
329                && let Res::Def(_, def_id) = path.res =>
330        {
331            // `foo<N>()`, point at the const parameter in the definition of `foo`.
332            if let Some(i) =
333                path.segments.last().and_then(|segment| segment.args).and_then(|args| {
334                    args.args.iter().position(|arg| {
335                        #[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)
336                    })
337                })
338            {
339                let generics = tcx.generics_of(def_id);
340                let param = &generics.param_at(i, tcx);
341                let sp = tcx.def_span(param.def_id);
342                err.span_note(sp, "expected because of the type of the const parameter");
343            }
344        }
345        hir::Node::AnonConst(anon)
346            if let hir::Node::Variant(_variant) = tcx.parent_hir_node(anon.hir_id) =>
347        {
348            // FIXME: point at `repr` when present in the type.
349            err.note(
350                "enum variant discriminant can only be of a primitive type compatible with the \
351                 enum's `repr`",
352            );
353        }
354        hir::Node::AnonConst(anon)
355            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
356                && let hir::Node::GenericParam(param) = tcx.parent_hir_node(parent.hir_id)
357                && let hir::GenericParamKind::Const { ty, .. } = param.kind =>
358        {
359            // `fn foo<const N: usize = ()>` point at the `usize`.
360            err.span_label(ty.span, "expected because of the type of the const parameter");
361        }
362        hir::Node::AnonConst(anon)
363            if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
364                && let hir::Node::TyPat(ty_pat) = tcx.parent_hir_node(parent.hir_id)
365                && let hir::Node::Ty(ty) = tcx.parent_hir_node(ty_pat.hir_id)
366                && let hir::TyKind::Pat(ty, _) = ty.kind =>
367        {
368            // Point at `char` in `pattern_type!(char is 1..=1)`.
369            err.span_label(ty.span, "the pattern must match the type");
370        }
371        hir::Node::AnonConst(anon)
372            if let hir::Node::Field(_) = tcx.parent_hir_node(anon.hir_id)
373                && let ty::Param(_) = expected_ty.kind() =>
374        {
375            err.note(
376                "the type of default fields referencing type parameters can't be assumed inside \
377                 the struct defining them",
378            );
379        }
380        _ => {}
381    }
382}
383
384fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
385    let tcx = fcx.tcx;
386    let def_id = fcx.body_def_id;
387    let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
388    {
389        if let Some(item) = tcx.opt_associated_item(def_id.into())
390            && let ty::AssocKind::Const { .. } = item.kind
391            && let ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container
392        {
393            let impl_def_id = item.container_id(tcx);
394            let impl_trait_ref =
395                tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
396            let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
397                tcx,
398                impl_def_id,
399                impl_trait_ref.args,
400            );
401            let alias_kind = ty::AliasTermKind::ProjectionConst { def_id: trait_item_def_id };
402            tcx.check_alias_term_args_compatible(alias_kind, args)
403                .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args).skip_norm_wip())
404        } else {
405            Some(fcx.next_ty_var(span))
406        }
407    } else if let Node::AnonConst(_) = node {
408        let id = tcx.local_def_id_to_hir_id(def_id);
409        match tcx.parent_hir_node(id) {
410            Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
411            | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
412                asm.operands.iter().find_map(|(op, _op_sp)| match op {
413                    hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
414                        Some(fcx.next_ty_var(span))
415                    }
416                    _ => None,
417                })
418            }
419            _ => None,
420        }
421    } else {
422        None
423    };
424    expected_type
425}
426
427/// When `check_fn` is invoked on a coroutine (i.e., a body that
428/// includes yield), it returns back some information about the yield
429/// points.
430#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for CoroutineTypes<'tcx>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "CoroutineTypes resume_ty yield_ty", &self.resume_ty,
            &&self.yield_ty)
    }
}Debug, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    CoroutineTypes<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for
    CoroutineTypes<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> 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]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for CoroutineTypes<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    CoroutineTypes<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone)]
431struct CoroutineTypes<'tcx> {
432    /// Type of coroutine argument / values returned by `yield`.
433    resume_ty: Ty<'tcx>,
434
435    /// Type of value that is yielded.
436    yield_ty: Ty<'tcx>,
437}
438
439#[derive(#[automatically_derived]impl ::core::marker::Copy for Needs { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Needs {
}
#[automatically_derived]impl ::core::clone::Clone for Needs {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Needs {
    #[inline]
    #[rustc_trivial_field_reads]
    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::marker::StructuralPartialEq for Needs { }
#[automatically_derived]impl ::core::cmp::PartialEq for Needs {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Needs { }Eq)]
440pub enum Needs {
441    MutPlace,
442    None,
443}
444
445impl Needs {
446    fn maybe_mut_place(m: hir::Mutability) -> Self {
447        match m {
448            hir::Mutability::Mut => Needs::MutPlace,
449            hir::Mutability::Not => Needs::None,
450        }
451    }
452}
453
454#[derive(#[automatically_derived]impl ::core::fmt::Debug for PlaceOp {
    #[inline]
    #[rustc_trivial_field_reads]
    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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PlaceOp {
}
#[automatically_derived]impl ::core::clone::Clone for PlaceOp {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
455pub enum PlaceOp {
456    Deref,
457    Index,
458}
459
460pub struct BreakableCtxt<'tcx> {
461    may_break: bool,
462
463    // this is `null` for loops where break with a value is illegal,
464    // such as `while`, `for`, and `while let`
465    coerce: Option<CoerceMany<'tcx>>,
466}
467
468pub struct EnclosingBreakables<'tcx> {
469    stack: Vec<BreakableCtxt<'tcx>>,
470    by_id: HirIdMap<usize>,
471}
472
473impl<'tcx> EnclosingBreakables<'tcx> {
474    fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
475        self.opt_find_breakable(target_id).unwrap_or_else(|| {
476            ::rustc_span::macros::bug_impl(None,
    format_args!("could not find enclosing breakable with id {0}", target_id),
    Location::caller());bug!("could not find enclosing breakable with id {}", target_id);
477        })
478    }
479
480    fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
481        match self.by_id.get(&target_id) {
482            Some(ix) => Some(&mut self.stack[*ix]),
483            None => None,
484        }
485    }
486}
487impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
488    fn report_unexpected_variant_res(
489        &self,
490        res: Res,
491        expr: Option<&hir::Expr<'_>>,
492        sub_pats: &[hir::Pat<'_>],
493        qpath: &hir::QPath<'_>,
494        span: Span,
495        err_code: ErrCode,
496        expected: &str,
497    ) -> ErrorGuaranteed {
498        let tcx = self.tcx;
499        let res_descr = match res {
500            Res::Def(DefKind::Variant, _) => "struct variant",
501            _ => res.descr(),
502        };
503        let path_str = rustc_hir_pretty::qpath_to_string(self, qpath);
504        let mut err = tcx
505            .dcx()
506            .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}`"))
507            .with_code(err_code);
508        match res {
509            Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
510                let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
511                err.with_span_label(span, "`fn` calls are not allowed in patterns")
512                    .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}"))
513            }
514            Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
515                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"));
516                let variant = tcx.expect_variant_res(res);
517                let sugg = if variant.fields.is_empty() {
518                    " {}".to_string()
519                } else {
520                    ::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!(
521                        " {{ {} }}",
522                        variant
523                            .fields
524                            .iter()
525                            .map(|f| format!("{}: /* value */", f.name))
526                            .collect::<Vec<_>>()
527                            .join(", ")
528                    )
529                };
530                let descr = "you might have meant to create a new value of the struct";
531                let mut suggestion = ::alloc::vec::Vec::new()vec![];
532                match tcx.parent_hir_node(expr.hir_id) {
533                    hir::Node::Expr(hir::Expr {
534                        kind: hir::ExprKind::Call(..),
535                        span: call_span,
536                        ..
537                    }) => {
538                        suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
539                    }
540                    hir::Node::Expr(hir::Expr {
541                        kind: hir::ExprKind::Binary(..), hir_id, ..
542                    }) => {
543                        suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
544                        if let hir::Node::Expr(parent) = tcx.parent_hir_node(*hir_id)
545                            && let hir::ExprKind::If(condition, block, None) = parent.kind
546                            && condition.hir_id == *hir_id
547                            && let hir::ExprKind::Block(block, _) = block.kind
548                            && block.stmts.is_empty()
549                            && let Some(expr) = block.expr
550                            && let hir::ExprKind::Path(..) = expr.kind
551                        {
552                            // Special case: you can incorrectly write an equality condition:
553                            // if foo == Struct { field } { /* if body */ }
554                            // which should have been written
555                            // if foo == (Struct { field }) { /* if body */ }
556                            suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
557                        } else {
558                            suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
559                        }
560                    }
561                    _ => {
562                        suggestion.push((span.shrink_to_hi(), sugg));
563                    }
564                }
565
566                err.multipart_suggestion(descr, suggestion, Applicability::HasPlaceholders);
567                err
568            }
569            Res::Def(DefKind::Variant, _) if expr.is_none() => {
570                err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"));
571
572                let fields = &tcx.expect_variant_res(res).fields.raw;
573                let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
574                let (msg, sugg) = if fields.is_empty() {
575                    ("use the struct variant pattern syntax", " {}".to_string())
576                } else {
577                    let msg = if fields.is_empty() {
578                        "use struct variant pattern syntax"
579                    } else {
580                        "add the names to match a struct variant's fields"
581                    };
582                    let fields_sugg = fields
583                        .iter()
584                        .enumerate()
585                        .map(|(i, field)| {
586                            let field_name = field.ident(tcx).to_string();
587
588                            let pat_snippet = sub_pats
589                                .get(i)
590                                .and_then(|sub_pat| {
591                                    tcx.sess.source_map().span_to_snippet(sub_pat.span).ok()
592                                })
593                                .unwrap_or_else(|| "_".to_string());
594
595                            if field_name == pat_snippet {
596                                field_name
597                            } else {
598                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", field_name,
                pat_snippet))
    })format!("{field_name}: {pat_snippet}")
599                            }
600                        })
601                        .collect::<Vec<_>>()
602                        .join(", ");
603                    let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{ {0} }}", fields_sugg))
    })format!(" {{ {} }}", fields_sugg);
604                    (msg, sugg)
605                };
606
607                err.span_suggestion_verbose(
608                    qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
609                    msg,
610                    sugg,
611                    Applicability::HasPlaceholders,
612                );
613                err
614            }
615            _ => err.with_span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}")),
616        }
617        .emit_err()
618    }
619}
620
621/// Controls whether all arguments are tupled. This is used for the call operator only.
622///
623/// Tupling means that all call-side arguments are packed into a tuple and passed as a single
624/// parameter. For example, if tupling is enabled, this function:
625/// ```
626/// fn f(x: (isize, isize)) {}
627/// ```
628/// Can be called as:
629/// ```ignore UNSOLVED (can this be done in user code?)
630/// # fn f(x: (isize, isize)) {}
631/// f(1, 2);
632/// ```
633/// Instead of:
634/// ```
635/// # fn f(x: (isize, isize)) {}
636/// f((1, 2));
637/// ```
638///
639/// Note: splatted arguments are handled separately.
640#[derive(#[automatically_derived]impl ::core::marker::Copy for TupleArgumentsFlag { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TupleArgumentsFlag {
}
#[automatically_derived]impl ::core::clone::Clone for TupleArgumentsFlag {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u8>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TupleArgumentsFlag {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::DontTupleArguments =>
                ::core::fmt::Formatter::write_str(f, "DontTupleArguments"),
            Self::TupleAllCallArgs =>
                ::core::fmt::Formatter::write_str(f, "TupleAllCallArgs"),
            Self::TupleSplattedSelfArg =>
                ::core::fmt::Formatter::write_str(f, "TupleSplattedSelfArg"),
            Self::TupleSplattedArg(__self_0) =>
                ::core::fmt::Formatter::debug_struct_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::marker::StructuralPartialEq for
    TupleArgumentsFlag {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TupleArgumentsFlag {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::TupleSplattedArg(__self_0),
                    Self::TupleSplattedArg(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
641enum TupleArgumentsFlag {
642    /// Arguments are typechecked unchanged.
643    DontTupleArguments,
644    /// This is a call operator: all caller arguments are tupled before typechecking.
645    /// Set based on the "rust-call" ABI and Fn* traits.
646    TupleAllCallArgs,
647    /// The `self` method argument is splatted, so `Self` should be tupled before typechecking.
648    TupleSplattedSelfArg,
649    /// A non-self argument is splatted, so that argument should be tupled before typechecking.
650    TupleSplattedArg(u8),
651}
652
653impl TupleArgumentsFlag {
654    /// Returns the TupleArgumentsFlag for a known RustCall function.
655    fn rust_fn_trait_call() -> Self {
656        Self::TupleAllCallArgs
657    }
658
659    /// Returns the appropriate TupleArgumentsFlag for the given FnSigKind and method flag.
660    fn with_fn_sig_kind<'tcx>(fn_sig_kind: FnSigKind<'tcx>, is_method: bool) -> Self {
661        if let Some(splatted_arg_index) = fn_sig_kind.splatted() {
662            if is_method {
663                if let Some(splatted_arg_index) = splatted_arg_index.checked_sub(1) {
664                    return Self::TupleSplattedArg(splatted_arg_index);
665                } else {
666                    // In `check_argument_types`, this is effectively `TupleSplattedArg(-1)`
667                    return Self::TupleSplattedSelfArg;
668                }
669            }
670
671            return Self::TupleSplattedArg(splatted_arg_index);
672        }
673
674        Self::DontTupleArguments
675    }
676
677    /// Returns true if the arguments are tupled through "rust-call" or splatting.
678    fn is_tupled(self) -> bool {
679        match self {
680            Self::DontTupleArguments => false,
681            Self::TupleAllCallArgs | Self::TupleSplattedSelfArg | Self::TupleSplattedArg(_) => true,
682        }
683    }
684
685    /// Returns true if the arguments are tupled through splatting.
686    /// (But false if they are "rust-call" or not tupled.)
687    fn is_splatted(self) -> bool {
688        match self {
689            Self::TupleSplattedSelfArg | Self::TupleSplattedArg(_) => true,
690            Self::DontTupleArguments | Self::TupleAllCallArgs => false,
691        }
692    }
693
694    /// Returns the tupled argument index, and whether the `self` argument is splatted.
695    /// Returns `None` if the arguments are not tupled, or if the `self` argument is splatted.
696    fn tupled_arg_index(self) -> (Option<u16>, bool /* is_self_splatted */) {
697        match self {
698            Self::TupleSplattedArg(index) => (Some(u16::from(index)), false),
699            Self::TupleAllCallArgs => (Some(0), false),
700            Self::TupleSplattedSelfArg => (None, true),
701            Self::DontTupleArguments => (None, false),
702        }
703    }
704}
705
706fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
707    let dcx = tcx.dcx();
708    let mut diag = dcx.struct_span_bug(
709        span,
710        "It looks like you're trying to break rust; would you like some ICE?",
711    );
712    diag.note("the compiler expectedly panicked. this is a feature.");
713    diag.note(
714        "we would appreciate a joke overview: \
715         https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
716    );
717    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(),));
718    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
719        diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("compiler flags: {0}",
                flags.join(" ")))
    })format!("compiler flags: {}", flags.join(" ")));
720        if excluded_cargo_defaults {
721            diag.note("some of the compiler flags provided by cargo are hidden");
722        }
723    }
724    diag.emit_bug()
725}
726
727/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
728pub fn provide(providers: &mut Providers) {
729    *providers = Providers {
730        method_autoderef_steps: method::probe::method_autoderef_steps,
731        typeck_root,
732        used_trait_imports,
733        check_transmutes: intrinsicck::check_transmutes,
734        check_offloads: intrinsicck::check_offloads,
735        ..*providers
736    };
737}