rustc_mir_build/builder/custom/
mod.rs1use rustc_attr_ir as attrs;
20use rustc_data_structures::fx::FxHashMap;
21use rustc_hir::HirId;
22use rustc_hir::def_id::DefId;
23use rustc_index::{IndexSlice, IndexVec, indexvec};
24use rustc_middle::mir::*;
25use rustc_middle::thir::*;
26use rustc_middle::ty::{self, Ty, TyCtxt};
27use rustc_span::{Span, bug};
28
29mod parse;
30
31pub(super) fn build_custom_mir<'tcx>(
32 tcx: TyCtxt<'tcx>,
33 did: DefId,
34 hir_id: HirId,
35 thir: &Thir<'tcx>,
36 expr: ExprId,
37 params: &IndexSlice<ParamId, Param<'tcx>>,
38 return_ty: Ty<'tcx>,
39 return_ty_span: Span,
40 span: Span,
41 dialect: Option<attrs::MirDialect>,
42 phase: Option<attrs::MirPhase>,
43) -> Body<'tcx> {
44 let mut body = Body {
45 basic_blocks: BasicBlocks::new(IndexVec::new()),
46 source: MirSource::item(did),
47 phase: MirPhase::Built,
48 source_scopes: IndexVec::new(),
49 coroutine: None,
50 local_decls: IndexVec::new(),
51 user_type_annotations: IndexVec::new(),
52 arg_count: params.len(),
53 spread_arg: None,
54 var_debug_info: Vec::new(),
55 span,
56 required_consts: None,
57 mentioned_items: None,
58 is_polymorphic: false,
59 tainted_by_errors: None,
60 injection_phase: None,
61 pass_count: 0,
62 coverage_early_info: None,
63 coverage_mir_info: None,
64 };
65
66 body.local_decls.push(LocalDecl::new(return_ty, return_ty_span));
67 body.source_scopes.push(SourceScopeData {
68 span,
69 parent_scope: None,
70 inlined: None,
71 inlined_parent_scope: None,
72 local_data: ClearCrossCrate::Set(SourceScopeLocalData { lint_root: hir_id }),
73 });
74 body.injection_phase = Some(parse_attribute(dialect, phase));
75
76 let mut pctxt = ParseCtxt {
77 tcx,
78 typing_env: body.typing_env(tcx),
79 thir,
80 source_scope: OUTERMOST_SOURCE_SCOPE,
81 body: &mut body,
82 block_decls: IndexVec::from_raw(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[false])))indexvec![false],
84 local_map: FxHashMap::default(),
85 block_map: FxHashMap::default(),
86 };
87
88 let res = try {
89 pctxt.parse_args(params)?;
90 pctxt.parse_body(expr)?;
91 };
92 if let Err(err) = res {
93 tcx.dcx().span_fatal(
94 err.span,
95 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Could not parse {0}, found: {1:?}",
err.expected, err.item_description))
})format!("Could not parse {}, found: {:?}", err.expected, err.item_description),
96 )
97 }
98
99 body
100}
101
102fn parse_attribute(dialect: Option<attrs::MirDialect>, phase: Option<attrs::MirPhase>) -> MirPhase {
105 let Some(dialect) = dialect else {
106 if !phase.is_none() {
::core::panicking::panic("assertion failed: phase.is_none()")
};assert!(phase.is_none());
108 return MirPhase::Built;
109 };
110
111 match dialect {
112 attrs::MirDialect::Built => {
113 if !phase.is_none() {
{
::core::panicking::panic_fmt(format_args!("Cannot specify a phase for `Built` MIR"));
}
};assert!(phase.is_none(), "Cannot specify a phase for `Built` MIR");
115 MirPhase::Built
116 }
117 attrs::MirDialect::Analysis => match phase {
118 None | Some(attrs::MirPhase::Initial) => MirPhase::Analysis(AnalysisPhase::Initial),
119
120 Some(attrs::MirPhase::PostCleanup) => MirPhase::Analysis(AnalysisPhase::PostCleanup),
121
122 Some(attrs::MirPhase::Optimized) => {
123 ::rustc_span::macros::bug_impl(None,
format_args!("`optimized` dialect is not compatible with the `analysis` dialect"),
Location::caller())bug!("`optimized` dialect is not compatible with the `analysis` dialect")
125 }
126 },
127
128 attrs::MirDialect::Runtime => match phase {
129 None | Some(attrs::MirPhase::Initial) => MirPhase::Runtime(RuntimePhase::Initial),
130 Some(attrs::MirPhase::PostCleanup) => MirPhase::Runtime(RuntimePhase::PostCleanup),
131 Some(attrs::MirPhase::Optimized) => MirPhase::Runtime(RuntimePhase::Optimized),
132 },
133 }
134}
135
136struct ParseCtxt<'a, 'tcx> {
137 tcx: TyCtxt<'tcx>,
138 typing_env: ty::TypingEnv<'tcx>,
139 thir: &'a Thir<'tcx>,
140 source_scope: SourceScope,
141 body: &'a mut Body<'tcx>,
142 block_decls: IndexVec<BasicBlock, bool>,
144 local_map: FxHashMap<LocalVarId, Local>,
145 block_map: FxHashMap<LocalVarId, BasicBlock>,
146}
147
148struct ParseError {
149 span: Span,
150 item_description: String,
151 expected: String,
152}
153
154impl<'a, 'tcx> ParseCtxt<'a, 'tcx> {
155 fn expr_error(&self, expr: ExprId, expected: &'static str) -> ParseError {
156 let expr = &self.thir[expr];
157 ParseError {
158 span: expr.span,
159 item_description: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", expr.kind))
})format!("{:?}", expr.kind),
160 expected: expected.to_string(),
161 }
162 }
163
164 fn stmt_error(&self, stmt: StmtId, expected: &'static str) -> ParseError {
165 let stmt = &self.thir[stmt];
166 let span = match stmt.kind {
167 StmtKind::Expr { expr, .. } => self.thir[expr].span,
168 StmtKind::Let { span, .. } => span,
169 };
170 ParseError {
171 span,
172 item_description: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", stmt.kind))
})format!("{:?}", stmt.kind),
173 expected: expected.to_string(),
174 }
175 }
176}
177
178type PResult<T> = Result<T, ParseError>;