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