flux_rustc_bridge/
lowering.rs

1use std::rc::Rc;
2
3use flux_arc_interner::List;
4use flux_common::result::ResultExt;
5use flux_errors::FluxSession;
6use itertools::Itertools;
7use rustc_borrowck::consumers::BodyWithBorrowckFacts;
8use rustc_errors::ErrorGuaranteed;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_infer::{
11    infer::{InferCtxt, TyCtxtInferExt},
12    traits::Obligation,
13};
14use rustc_macros::{Decodable, Encodable};
15use rustc_middle::{
16    mir::{self as rustc_mir},
17    traits::{ImplSource, ObligationCause},
18    ty::{
19        self as rustc_ty, GenericArgKind, ParamConst, ParamEnv, TyCtxt, TypingMode,
20        adjustment as rustc_adjustment,
21    },
22};
23use rustc_span::Span;
24use rustc_trait_selection::traits::SelectionContext;
25
26use super::{
27    mir::{
28        AggregateKind, AssertKind, BasicBlockData, BinOp, Body, CallArgs, CastKind, LocalDecl,
29        NonDivergingIntrinsic, Operand, Place, PlaceElem, PointerCast, Rvalue, Statement,
30        StatementKind, Terminator, TerminatorKind,
31    },
32    ty::{
33        AdtDef, AdtDefData, AliasKind, Binder, BoundRegion, BoundVariableKind, Clause, ClauseKind,
34        Const, ConstKind, ExistentialPredicate, ExistentialProjection, FieldDef, FnSig, GenericArg,
35        GenericParamDef, GenericParamDefKind, GenericPredicates, Generics, OutlivesPredicate,
36        TraitPredicate, TraitRef, Ty, TypeOutlivesPredicate, UnevaluatedConst, VariantDef,
37    },
38};
39use crate::{
40    mir::{BodyKind, BodyRoot, CallKind, ConstOperand},
41    ty::{
42        AliasTy, ExistentialTraitRef, GenericArgs, ProjectionPredicate, Region,
43        RegionOutlivesPredicate,
44    },
45};
46
47pub trait Lower<'tcx> {
48    type R;
49
50    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R;
51}
52
53pub struct MirLoweringCtxt<'a, 'sess, 'tcx> {
54    tcx: TyCtxt<'tcx>,
55    param_env: ParamEnv<'tcx>,
56    selcx: SelectionContext<'a, 'tcx>,
57    sess: &'sess FluxSession,
58    rustc_mir: &'a rustc_mir::Body<'tcx>,
59}
60
61#[derive(Debug, Clone)]
62pub struct UnsupportedReason {
63    pub(crate) descr: String,
64}
65
66impl UnsupportedReason {
67    fn new(reason: impl ToString) -> Self {
68        UnsupportedReason { descr: reason.to_string() }
69    }
70
71    pub fn into_err(self) -> UnsupportedErr {
72        UnsupportedErr { descr: self.descr, span: None }
73    }
74}
75
76#[derive(Debug, Clone, Encodable, Decodable)]
77pub struct UnsupportedErr {
78    pub descr: String,
79    pub span: Option<Span>,
80}
81
82impl UnsupportedErr {
83    pub fn new(reason: UnsupportedReason) -> Self {
84        UnsupportedErr { descr: reason.descr, span: None }
85    }
86
87    pub fn with_span(mut self, span: Span) -> Self {
88        self.span = Some(span);
89        self
90    }
91}
92
93fn trait_ref_impl_id<'tcx>(
94    tcx: TyCtxt<'tcx>,
95    selcx: &mut SelectionContext<'_, 'tcx>,
96    param_env: ParamEnv<'tcx>,
97    trait_ref: rustc_ty::TraitRef<'tcx>,
98) -> Option<(DefId, rustc_middle::ty::GenericArgsRef<'tcx>)> {
99    let trait_ref = tcx.erase_and_anonymize_regions(trait_ref);
100    let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, trait_ref);
101    let impl_source = selcx.select(&obligation).ok()??;
102    let impl_source = selcx.infcx.resolve_vars_if_possible(impl_source);
103    // let impl_source = selcx.infcx.fully_resolve(impl_source).ok()?;
104    let ImplSource::UserDefined(impl_data) = impl_source else { return None };
105    Some((impl_data.impl_def_id, impl_data.args))
106}
107
108pub fn resolve_trait_ref_impl_id<'tcx>(
109    tcx: TyCtxt<'tcx>,
110    def_id: DefId,
111    trait_ref: rustc_ty::TraitRef<'tcx>,
112) -> Option<(DefId, rustc_middle::ty::GenericArgsRef<'tcx>)> {
113    let param_env = tcx.param_env(def_id);
114    let infcx = tcx
115        .infer_ctxt()
116        .with_next_trait_solver(true)
117        .build(TypingMode::non_body_analysis());
118    trait_ref_impl_id(tcx, &mut SelectionContext::new(&infcx), param_env, trait_ref)
119}
120
121pub fn resolve_call_query<'tcx>(
122    tcx: TyCtxt<'tcx>,
123    selcx: &mut SelectionContext<'_, 'tcx>,
124    param_env: ParamEnv<'tcx>,
125    callee_id: DefId,
126    args: rustc_middle::ty::GenericArgsRef<'tcx>,
127) -> Option<(DefId, rustc_middle::ty::GenericArgsRef<'tcx>)> {
128    let trait_id = tcx.trait_of_assoc(callee_id)?;
129    let trait_ref = rustc_ty::TraitRef::from_assoc(tcx, trait_id, args);
130    let (impl_def_id, impl_args) = trait_ref_impl_id(tcx, selcx, param_env, trait_ref)?;
131    let impl_args = args.rebase_onto(tcx, trait_id, impl_args);
132    let assoc_id = tcx.impl_item_implementor_ids(impl_def_id).get(&callee_id)?;
133    let assoc_item = tcx.associated_item(assoc_id);
134    Some((assoc_item.def_id, impl_args))
135}
136
137impl<'sess, 'tcx> MirLoweringCtxt<'_, 'sess, 'tcx> {
138    // We used to call `replicate_infer_ctxt` to compute the `infcx`
139    // which replicated the [`InferCtxt`] used for mir typeck
140    // by generating region variables for every region the body.
141    // HOWEVER,the rustc folks hid access to the region-variables
142    // so instead we have to take care to call `tcx.erase_regions(..)`
143    // before using the `infcx` or `SelectionContext` to do any queries
144    // (eg. see `get_impl_id_of_alias_reft` in projections.rs)
145    pub fn lower_mir_body(
146        tcx: TyCtxt<'tcx>,
147        sess: &'sess FluxSession,
148        def_id: LocalDefId,
149        body_with_facts: Rc<BodyWithBorrowckFacts<'tcx>>,
150    ) -> Result<BodyRoot<'tcx>, ErrorGuaranteed> {
151        let infcx = tcx
152            .infer_ctxt()
153            .with_next_trait_solver(true)
154            .build(TypingMode::analysis_in_body(tcx, def_id));
155        let def_id = body_with_facts.body.source.def_id();
156
157        let body =
158            Self::lower_rustc_body(tcx, &infcx, sess, def_id, &body_with_facts, BodyKind::Main)?;
159        let promoted = body_with_facts
160            .promoted
161            .indices()
162            .map(|promoted| {
163                Self::lower_rustc_body(
164                    tcx,
165                    &infcx,
166                    sess,
167                    def_id,
168                    &body_with_facts,
169                    BodyKind::Promoted(promoted),
170                )
171            })
172            .try_collect()?;
173
174        let body_root = BodyRoot::new(body_with_facts, infcx, body, promoted);
175        Ok(body_root)
176    }
177
178    fn lower_rustc_body(
179        tcx: TyCtxt<'tcx>,
180        infcx: &InferCtxt<'tcx>,
181        sess: &'sess FluxSession,
182        def_id: DefId,
183        facts: &Rc<BodyWithBorrowckFacts<'tcx>>,
184        kind: BodyKind,
185    ) -> Result<Body<'tcx>, ErrorGuaranteed> {
186        let body = kind.select_body(facts);
187        let selcx = SelectionContext::new(infcx);
188        let param_env = tcx.param_env(def_id);
189        let mut lower = MirLoweringCtxt { tcx, selcx, param_env, sess, rustc_mir: body };
190
191        let basic_blocks = body
192            .basic_blocks
193            .iter()
194            .map(|bb_data| lower.lower_basic_block_data(bb_data))
195            .try_collect()?;
196
197        let local_decls = body
198            .local_decls
199            .iter()
200            .map(|local_decl| lower.lower_local_decl(local_decl))
201            .try_collect()?;
202
203        Ok(Body::new(basic_blocks, local_decls, Rc::clone(facts), kind))
204    }
205
206    fn lower_basic_block_data(
207        &mut self,
208        data: &rustc_mir::BasicBlockData<'tcx>,
209    ) -> Result<BasicBlockData<'tcx>, ErrorGuaranteed> {
210        let data = BasicBlockData {
211            statements: data
212                .statements
213                .iter()
214                .map(|stmt| self.lower_statement(stmt))
215                .try_collect()?,
216            terminator: data
217                .terminator
218                .as_ref()
219                .map(|terminator| self.lower_terminator(terminator))
220                .transpose()?,
221            is_cleanup: data.is_cleanup,
222        };
223        Ok(data)
224    }
225
226    fn lower_local_decl(
227        &self,
228        local_decl: &rustc_mir::LocalDecl<'tcx>,
229    ) -> Result<LocalDecl, ErrorGuaranteed> {
230        Ok(LocalDecl {
231            ty: local_decl
232                .ty
233                .lower(self.tcx)
234                .map_err(|err| errors::UnsupportedLocalDecl::new(local_decl, err))
235                .emit(self.sess)?,
236            source_info: local_decl.source_info,
237        })
238    }
239
240    fn lower_statement(
241        &self,
242        stmt: &rustc_mir::Statement<'tcx>,
243    ) -> Result<Statement<'tcx>, ErrorGuaranteed> {
244        let span = stmt.source_info.span;
245        let kind = match &stmt.kind {
246            rustc_mir::StatementKind::Assign(box (place, rvalue)) => {
247                StatementKind::Assign(
248                    lower_place(self.tcx, place)
249                        .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
250                        .emit(self.sess)?,
251                    self.lower_rvalue(rvalue)
252                        .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
253                        .emit(self.sess)?,
254                )
255            }
256            rustc_mir::StatementKind::SetDiscriminant { place, variant_index } => {
257                StatementKind::SetDiscriminant(
258                    lower_place(self.tcx, place)
259                        .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
260                        .emit(self.sess)?,
261                    *variant_index,
262                )
263            }
264            rustc_mir::StatementKind::FakeRead(box (cause, place)) => {
265                StatementKind::FakeRead(Box::new((
266                    *cause,
267                    lower_place(self.tcx, place)
268                        .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
269                        .emit(self.sess)?,
270                )))
271            }
272            rustc_mir::StatementKind::PlaceMention(place) => {
273                StatementKind::PlaceMention(
274                    lower_place(self.tcx, place)
275                        .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
276                        .emit(self.sess)?,
277                )
278            }
279            rustc_mir::StatementKind::Nop
280            | rustc_mir::StatementKind::StorageLive(_)
281            | rustc_mir::StatementKind::StorageDead(_) => StatementKind::Nop,
282            rustc_mir::StatementKind::AscribeUserType(
283                box (place, rustc_mir::UserTypeProjection { projs, .. }),
284                variance,
285            ) if projs.is_empty() => {
286                StatementKind::AscribeUserType(
287                    lower_place(self.tcx, place)
288                        .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
289                        .emit(self.sess)?,
290                    *variance,
291                )
292            }
293            rustc_mir::StatementKind::Intrinsic(ndi) => {
294                match ndi.as_ref() {
295                    rustc_mir::NonDivergingIntrinsic::Assume(op) => {
296                        let op = self
297                            .lower_operand(op)
298                            .map_err(|reason| errors::UnsupportedMir::statement(span, reason))
299                            .emit(self.sess)?;
300                        StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op))
301                    }
302                    rustc_mir::NonDivergingIntrinsic::CopyNonOverlapping(_) => {
303                        return Err(errors::UnsupportedMir::from(stmt)).emit(self.sess);
304                    }
305                }
306            }
307
308            rustc_mir::StatementKind::Retag(_, _)
309            | rustc_mir::StatementKind::AscribeUserType(..)
310            | rustc_mir::StatementKind::Coverage(_)
311            | rustc_mir::StatementKind::ConstEvalCounter
312            | rustc_mir::StatementKind::BackwardIncompatibleDropHint { .. } => {
313                return Err(errors::UnsupportedMir::from(stmt)).emit(self.sess);
314            }
315        };
316        Ok(Statement { kind, source_info: stmt.source_info })
317    }
318
319    fn lower_terminator(
320        &mut self,
321        terminator: &rustc_mir::Terminator<'tcx>,
322    ) -> Result<Terminator<'tcx>, ErrorGuaranteed> {
323        let span = terminator.source_info.span;
324        let kind = match &terminator.kind {
325            rustc_mir::TerminatorKind::Return => TerminatorKind::Return,
326            rustc_mir::TerminatorKind::Call { func, args, destination, target, unwind, .. } => {
327                let kind = {
328                    let func_ty = func.ty(self.rustc_mir, self.tcx);
329                    match func_ty.kind() {
330                        rustc_middle::ty::TyKind::FnDef(fn_def, args) => {
331                            let lowered = args
332                                .lower(self.tcx)
333                                .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
334                                .emit(self.sess)?;
335                            let def_id = *fn_def;
336                            let generic_args = CallArgs { orig: args, lowered };
337                            let (resolved_id, resolved_args) = self
338                                .resolve_call(def_id, generic_args.orig)
339                                .map_err(|reason| {
340                                    errors::UnsupportedMir::new(span, "terminator call", reason)
341                                })
342                                .emit(self.sess)?;
343                            CallKind::FnDef { def_id, generic_args, resolved_id, resolved_args }
344                        }
345                        rustc_middle::ty::TyKind::FnPtr(fn_sig_tys, header) => {
346                            let fn_sig = fnptr_as_fnsig(fn_sig_tys, header)
347                                .lower(self.tcx)
348                                .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
349                                .emit(self.sess)?;
350                            let operand = self
351                                .lower_operand(func)
352                                .map_err(|reason| {
353                                    errors::UnsupportedMir::new(
354                                        span,
355                                        "function pointer target",
356                                        reason,
357                                    )
358                                })
359                                .emit(self.sess)?;
360                            CallKind::FnPtr { fn_sig, operand }
361                        }
362                        _ => {
363                            Err(errors::UnsupportedMir::terminator(
364                                span,
365                                UnsupportedReason::new(format!(
366                                    "unsupported callee type `{func_ty:?}`"
367                                )),
368                            ))
369                            .emit(self.sess)?
370                        }
371                    }
372                };
373
374                let destination = lower_place(self.tcx, destination)
375                    .map_err(|reason| {
376                        errors::UnsupportedMir::new(span, "terminator destination", reason)
377                    })
378                    .emit(self.sess)?;
379
380                TerminatorKind::Call {
381                    kind,
382                    destination,
383                    target: *target,
384                    args: args
385                        .iter()
386                        .map(|arg| {
387                            self.lower_operand(&arg.node).map_err(|reason| {
388                                errors::UnsupportedMir::new(span, "terminator args", reason)
389                            })
390                        })
391                        .try_collect()
392                        .emit(self.sess)?,
393                    unwind: *unwind,
394                }
395            }
396            rustc_mir::TerminatorKind::SwitchInt { discr, targets, .. } => {
397                TerminatorKind::SwitchInt {
398                    discr: self
399                        .lower_operand(discr)
400                        .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
401                        .emit(self.sess)?,
402                    targets: targets.clone(),
403                }
404            }
405            rustc_mir::TerminatorKind::Goto { target } => TerminatorKind::Goto { target: *target },
406            rustc_mir::TerminatorKind::Drop { place, target, unwind, .. } => {
407                TerminatorKind::Drop {
408                    place: lower_place(self.tcx, place)
409                        .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
410                        .emit(self.sess)?,
411                    target: *target,
412                    unwind: *unwind,
413                }
414            }
415            rustc_mir::TerminatorKind::Assert { cond, target, expected, msg, .. } => {
416                TerminatorKind::Assert {
417                    cond: self
418                        .lower_operand(cond)
419                        .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
420                        .emit(self.sess)?,
421                    expected: *expected,
422                    target: *target,
423                    msg: self
424                        .lower_assert_msg(msg)
425                        .ok_or_else(|| errors::UnsupportedMir::from(terminator))
426                        .emit(self.sess)?,
427                }
428            }
429            rustc_mir::TerminatorKind::Unreachable => TerminatorKind::Unreachable,
430            rustc_mir::TerminatorKind::FalseEdge { real_target, imaginary_target } => {
431                TerminatorKind::FalseEdge {
432                    real_target: *real_target,
433                    imaginary_target: *imaginary_target,
434                }
435            }
436            rustc_mir::TerminatorKind::FalseUnwind { real_target, unwind } => {
437                TerminatorKind::FalseUnwind { real_target: *real_target, unwind: *unwind }
438            }
439            rustc_mir::TerminatorKind::Yield { value, resume, resume_arg, drop } => {
440                TerminatorKind::Yield {
441                    value: self
442                        .lower_operand(value)
443                        .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
444                        .emit(self.sess)?,
445                    resume: *resume,
446                    resume_arg: lower_place(self.tcx, resume_arg)
447                        .map_err(|reason| errors::UnsupportedMir::terminator(span, reason))
448                        .emit(self.sess)?,
449                    drop: *drop,
450                }
451            }
452            rustc_mir::TerminatorKind::CoroutineDrop => TerminatorKind::CoroutineDrop,
453            rustc_mir::TerminatorKind::UnwindResume => TerminatorKind::UnwindResume,
454            rustc_mir::TerminatorKind::UnwindTerminate(..)
455            | rustc_mir::TerminatorKind::TailCall { .. }
456            | rustc_mir::TerminatorKind::InlineAsm { .. } => {
457                return Err(errors::UnsupportedMir::from(terminator)).emit(self.sess);
458            }
459        };
460        Ok(Terminator { kind, source_info: terminator.source_info })
461    }
462
463    fn resolve_call(
464        &mut self,
465        callee_id: DefId,
466        args: rustc_middle::ty::GenericArgsRef<'tcx>,
467    ) -> Result<(DefId, CallArgs<'tcx>), UnsupportedReason> {
468        let (resolved_id, resolved_args) =
469            resolve_call_query(self.tcx, &mut self.selcx, self.param_env, callee_id, args)
470                .unwrap_or((callee_id, args));
471        let call_args = CallArgs { lowered: resolved_args.lower(self.tcx)?, orig: resolved_args };
472        Ok((resolved_id, call_args))
473    }
474
475    fn lower_rvalue(
476        &self,
477        rvalue: &rustc_mir::Rvalue<'tcx>,
478    ) -> Result<Rvalue<'tcx>, UnsupportedReason> {
479        match rvalue {
480            rustc_mir::Rvalue::Use(op) => Ok(Rvalue::Use(self.lower_operand(op)?)),
481            rustc_mir::Rvalue::Repeat(op, c) => {
482                let op = self.lower_operand(op)?;
483                let c = c.lower(self.tcx)?;
484                Ok(Rvalue::Repeat(op, c))
485            }
486            rustc_mir::Rvalue::Ref(region, bk, p) => {
487                Ok(Rvalue::Ref(region.lower(self.tcx)?, *bk, lower_place(self.tcx, p)?))
488            }
489            rustc_mir::Rvalue::RawPtr(kind, place) => {
490                Ok(Rvalue::RawPtr(*kind, lower_place(self.tcx, place)?))
491            }
492            rustc_mir::Rvalue::Cast(kind, op, ty) => {
493                let kind = self.lower_cast_kind(*kind).ok_or_else(|| {
494                    UnsupportedReason::new(format!("unsupported cast `{kind:?}`"))
495                })?;
496                let op = self.lower_operand(op)?;
497                let ty = ty.lower(self.tcx)?;
498                Ok(Rvalue::Cast(kind, op, ty))
499            }
500            rustc_mir::Rvalue::BinaryOp(bin_op, box (op1, op2)) => {
501                Ok(Rvalue::BinaryOp(
502                    self.lower_bin_op(*bin_op)?,
503                    self.lower_operand(op1)?,
504                    self.lower_operand(op2)?,
505                ))
506            }
507            rustc_mir::Rvalue::UnaryOp(un_op, op) => {
508                Ok(Rvalue::UnaryOp(*un_op, self.lower_operand(op)?))
509            }
510            rustc_mir::Rvalue::Discriminant(p) => {
511                Ok(Rvalue::Discriminant(lower_place(self.tcx, p)?))
512            }
513            rustc_mir::Rvalue::Aggregate(aggregate_kind, args) => {
514                let aggregate_kind = self.lower_aggregate_kind(aggregate_kind)?;
515                let args = args.iter().map(|op| self.lower_operand(op)).try_collect()?;
516                Ok(Rvalue::Aggregate(aggregate_kind, args))
517            }
518            rustc_mir::Rvalue::ShallowInitBox(op, ty) => {
519                Ok(Rvalue::ShallowInitBox(self.lower_operand(op)?, ty.lower(self.tcx)?))
520            }
521            rustc_mir::Rvalue::ThreadLocalRef(_)
522            | rustc_mir::Rvalue::NullaryOp(..)
523            | rustc_mir::Rvalue::CopyForDeref(_)
524            | rustc_mir::Rvalue::WrapUnsafeBinder(..) => {
525                Err(UnsupportedReason::new(format!("unsupported rvalue `{rvalue:?}`")))
526            }
527        }
528    }
529
530    fn lower_pointer_coercion(
531        &self,
532        coercion: rustc_adjustment::PointerCoercion,
533    ) -> Option<PointerCast> {
534        match coercion {
535            rustc_adjustment::PointerCoercion::MutToConstPointer => {
536                Some(crate::mir::PointerCast::MutToConstPointer)
537            }
538            rustc_adjustment::PointerCoercion::Unsize => Some(crate::mir::PointerCast::Unsize),
539            rustc_adjustment::PointerCoercion::ClosureFnPointer(_) => {
540                Some(crate::mir::PointerCast::ClosureFnPointer)
541            }
542            rustc_adjustment::PointerCoercion::ReifyFnPointer => {
543                Some(crate::mir::PointerCast::ReifyFnPointer)
544            }
545            rustc_adjustment::PointerCoercion::UnsafeFnPointer
546            | rustc_adjustment::PointerCoercion::ArrayToPointer => None,
547        }
548    }
549    fn lower_cast_kind(&self, kind: rustc_mir::CastKind) -> Option<CastKind> {
550        match kind {
551            rustc_mir::CastKind::IntToInt => Some(CastKind::IntToInt),
552            rustc_mir::CastKind::IntToFloat => Some(CastKind::IntToFloat),
553            rustc_mir::CastKind::FloatToInt => Some(CastKind::FloatToInt),
554            rustc_mir::CastKind::FloatToFloat => Some(CastKind::FloatToFloat),
555            rustc_mir::CastKind::PtrToPtr => Some(CastKind::PtrToPtr),
556            rustc_mir::CastKind::PointerCoercion(ptr_coercion, _) => {
557                Some(CastKind::PointerCoercion(self.lower_pointer_coercion(ptr_coercion)?))
558            }
559            rustc_mir::CastKind::PointerExposeProvenance => Some(CastKind::PointerExposeProvenance),
560            rustc_mir::CastKind::PointerWithExposedProvenance => {
561                Some(CastKind::PointerWithExposedProvenance)
562            }
563            _ => None,
564        }
565    }
566
567    fn lower_aggregate_kind(
568        &self,
569        aggregate_kind: &rustc_mir::AggregateKind<'tcx>,
570    ) -> Result<AggregateKind, UnsupportedReason> {
571        match aggregate_kind {
572            rustc_mir::AggregateKind::Adt(
573                def_id,
574                variant_idx,
575                args,
576                user_type_annot_idx,
577                field_idx,
578            ) => {
579                Ok(AggregateKind::Adt(
580                    *def_id,
581                    *variant_idx,
582                    args.lower(self.tcx)?,
583                    *user_type_annot_idx,
584                    *field_idx,
585                ))
586            }
587            rustc_mir::AggregateKind::Array(ty) => Ok(AggregateKind::Array(ty.lower(self.tcx)?)),
588            rustc_mir::AggregateKind::Tuple => Ok(AggregateKind::Tuple),
589            rustc_mir::AggregateKind::Closure(did, args) => {
590                let args = args.lower(self.tcx)?;
591                Ok(AggregateKind::Closure(*did, args))
592            }
593            rustc_mir::AggregateKind::Coroutine(did, args) => {
594                let args = args.lower(self.tcx)?;
595                Ok(AggregateKind::Coroutine(*did, args))
596            }
597            rustc_mir::AggregateKind::RawPtr(_, _)
598            | rustc_mir::AggregateKind::CoroutineClosure(..) => {
599                Err(UnsupportedReason::new(format!(
600                    "unsupported aggregate kind `{aggregate_kind:?}`"
601                )))
602            }
603        }
604    }
605
606    fn lower_bin_op(&self, bin_op: rustc_mir::BinOp) -> Result<BinOp, UnsupportedReason> {
607        match bin_op {
608            rustc_mir::BinOp::Add => Ok(BinOp::Add),
609            rustc_mir::BinOp::Sub => Ok(BinOp::Sub),
610            rustc_mir::BinOp::Gt => Ok(BinOp::Gt),
611            rustc_mir::BinOp::Ge => Ok(BinOp::Ge),
612            rustc_mir::BinOp::Lt => Ok(BinOp::Lt),
613            rustc_mir::BinOp::Le => Ok(BinOp::Le),
614            rustc_mir::BinOp::Eq => Ok(BinOp::Eq),
615            rustc_mir::BinOp::Ne => Ok(BinOp::Ne),
616            rustc_mir::BinOp::Mul => Ok(BinOp::Mul),
617            rustc_mir::BinOp::Div => Ok(BinOp::Div),
618            rustc_mir::BinOp::Rem => Ok(BinOp::Rem),
619            rustc_mir::BinOp::BitAnd => Ok(BinOp::BitAnd),
620            rustc_mir::BinOp::BitOr => Ok(BinOp::BitOr),
621            rustc_mir::BinOp::BitXor => Ok(BinOp::BitXor),
622            rustc_mir::BinOp::Shl => Ok(BinOp::Shl),
623            rustc_mir::BinOp::Shr => Ok(BinOp::Shr),
624            rustc_mir::BinOp::AddUnchecked
625            | rustc_mir::BinOp::SubUnchecked
626            | rustc_mir::BinOp::MulUnchecked
627            | rustc_mir::BinOp::ShlUnchecked
628            | rustc_mir::BinOp::ShrUnchecked
629            | rustc_mir::BinOp::AddWithOverflow
630            | rustc_mir::BinOp::SubWithOverflow
631            | rustc_mir::BinOp::MulWithOverflow
632            | rustc_mir::BinOp::Cmp
633            | rustc_mir::BinOp::Offset => {
634                Err(UnsupportedReason::new(format!("unsupported binary op `{bin_op:?}`")))
635            }
636        }
637    }
638
639    fn lower_operand(
640        &self,
641        op: &rustc_mir::Operand<'tcx>,
642    ) -> Result<Operand<'tcx>, UnsupportedReason> {
643        match op {
644            rustc_mir::Operand::Copy(place) => Ok(Operand::Copy(lower_place(self.tcx, place)?)),
645            rustc_mir::Operand::Move(place) => Ok(Operand::Move(lower_place(self.tcx, place)?)),
646            rustc_mir::Operand::Constant(c) => Ok(Operand::Constant(self.lower_constant(c)?)),
647        }
648    }
649
650    fn lower_constant(
651        &self,
652        constant: &rustc_mir::ConstOperand<'tcx>,
653    ) -> Result<ConstOperand<'tcx>, UnsupportedReason> {
654        Ok(ConstOperand {
655            span: constant.span,
656            ty: constant.const_.ty().lower(self.tcx)?,
657            const_: constant.const_,
658        })
659    }
660
661    fn lower_assert_msg(&self, msg: &rustc_mir::AssertMessage) -> Option<AssertKind> {
662        use rustc_mir::AssertKind::*;
663        match msg {
664            BoundsCheck { .. } => Some(AssertKind::BoundsCheck),
665            DivisionByZero(_) => Some(AssertKind::DivisionByZero),
666            RemainderByZero(_) => Some(AssertKind::RemainderByZero),
667            Overflow(bin_op, ..) => Some(AssertKind::Overflow(self.lower_bin_op(*bin_op).ok()?)),
668            _ => None,
669        }
670    }
671}
672
673pub fn lower_place<'tcx>(
674    _tcx: TyCtxt<'tcx>,
675    place: &rustc_mir::Place<'tcx>,
676) -> Result<Place, UnsupportedReason> {
677    let mut projection = vec![];
678    for elem in place.projection {
679        match elem {
680            rustc_mir::PlaceElem::Deref => projection.push(PlaceElem::Deref),
681            rustc_mir::PlaceElem::Field(field, _) => projection.push(PlaceElem::Field(field)),
682            rustc_mir::PlaceElem::Downcast(name, idx) => {
683                projection.push(PlaceElem::Downcast(name, idx));
684            }
685            rustc_mir::PlaceElem::Index(v) => projection.push(PlaceElem::Index(v)),
686            rustc_mir::ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
687                projection.push(PlaceElem::ConstantIndex { offset, min_length, from_end });
688            }
689            _ => {
690                return Err(UnsupportedReason::new(format!("unsupported place `{place:?}`")));
691            }
692        }
693    }
694    Ok(Place { local: place.local, projection })
695}
696
697impl<'tcx> Lower<'tcx> for rustc_ty::FnSig<'tcx> {
698    type R = Result<FnSig, UnsupportedReason>;
699
700    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
701        let inputs_and_output = List::from_vec(
702            self.inputs_and_output
703                .iter()
704                .map(|ty| ty.lower(tcx))
705                .try_collect()?,
706        );
707        Ok(FnSig { safety: self.safety, abi: self.abi, inputs_and_output })
708    }
709}
710
711impl<'tcx> Lower<'tcx> for &'tcx rustc_ty::List<rustc_ty::BoundVariableKind> {
712    type R = Result<List<BoundVariableKind>, UnsupportedReason>;
713
714    fn lower(self, _tcx: TyCtxt<'tcx>) -> Self::R {
715        let mut vars = vec![];
716        for var in self {
717            match var {
718                rustc_ty::BoundVariableKind::Region(kind) => {
719                    vars.push(BoundVariableKind::Region(kind));
720                }
721                _ => {
722                    return Err(UnsupportedReason {
723                        descr: format!("unsupported bound variable {var:?}"),
724                    });
725                }
726            }
727        }
728        Ok(List::from_vec(vars))
729    }
730}
731
732impl<'tcx> Lower<'tcx> for rustc_ty::ValTree<'tcx> {
733    type R = crate::ty::ValTree;
734
735    fn lower(self, _tcx: TyCtxt<'tcx>) -> Self::R {
736        match &*self {
737            rustc_ty::ValTreeKind::Leaf(scalar_int) => crate::ty::ValTree::Leaf(*scalar_int),
738            rustc_ty::ValTreeKind::Branch(trees) => {
739                let trees = trees.iter().map(|tree| tree.lower(_tcx)).collect();
740                crate::ty::ValTree::Branch(trees)
741            }
742        }
743    }
744}
745
746impl<'tcx> Lower<'tcx> for rustc_ty::Const<'tcx> {
747    type R = Result<Const, UnsupportedReason>;
748
749    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
750        let kind = match self.kind() {
751            rustc_type_ir::ConstKind::Param(param_const) => {
752                ConstKind::Param(ParamConst { name: param_const.name, index: param_const.index })
753            }
754            rustc_type_ir::ConstKind::Value(value) => {
755                ConstKind::Value(value.ty.lower(tcx)?, value.valtree.lower(tcx))
756            }
757            rustc_type_ir::ConstKind::Unevaluated(c) => {
758                // TODO: raise unsupported if c.args is not empty?
759                let args = c.args.lower(tcx)?;
760                ConstKind::Unevaluated(UnevaluatedConst { def: c.def, args, promoted: None })
761            }
762            _ => return Err(UnsupportedReason::new(format!("unsupported const {self:?}"))),
763        };
764        Ok(Const { kind })
765    }
766}
767
768impl<'tcx, T, S> Lower<'tcx> for rustc_ty::Binder<'tcx, T>
769where
770    T: Lower<'tcx, R = Result<S, UnsupportedReason>>,
771{
772    type R = Result<Binder<S>, UnsupportedReason>;
773
774    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
775        let vars = self.bound_vars().lower(tcx)?;
776        Ok(Binder::bind_with_vars(self.skip_binder().lower(tcx)?, vars))
777    }
778}
779
780impl<'tcx> Lower<'tcx> for rustc_ty::Ty<'tcx> {
781    type R = Result<Ty, UnsupportedReason>;
782
783    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
784        match self.kind() {
785            rustc_ty::Ref(region, ty, mutability) => {
786                Ok(Ty::mk_ref(region.lower(tcx)?, ty.lower(tcx)?, *mutability))
787            }
788            rustc_ty::Bool => Ok(Ty::mk_bool()),
789            rustc_ty::Int(int_ty) => Ok(Ty::mk_int(*int_ty)),
790            rustc_ty::Uint(uint_ty) => Ok(Ty::mk_uint(*uint_ty)),
791            rustc_ty::Float(float_ty) => Ok(Ty::mk_float(*float_ty)),
792            rustc_ty::Param(param_ty) => Ok(Ty::mk_param(*param_ty)),
793            rustc_ty::Adt(adt_def, args) => {
794                let args = args.lower(tcx)?;
795                Ok(Ty::mk_adt(adt_def.lower(tcx), args))
796            }
797            rustc_ty::FnDef(def_id, args) => {
798                let args = args.lower(tcx)?;
799                Ok(Ty::mk_fn_def(*def_id, args))
800            }
801            rustc_ty::Never => Ok(Ty::mk_never()),
802            rustc_ty::Str => Ok(Ty::mk_str()),
803            rustc_ty::Char => Ok(Ty::mk_char()),
804            rustc_ty::Tuple(tys) => {
805                let tys = List::from_vec(tys.iter().map(|ty| ty.lower(tcx)).try_collect()?);
806                Ok(Ty::mk_tuple(tys))
807            }
808            rustc_ty::Array(ty, len) => Ok(Ty::mk_array(ty.lower(tcx)?, len.lower(tcx)?)),
809            rustc_ty::Slice(ty) => Ok(Ty::mk_slice(ty.lower(tcx)?)),
810            rustc_ty::RawPtr(ty, mutbl) => {
811                let ty = ty.lower(tcx)?;
812                Ok(Ty::mk_raw_ptr(ty, *mutbl))
813            }
814            rustc_ty::FnPtr(fn_sig_tys, header) => {
815                let fn_sig = fnptr_as_fnsig(fn_sig_tys, header).lower(tcx)?;
816                Ok(Ty::mk_fn_ptr(fn_sig))
817            }
818            rustc_ty::Closure(did, args) => {
819                let args = args.lower(tcx)?;
820                Ok(Ty::mk_closure(*did, args))
821            }
822
823            rustc_ty::Alias(kind, alias_ty) => {
824                let kind = kind.lower(tcx)?;
825                let args = alias_ty.args.lower(tcx)?;
826                Ok(Ty::mk_alias(kind, alias_ty.def_id, args))
827            }
828            rustc_ty::Coroutine(did, args) => {
829                let args = args.lower(tcx)?;
830                Ok(Ty::mk_coroutine(*did, args))
831            }
832            rustc_ty::CoroutineWitness(did, args) => {
833                let args = args.lower(tcx)?;
834                Ok(Ty::mk_generator_witness(*did, args))
835            }
836            rustc_ty::Dynamic(predicates, region) => {
837                let region = region.lower(tcx)?;
838
839                let exi_preds = List::from_vec(
840                    predicates
841                        .iter()
842                        .map(|pred| pred.lower(tcx))
843                        .try_collect()?,
844                );
845
846                Ok(Ty::mk_dynamic(exi_preds, region))
847            }
848            rustc_ty::Foreign(def_id) => Ok(Ty::mk_foreign(*def_id)),
849            rustc_ty::Pat(..) => Ok(Ty::mk_pat()),
850            _ => Err(UnsupportedReason::new(format!("unsupported type `{self:?}`"))),
851        }
852    }
853}
854
855fn fnptr_as_fnsig<'tcx>(
856    fn_sig_tys: &'tcx rustc_ty::Binder<'tcx, rustc_ty::FnSigTys<TyCtxt<'tcx>>>,
857    header: &'tcx rustc_ty::FnHeader<TyCtxt<'tcx>>,
858) -> rustc_ty::Binder<'tcx, rustc_ty::FnSig<'tcx>> {
859    fn_sig_tys.map_bound(|fn_sig_tys| {
860        rustc_ty::FnSig {
861            inputs_and_output: fn_sig_tys.inputs_and_output,
862            c_variadic: header.c_variadic,
863            safety: header.safety,
864            abi: header.abi,
865        }
866    })
867}
868
869impl<'tcx> Lower<'tcx> for rustc_ty::AliasTyKind {
870    type R = Result<AliasKind, UnsupportedReason>;
871
872    fn lower(self, _tcx: TyCtxt<'tcx>) -> Self::R {
873        match self {
874            rustc_type_ir::AliasTyKind::Projection => Ok(AliasKind::Projection),
875            rustc_type_ir::AliasTyKind::Opaque => Ok(AliasKind::Opaque),
876            _ => Err(UnsupportedReason::new(format!("unsupported alias kind `{self:?}`"))),
877        }
878    }
879}
880
881impl<'tcx> Lower<'tcx> for rustc_ty::AdtDef<'tcx> {
882    type R = AdtDef;
883
884    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
885        AdtDef::new(AdtDefData::new(
886            tcx,
887            self,
888            self.variants()
889                .iter()
890                .map(|variant| {
891                    VariantDef {
892                        def_id: variant.def_id,
893                        name: variant.name,
894                        fields: variant
895                            .fields
896                            .iter()
897                            .map(|f| FieldDef { did: f.did, name: f.name })
898                            .collect(),
899                    }
900                })
901                .collect(),
902        ))
903    }
904}
905
906impl<'tcx> Lower<'tcx> for rustc_ty::ExistentialPredicate<'tcx> {
907    type R = Result<ExistentialPredicate, UnsupportedReason>;
908
909    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
910        match self {
911            rustc_type_ir::ExistentialPredicate::Trait(trait_ref) => {
912                Ok(ExistentialPredicate::Trait(ExistentialTraitRef {
913                    def_id: trait_ref.def_id,
914                    args: trait_ref.args.lower(tcx)?,
915                }))
916            }
917            rustc_type_ir::ExistentialPredicate::Projection(proj) => {
918                let Some(term) = proj.term.as_type() else {
919                    return Err(UnsupportedReason::new(format!(
920                        "unsupported existential predicate `{self:?}`"
921                    )));
922                };
923                Ok(ExistentialPredicate::Projection(ExistentialProjection {
924                    def_id: proj.def_id,
925                    args: proj.args.lower(tcx)?,
926                    term: term.lower(tcx)?,
927                }))
928            }
929            rustc_type_ir::ExistentialPredicate::AutoTrait(def_id) => {
930                Ok(ExistentialPredicate::AutoTrait(def_id))
931            }
932        }
933    }
934}
935
936impl<'tcx> Lower<'tcx> for rustc_middle::ty::GenericArgsRef<'tcx> {
937    type R = Result<GenericArgs, UnsupportedReason>;
938
939    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
940        Ok(List::from_vec(self.iter().map(|arg| arg.lower(tcx)).try_collect()?))
941    }
942}
943
944impl<'tcx> Lower<'tcx> for rustc_middle::ty::GenericArg<'tcx> {
945    type R = Result<GenericArg, UnsupportedReason>;
946
947    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
948        match self.kind() {
949            GenericArgKind::Type(ty) => Ok(GenericArg::Ty(ty.lower(tcx)?)),
950            GenericArgKind::Lifetime(region) => Ok(GenericArg::Lifetime(region.lower(tcx)?)),
951            GenericArgKind::Const(c) => Ok(GenericArg::Const(c.lower(tcx)?)),
952        }
953    }
954}
955
956impl<'tcx> Lower<'tcx> for rustc_middle::ty::Region<'tcx> {
957    type R = Result<Region, UnsupportedReason>;
958
959    fn lower(self, _tcx: TyCtxt<'tcx>) -> Self::R {
960        use rustc_middle::ty;
961        match self.kind() {
962            ty::ReVar(rvid) => Ok(Region::ReVar(rvid)),
963            ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), bregion) => {
964                Ok(Region::ReBound(
965                    debruijn,
966                    Ok(BoundRegion { kind: bregion.kind, var: bregion.var })?,
967                ))
968            }
969            ty::ReEarlyParam(bregion) => Ok(Region::ReEarlyParam(bregion)),
970            ty::ReStatic => Ok(Region::ReStatic),
971            ty::ReErased => Ok(Region::ReErased),
972            ty::ReBound(ty::BoundVarIndexKind::Canonical, _)
973            | ty::ReLateParam(_)
974            | ty::RePlaceholder(_)
975            | ty::ReError(_) => {
976                Err(UnsupportedReason::new(format!("unsupported region `{self:?}`")))
977            }
978        }
979    }
980}
981
982impl<'tcx> Lower<'tcx> for &'tcx rustc_middle::ty::Generics {
983    type R = Generics<'tcx>;
984
985    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
986        let params = List::from_vec(
987            self.own_params
988                .iter()
989                .map(|param| param.lower(tcx))
990                .collect(),
991        );
992        Generics { params, orig: self }
993    }
994}
995
996impl<'tcx> Lower<'tcx> for &rustc_middle::ty::GenericParamDef {
997    type R = GenericParamDef;
998
999    fn lower(self, _tcx: TyCtxt<'tcx>) -> Self::R {
1000        let kind = match self.kind {
1001            rustc_ty::GenericParamDefKind::Type { has_default, .. } => {
1002                GenericParamDefKind::Type { has_default }
1003            }
1004            rustc_ty::GenericParamDefKind::Lifetime => GenericParamDefKind::Lifetime,
1005            rustc_ty::GenericParamDefKind::Const { has_default, .. } => {
1006                GenericParamDefKind::Const { has_default }
1007            }
1008        };
1009        GenericParamDef { def_id: self.def_id, index: self.index, name: self.name, kind }
1010    }
1011}
1012
1013impl<'tcx> Lower<'tcx> for rustc_ty::GenericPredicates<'tcx> {
1014    type R = Result<GenericPredicates, UnsupportedErr>;
1015
1016    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1017        let predicates = self
1018            .predicates
1019            .iter()
1020            .map(|(clause, span)| {
1021                clause
1022                    .lower(tcx)
1023                    .map_err(|reason| UnsupportedErr::new(reason).with_span(*span))
1024            })
1025            .try_collect()?;
1026        Ok(GenericPredicates { parent: self.parent, predicates })
1027    }
1028}
1029
1030impl<'tcx> Lower<'tcx> for rustc_ty::Clauses<'tcx> {
1031    type R = Result<List<Clause>, UnsupportedErr>;
1032
1033    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1034        self.iter()
1035            .map(|clause| clause.lower(tcx).map_err(UnsupportedErr::new))
1036            .try_collect()
1037    }
1038}
1039
1040impl<'tcx> Lower<'tcx> for rustc_ty::ClauseKind<'tcx> {
1041    type R = Result<ClauseKind, UnsupportedReason>;
1042
1043    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1044        let kind = match self {
1045            rustc_ty::ClauseKind::Trait(trait_pred) => {
1046                ClauseKind::Trait(TraitPredicate { trait_ref: trait_pred.trait_ref.lower(tcx)? })
1047            }
1048            rustc_ty::ClauseKind::Projection(proj_pred) => {
1049                let Some(term) = proj_pred.term.as_type() else {
1050                    return Err(UnsupportedReason::new(format!(
1051                        "unsupported projection predicate `{proj_pred:?}`"
1052                    )));
1053                };
1054                let proj_ty = proj_pred.projection_term;
1055                let args = proj_ty.args.lower(tcx)?;
1056
1057                let projection_ty = AliasTy { args, def_id: proj_ty.def_id };
1058                let term = term.lower(tcx)?;
1059                ClauseKind::Projection(ProjectionPredicate { projection_ty, term })
1060            }
1061            rustc_ty::ClauseKind::RegionOutlives(outlives) => {
1062                ClauseKind::RegionOutlives(outlives.lower(tcx)?)
1063            }
1064            rustc_ty::ClauseKind::TypeOutlives(outlives) => {
1065                ClauseKind::TypeOutlives(outlives.lower(tcx)?)
1066            }
1067            rustc_ty::ClauseKind::ConstArgHasType(const_, ty) => {
1068                ClauseKind::ConstArgHasType(const_.lower(tcx)?, ty.lower(tcx)?)
1069            }
1070            rustc_ty::ClauseKind::UnstableFeature(sym) => ClauseKind::UnstableFeature(sym),
1071            _ => {
1072                return Err(UnsupportedReason::new(format!("unsupported clause kind `{self:?}`")));
1073            }
1074        };
1075        Ok(kind)
1076    }
1077}
1078
1079impl<'tcx> Lower<'tcx> for rustc_ty::Clause<'tcx> {
1080    type R = Result<Clause, UnsupportedReason>;
1081
1082    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1083        Ok(Clause::new(self.kind().lower(tcx)?))
1084    }
1085}
1086
1087impl<'tcx> Lower<'tcx> for rustc_ty::TraitRef<'tcx> {
1088    type R = Result<TraitRef, UnsupportedReason>;
1089
1090    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1091        Ok(TraitRef { def_id: self.def_id, args: self.args.lower(tcx)? })
1092    }
1093}
1094
1095impl<'tcx> Lower<'tcx> for rustc_ty::TypeOutlivesPredicate<'tcx> {
1096    type R = Result<TypeOutlivesPredicate, UnsupportedReason>;
1097
1098    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1099        Ok(OutlivesPredicate(self.0.lower(tcx)?, self.1.lower(tcx)?))
1100    }
1101}
1102
1103impl<'tcx> Lower<'tcx> for rustc_ty::RegionOutlivesPredicate<'tcx> {
1104    type R = Result<RegionOutlivesPredicate, UnsupportedReason>;
1105
1106    fn lower(self, tcx: TyCtxt<'tcx>) -> Self::R {
1107        Ok(OutlivesPredicate(self.0.lower(tcx)?, self.1.lower(tcx)?))
1108    }
1109}
1110
1111mod errors {
1112    use std::path::PathBuf;
1113
1114    use flux_errors::E0999;
1115    use flux_macros::Diagnostic;
1116    use rustc_middle::mir as rustc_mir;
1117    use rustc_span::Span;
1118
1119    use super::UnsupportedReason;
1120
1121    #[derive(Diagnostic)]
1122    #[diag(rustc_bridge_unsupported_local_decl, code = E0999)]
1123    pub(super) struct UnsupportedLocalDecl<'tcx> {
1124        #[primary_span]
1125        #[label]
1126        span: Span,
1127        ty: rustc_middle::ty::Ty<'tcx>,
1128    }
1129
1130    impl<'tcx> UnsupportedLocalDecl<'tcx> {
1131        pub(super) fn new(
1132            local_decl: &rustc_mir::LocalDecl<'tcx>,
1133            _err: UnsupportedReason,
1134        ) -> Self {
1135            Self { span: local_decl.source_info.span, ty: local_decl.ty }
1136        }
1137    }
1138
1139    #[derive(Diagnostic)]
1140    #[diag(rustc_bridge_unsupported_mir, code = E0999)]
1141    #[note]
1142    pub(super) struct UnsupportedMir {
1143        #[primary_span]
1144        span: Span,
1145        kind: &'static str,
1146        reason: UnsupportedReason,
1147    }
1148
1149    impl rustc_errors::IntoDiagArg for UnsupportedReason {
1150        fn into_diag_arg(self, _path: &mut Option<PathBuf>) -> rustc_errors::DiagArgValue {
1151            rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(self.descr))
1152        }
1153    }
1154
1155    impl UnsupportedMir {
1156        pub(super) fn new(span: Span, kind: &'static str, reason: UnsupportedReason) -> Self {
1157            Self { span, kind, reason }
1158        }
1159
1160        pub(super) fn terminator(span: Span, reason: UnsupportedReason) -> Self {
1161            Self { span, kind: "terminator", reason }
1162        }
1163
1164        pub(super) fn statement(span: Span, reason: UnsupportedReason) -> Self {
1165            Self { span, kind: "statement", reason }
1166        }
1167    }
1168
1169    impl<'a, 'tcx> From<&'a rustc_mir::Terminator<'tcx>> for UnsupportedMir {
1170        fn from(terminator: &'a rustc_mir::Terminator<'tcx>) -> Self {
1171            Self::terminator(
1172                terminator.source_info.span,
1173                UnsupportedReason::new(format!("{terminator:?}",)),
1174            )
1175        }
1176    }
1177
1178    impl<'a, 'tcx> From<&'a rustc_mir::Statement<'tcx>> for UnsupportedMir {
1179        fn from(statement: &'a rustc_mir::Statement<'tcx>) -> Self {
1180            Self::statement(
1181                statement.source_info.span,
1182                UnsupportedReason::new(format!("{statement:?}")),
1183            )
1184        }
1185    }
1186}