1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
9 use std::{mem, ops::Index, sync::Arc};
13 use drop_bomb::DropBomb;
16 ast_id_map::AstIdMap, diagnostics::DiagnosticSink, hygiene::Hygiene, AstId, ExpandResult,
17 HirFileId, InFile, MacroDefId,
19 use la_arena::{Arena, ArenaMap};
21 use rustc_hash::FxHashMap;
22 use syntax::{ast, AstNode, AstPtr};
25 attr::{Attrs, RawAttrs},
27 expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
28 item_scope::BuiltinShadowMode,
30 path::{ModPath, Path},
32 AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleId,
36 pub use lower::LowerCtx;
38 /// A subset of Expander that only deals with cfg attributes. We only need it to
39 /// avoid cyclic queries in crate def map during enum processing.
41 pub(crate) struct CfgExpander {
42 cfg_options: CfgOptions,
49 cfg_expander: CfgExpander,
51 current_file_id: HirFileId,
52 ast_id_map: Arc<AstIdMap>,
53 module: LocalModuleId,
54 recursion_limit: usize,
58 const EXPANSION_RECURSION_LIMIT: usize = 32;
61 const EXPANSION_RECURSION_LIMIT: usize = 128;
66 current_file_id: HirFileId,
69 let hygiene = Hygiene::new(db.upcast(), current_file_id);
70 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
71 CfgExpander { cfg_options, hygiene, krate }
74 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
75 RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
78 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> bool {
79 let attrs = self.parse_attrs(db, owner);
80 attrs.is_cfg_enabled(&self.cfg_options)
85 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
86 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
87 let def_map = module.def_map(db);
88 let ast_id_map = db.ast_id_map(current_file_id);
94 module: module.local_id,
99 pub fn enter_expand<T: ast::AstNode>(
101 db: &dyn DefDatabase,
102 macro_call: ast::MacroCall,
103 ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
104 if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
105 cov_mark::hit!(your_stack_belongs_to_me);
106 return Ok(ExpandResult::str_err(
107 "reached recursion limit during macro expansion".into(),
111 let macro_call = InFile::new(self.current_file_id, ¯o_call);
114 |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
118 macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
119 err.get_or_insert(e);
121 let call_id = match call_id {
124 return Ok(ExpandResult { value: None, err });
129 err = db.macro_expand_error(call_id);
132 let file_id = call_id.as_file();
134 let raw_node = match db.parse_or_expand(file_id) {
137 // Only `None` if the macro expansion produced no usable AST.
139 log::warn!("no error despite `parse_or_expand` failing");
142 return Ok(ExpandResult::only_err(err.unwrap_or_else(|| {
143 mbe::ExpandError::Other("failed to parse macro invocation".into())
148 let node = match T::cast(raw_node) {
151 // This can happen without being an error, so only forward previous errors.
152 return Ok(ExpandResult { value: None, err });
156 log::debug!("macro expansion {:#?}", node.syntax());
158 self.recursion_limit += 1;
160 file_id: self.current_file_id,
161 ast_id_map: mem::take(&mut self.ast_id_map),
162 bomb: DropBomb::new("expansion mark dropped"),
164 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
165 self.current_file_id = file_id;
166 self.ast_id_map = db.ast_id_map(file_id);
168 Ok(ExpandResult { value: Some((mark, node)), err })
171 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
172 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
173 self.current_file_id = mark.file_id;
174 self.ast_id_map = mem::take(&mut mark.ast_id_map);
175 self.recursion_limit -= 1;
179 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
180 InFile { file_id: self.current_file_id, value }
183 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
184 self.cfg_expander.parse_attrs(db, owner)
187 pub(crate) fn cfg_options(&self) -> &CfgOptions {
188 &self.cfg_expander.cfg_options
191 pub fn current_file_id(&self) -> HirFileId {
195 fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
196 let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
197 Path::from_src(path, &ctx)
200 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
201 self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
204 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
205 let file_local_id = self.ast_id_map.ast_id(item);
206 AstId::new(self.current_file_id, file_local_id)
213 ast_id_map: Arc<AstIdMap>,
217 /// The body of an item (function, const etc.).
218 #[derive(Debug, Eq, PartialEq)]
220 pub exprs: Arena<Expr>,
221 pub pats: Arena<Pat>,
222 pub labels: Arena<Label>,
223 /// The patterns for the function's parameters. While the parameter types are
224 /// part of the function signature, the patterns are not (they don't change
225 /// the external type of the function).
227 /// If this `Body` is for the body of a constant, this will just be
229 pub params: Vec<PatId>,
230 /// The `ExprId` of the actual body expression.
231 pub body_expr: ExprId,
232 /// Block expressions in this body that may contain inner items.
233 block_scopes: Vec<BlockId>,
237 pub type ExprPtr = AstPtr<ast::Expr>;
238 pub type ExprSource = InFile<ExprPtr>;
240 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
241 pub type PatSource = InFile<PatPtr>;
243 pub type LabelPtr = AstPtr<ast::Label>;
244 pub type LabelSource = InFile<LabelPtr>;
245 /// An item body together with the mapping from syntax nodes to HIR expression
246 /// IDs. This is needed to go from e.g. a position in a file to the HIR
247 /// expression containing it; but for type inference etc., we want to operate on
248 /// a structure that is agnostic to the actual positions of expressions in the
249 /// file, so that we don't recompute types whenever some whitespace is typed.
251 /// One complication here is that, due to macro expansion, a single `Body` might
252 /// be spread across several files. So, for each ExprId and PatId, we record
253 /// both the HirFileId and the position inside the file. However, we only store
254 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
255 /// this properly for macros.
256 #[derive(Default, Debug, Eq, PartialEq)]
257 pub struct BodySourceMap {
258 expr_map: FxHashMap<ExprSource, ExprId>,
259 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
261 pat_map: FxHashMap<PatSource, PatId>,
262 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
264 label_map: FxHashMap<LabelSource, LabelId>,
265 label_map_back: ArenaMap<LabelId, LabelSource>,
267 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
268 /// Instead, we use id of expression (`92`) to identify the field.
269 field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
270 field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
272 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
274 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
275 /// the source map (since they're just as volatile).
276 diagnostics: Vec<diagnostics::BodyDiagnostic>,
279 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
280 pub struct SyntheticSyntax;
283 pub(crate) fn body_with_source_map_query(
284 db: &dyn DefDatabase,
286 ) -> (Arc<Body>, Arc<BodySourceMap>) {
287 let _p = profile::span("body_with_source_map_query");
288 let mut params = None;
290 let (file_id, module, body) = match def {
291 DefWithBodyId::FunctionId(f) => {
292 let f = f.lookup(db);
293 let src = f.source(db);
294 params = src.value.param_list();
295 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
297 DefWithBodyId::ConstId(c) => {
298 let c = c.lookup(db);
299 let src = c.source(db);
300 (src.file_id, c.module(db), src.value.body())
302 DefWithBodyId::StaticId(s) => {
303 let s = s.lookup(db);
304 let src = s.source(db);
305 (src.file_id, s.module(db), src.value.body())
308 let expander = Expander::new(db, file_id, module);
309 let (mut body, source_map) = Body::new(db, expander, params, body);
310 body.shrink_to_fit();
311 (Arc::new(body), Arc::new(source_map))
314 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
315 db.body_with_source_map(def).0
318 /// Returns an iterator over all block expressions in this body that define inner items.
321 db: &'a dyn DefDatabase,
322 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
325 .map(move |block| (*block, db.block_def_map(*block).expect("block ID without DefMap")))
329 db: &dyn DefDatabase,
331 params: Option<ast::ParamList>,
332 body: Option<ast::Expr>,
333 ) -> (Body, BodySourceMap) {
334 lower::lower(db, expander, params, body)
337 fn shrink_to_fit(&mut self) {
338 let Self { _c: _, body_expr: _, block_scopes, exprs, labels, params, pats } = self;
339 block_scopes.shrink_to_fit();
340 exprs.shrink_to_fit();
341 labels.shrink_to_fit();
342 params.shrink_to_fit();
343 pats.shrink_to_fit();
347 impl Index<ExprId> for Body {
350 fn index(&self, expr: ExprId) -> &Expr {
355 impl Index<PatId> for Body {
358 fn index(&self, pat: PatId) -> &Pat {
363 impl Index<LabelId> for Body {
366 fn index(&self, label: LabelId) -> &Label {
371 // FIXME: Change `node_` prefix to something more reasonable.
372 // Perhaps `expr_syntax` and `expr_id`?
374 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
375 self.expr_map_back[expr].clone()
378 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
379 let src = node.map(|it| AstPtr::new(it));
380 self.expr_map.get(&src).cloned()
383 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
384 let src = node.map(|it| AstPtr::new(it));
385 self.expansions.get(&src).cloned()
388 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
389 self.pat_map_back[pat].clone()
392 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
393 let src = node.map(|it| Either::Left(AstPtr::new(it)));
394 self.pat_map.get(&src).cloned()
397 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
398 let src = node.map(|it| Either::Right(AstPtr::new(it)));
399 self.pat_map.get(&src).cloned()
402 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
403 self.label_map_back[label].clone()
406 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
407 let src = node.map(|it| AstPtr::new(it));
408 self.label_map.get(&src).cloned()
411 pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
412 self.field_map_back[&expr].clone()
414 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
415 let src = node.map(|it| AstPtr::new(it));
416 self.field_map.get(&src).cloned()
419 pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
420 for diag in &self.diagnostics {