1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
8 use std::{mem, ops::Index, sync::Arc};
11 use cfg::{CfgExpr, CfgOptions};
12 use drop_bomb::DropBomb;
15 ast_id_map::AstIdMap, hygiene::Hygiene, AstId, ExpandError, ExpandResult, HirFileId, InFile,
16 MacroCallId, MacroDefId,
18 use la_arena::{Arena, ArenaMap};
21 use rustc_hash::FxHashMap;
22 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
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,
60 current_file_id: HirFileId,
63 let hygiene = Hygiene::new(db.upcast(), current_file_id);
64 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
65 CfgExpander { cfg_options, hygiene, krate }
68 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
69 RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
72 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
73 let attrs = self.parse_attrs(db, owner);
74 attrs.is_cfg_enabled(&self.cfg_options)
79 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
80 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
81 let def_map = module.def_map(db);
82 let ast_id_map = db.ast_id_map(current_file_id);
88 module: module.local_id,
93 pub fn enter_expand<T: ast::AstNode>(
96 macro_call: ast::MacroCall,
97 ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
98 if self.recursion_limit(db).check(self.recursion_limit + 1).is_err() {
99 cov_mark::hit!(your_stack_belongs_to_me);
100 return Ok(ExpandResult::str_err(
101 "reached recursion limit during macro expansion".into(),
105 let macro_call = InFile::new(self.current_file_id, ¯o_call);
108 |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
112 macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
113 err.get_or_insert(e);
115 let call_id = match call_id {
118 return Ok(ExpandResult { value: None, err });
122 Ok(self.enter_expand_inner(db, call_id, err))
125 pub fn enter_expand_id<T: ast::AstNode>(
127 db: &dyn DefDatabase,
128 call_id: MacroCallId,
129 ) -> ExpandResult<Option<(Mark, T)>> {
130 self.enter_expand_inner(db, call_id, None)
133 fn enter_expand_inner<T: ast::AstNode>(
135 db: &dyn DefDatabase,
136 call_id: MacroCallId,
137 mut err: Option<ExpandError>,
138 ) -> ExpandResult<Option<(Mark, T)>> {
140 err = db.macro_expand_error(call_id);
143 let file_id = call_id.as_file();
145 let raw_node = match db.parse_or_expand(file_id) {
148 // Only `None` if the macro expansion produced no usable AST.
150 tracing::warn!("no error despite `parse_or_expand` failing");
153 return ExpandResult::only_err(err.unwrap_or_else(|| {
154 mbe::ExpandError::Other("failed to parse macro invocation".into())
159 let node = match T::cast(raw_node) {
162 // This can happen without being an error, so only forward previous errors.
163 return ExpandResult { value: None, err };
167 tracing::debug!("macro expansion {:#?}", node.syntax());
169 self.recursion_limit += 1;
171 file_id: self.current_file_id,
172 ast_id_map: mem::take(&mut self.ast_id_map),
173 bomb: DropBomb::new("expansion mark dropped"),
175 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
176 self.current_file_id = file_id;
177 self.ast_id_map = db.ast_id_map(file_id);
179 ExpandResult { value: Some((mark, node)), err }
182 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
183 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
184 self.current_file_id = mark.file_id;
185 self.ast_id_map = mem::take(&mut mark.ast_id_map);
186 self.recursion_limit -= 1;
190 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
191 InFile { file_id: self.current_file_id, value }
194 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
195 self.cfg_expander.parse_attrs(db, owner)
198 pub(crate) fn cfg_options(&self) -> &CfgOptions {
199 &self.cfg_expander.cfg_options
202 pub fn current_file_id(&self) -> HirFileId {
206 fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
207 let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
208 Path::from_src(path, &ctx)
211 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
212 self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
215 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
216 let file_local_id = self.ast_id_map.ast_id(item);
217 AstId::new(self.current_file_id, file_local_id)
220 fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
221 let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
224 return Limit::new(limit);
226 // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
228 return Limit::new(std::cmp::min(32, limit));
235 ast_id_map: Arc<AstIdMap>,
239 /// The body of an item (function, const etc.).
240 #[derive(Debug, Eq, PartialEq)]
242 pub exprs: Arena<Expr>,
243 pub pats: Arena<Pat>,
244 pub labels: Arena<Label>,
245 /// The patterns for the function's parameters. While the parameter types are
246 /// part of the function signature, the patterns are not (they don't change
247 /// the external type of the function).
249 /// If this `Body` is for the body of a constant, this will just be
251 pub params: Vec<PatId>,
252 /// The `ExprId` of the actual body expression.
253 pub body_expr: ExprId,
254 /// Block expressions in this body that may contain inner items.
255 block_scopes: Vec<BlockId>,
259 pub type ExprPtr = AstPtr<ast::Expr>;
260 pub type ExprSource = InFile<ExprPtr>;
262 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
263 pub type PatSource = InFile<PatPtr>;
265 pub type LabelPtr = AstPtr<ast::Label>;
266 pub type LabelSource = InFile<LabelPtr>;
267 /// An item body together with the mapping from syntax nodes to HIR expression
268 /// IDs. This is needed to go from e.g. a position in a file to the HIR
269 /// expression containing it; but for type inference etc., we want to operate on
270 /// a structure that is agnostic to the actual positions of expressions in the
271 /// file, so that we don't recompute types whenever some whitespace is typed.
273 /// One complication here is that, due to macro expansion, a single `Body` might
274 /// be spread across several files. So, for each ExprId and PatId, we record
275 /// both the HirFileId and the position inside the file. However, we only store
276 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
277 /// this properly for macros.
278 #[derive(Default, Debug, Eq, PartialEq)]
279 pub struct BodySourceMap {
280 expr_map: FxHashMap<ExprSource, ExprId>,
281 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
283 pat_map: FxHashMap<PatSource, PatId>,
284 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
286 label_map: FxHashMap<LabelSource, LabelId>,
287 label_map_back: ArenaMap<LabelId, LabelSource>,
289 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
290 /// Instead, we use id of expression (`92`) to identify the field.
291 field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
292 field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
294 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
296 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
297 /// the source map (since they're just as volatile).
298 diagnostics: Vec<BodyDiagnostic>,
301 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
302 pub struct SyntheticSyntax;
304 #[derive(Debug, Eq, PartialEq)]
305 pub enum BodyDiagnostic {
306 InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
307 MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
308 UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
309 UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
313 pub(crate) fn body_with_source_map_query(
314 db: &dyn DefDatabase,
316 ) -> (Arc<Body>, Arc<BodySourceMap>) {
317 let _p = profile::span("body_with_source_map_query");
318 let mut params = None;
320 let (file_id, module, body) = match def {
321 DefWithBodyId::FunctionId(f) => {
322 let f = f.lookup(db);
323 let src = f.source(db);
324 params = src.value.param_list();
325 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
327 DefWithBodyId::ConstId(c) => {
328 let c = c.lookup(db);
329 let src = c.source(db);
330 (src.file_id, c.module(db), src.value.body())
332 DefWithBodyId::StaticId(s) => {
333 let s = s.lookup(db);
334 let src = s.source(db);
335 (src.file_id, s.module(db), src.value.body())
338 let expander = Expander::new(db, file_id, module);
339 let (mut body, source_map) = Body::new(db, expander, params, body);
340 body.shrink_to_fit();
341 (Arc::new(body), Arc::new(source_map))
344 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
345 db.body_with_source_map(def).0
348 /// Returns an iterator over all block expressions in this body that define inner items.
351 db: &'a dyn DefDatabase,
352 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
355 .map(move |block| (*block, db.block_def_map(*block).expect("block ID without DefMap")))
359 db: &dyn DefDatabase,
361 params: Option<ast::ParamList>,
362 body: Option<ast::Expr>,
363 ) -> (Body, BodySourceMap) {
364 lower::lower(db, expander, params, body)
367 fn shrink_to_fit(&mut self) {
368 let Self { _c: _, body_expr: _, block_scopes, exprs, labels, params, pats } = self;
369 block_scopes.shrink_to_fit();
370 exprs.shrink_to_fit();
371 labels.shrink_to_fit();
372 params.shrink_to_fit();
373 pats.shrink_to_fit();
377 impl Index<ExprId> for Body {
380 fn index(&self, expr: ExprId) -> &Expr {
385 impl Index<PatId> for Body {
388 fn index(&self, pat: PatId) -> &Pat {
393 impl Index<LabelId> for Body {
396 fn index(&self, label: LabelId) -> &Label {
401 // FIXME: Change `node_` prefix to something more reasonable.
402 // Perhaps `expr_syntax` and `expr_id`?
404 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
405 self.expr_map_back[expr].clone()
408 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
409 let src = node.map(|it| AstPtr::new(it));
410 self.expr_map.get(&src).cloned()
413 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
414 let src = node.map(|it| AstPtr::new(it));
415 self.expansions.get(&src).cloned()
418 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
419 self.pat_map_back[pat].clone()
422 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
423 let src = node.map(|it| Either::Left(AstPtr::new(it)));
424 self.pat_map.get(&src).cloned()
427 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
428 let src = node.map(|it| Either::Right(AstPtr::new(it)));
429 self.pat_map.get(&src).cloned()
432 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
433 self.label_map_back[label].clone()
436 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
437 let src = node.map(|it| AstPtr::new(it));
438 self.label_map.get(&src).cloned()
441 pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
442 self.field_map_back[&expr].clone()
444 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
445 let src = node.map(|it| AstPtr::new(it));
446 self.field_map.get(&src).cloned()
449 /// Get a reference to the body source map's diagnostics.
450 pub fn diagnostics(&self) -> &[BodyDiagnostic] {