1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
9 use std::{ops::Index, sync::Arc};
12 use cfg::{CfgExpr, CfgOptions};
13 use drop_bomb::DropBomb;
15 use hir_expand::{hygiene::Hygiene, ExpandError, ExpandResult, HirFileId, InFile, MacroCallId};
16 use la_arena::{Arena, ArenaMap};
19 use rustc_hash::FxHashMap;
20 use syntax::{ast, AstPtr, SyntaxNodePtr};
23 attr::{Attrs, RawAttrs},
25 expr::{dummy_expr_id, Expr, ExprId, Label, LabelId, Pat, PatId},
26 item_scope::BuiltinShadowMode,
29 path::{ModPath, Path},
31 AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, MacroId, ModuleId,
35 pub use lower::LowerCtx;
37 /// A subset of Expander that only deals with cfg attributes. We only need it to
38 /// avoid cyclic queries in crate def map during enum processing.
40 pub(crate) struct CfgExpander {
41 cfg_options: CfgOptions,
48 cfg_expander: CfgExpander,
50 current_file_id: HirFileId,
51 module: LocalModuleId,
52 recursion_limit: usize,
58 current_file_id: HirFileId,
61 let hygiene = Hygiene::new(db.upcast(), current_file_id);
62 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
63 CfgExpander { cfg_options, hygiene, krate }
66 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
67 RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
70 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
71 let attrs = self.parse_attrs(db, owner);
72 attrs.is_cfg_enabled(&self.cfg_options)
77 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
78 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
79 let def_map = module.def_map(db);
84 module: module.local_id,
89 pub fn enter_expand<T: ast::AstNode>(
92 macro_call: ast::MacroCall,
93 ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
94 if self.recursion_limit(db).check(self.recursion_limit + 1).is_err() {
95 cov_mark::hit!(your_stack_belongs_to_me);
96 return Ok(ExpandResult::only_err(ExpandError::Other(
97 "reached recursion limit during macro expansion".into(),
101 let macro_call = InFile::new(self.current_file_id, ¯o_call);
104 |path| self.resolve_path_as_macro(db, &path).map(|it| macro_id_to_def_id(db, it));
108 macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
109 err.get_or_insert(e);
111 let call_id = match call_id {
114 return Ok(ExpandResult { value: None, err });
118 Ok(self.enter_expand_inner(db, call_id, err))
121 pub fn enter_expand_id<T: ast::AstNode>(
123 db: &dyn DefDatabase,
124 call_id: MacroCallId,
125 ) -> ExpandResult<Option<(Mark, T)>> {
126 self.enter_expand_inner(db, call_id, None)
129 fn enter_expand_inner<T: ast::AstNode>(
131 db: &dyn DefDatabase,
132 call_id: MacroCallId,
133 mut err: Option<ExpandError>,
134 ) -> ExpandResult<Option<(Mark, T)>> {
136 err = db.macro_expand_error(call_id);
139 let file_id = call_id.as_file();
141 let raw_node = match db.parse_or_expand(file_id) {
144 // Only `None` if the macro expansion produced no usable AST.
146 tracing::warn!("no error despite `parse_or_expand` failing");
149 return ExpandResult::only_err(err.unwrap_or_else(|| {
150 ExpandError::Other("failed to parse macro invocation".into())
155 let node = match T::cast(raw_node) {
158 // This can happen without being an error, so only forward previous errors.
159 return ExpandResult { value: None, err };
163 tracing::debug!("macro expansion {:#?}", node.syntax());
165 self.recursion_limit += 1;
167 Mark { file_id: self.current_file_id, bomb: DropBomb::new("expansion mark dropped") };
168 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
169 self.current_file_id = file_id;
171 ExpandResult { value: Some((mark, node)), err }
174 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
175 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
176 self.current_file_id = mark.file_id;
177 self.recursion_limit -= 1;
181 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
182 InFile { file_id: self.current_file_id, value }
185 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
186 self.cfg_expander.parse_attrs(db, owner)
189 pub(crate) fn cfg_options(&self) -> &CfgOptions {
190 &self.cfg_expander.cfg_options
193 pub fn current_file_id(&self) -> HirFileId {
197 fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
198 let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
199 Path::from_src(path, &ctx)
202 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroId> {
203 self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
206 fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
207 let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
210 return Limit::new(limit);
212 // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
214 return Limit::new(std::cmp::min(32, limit));
224 /// The body of an item (function, const etc.).
225 #[derive(Debug, Eq, PartialEq)]
227 pub exprs: Arena<Expr>,
228 pub pats: Arena<Pat>,
229 pub or_pats: FxHashMap<PatId, Arc<[PatId]>>,
230 pub labels: Arena<Label>,
231 /// The patterns for the function's parameters. While the parameter types are
232 /// part of the function signature, the patterns are not (they don't change
233 /// the external type of the function).
235 /// If this `Body` is for the body of a constant, this will just be
237 pub params: Vec<PatId>,
238 /// The `ExprId` of the actual body expression.
239 pub body_expr: ExprId,
240 /// Block expressions in this body that may contain inner items.
241 block_scopes: Vec<BlockId>,
245 pub type ExprPtr = AstPtr<ast::Expr>;
246 pub type ExprSource = InFile<ExprPtr>;
248 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
249 pub type PatSource = InFile<PatPtr>;
251 pub type LabelPtr = AstPtr<ast::Label>;
252 pub type LabelSource = InFile<LabelPtr>;
253 /// An item body together with the mapping from syntax nodes to HIR expression
254 /// IDs. This is needed to go from e.g. a position in a file to the HIR
255 /// expression containing it; but for type inference etc., we want to operate on
256 /// a structure that is agnostic to the actual positions of expressions in the
257 /// file, so that we don't recompute types whenever some whitespace is typed.
259 /// One complication here is that, due to macro expansion, a single `Body` might
260 /// be spread across several files. So, for each ExprId and PatId, we record
261 /// both the HirFileId and the position inside the file. However, we only store
262 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
263 /// this properly for macros.
264 #[derive(Default, Debug, Eq, PartialEq)]
265 pub struct BodySourceMap {
266 expr_map: FxHashMap<ExprSource, ExprId>,
267 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
269 pat_map: FxHashMap<PatSource, PatId>,
270 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
272 label_map: FxHashMap<LabelSource, LabelId>,
273 label_map_back: ArenaMap<LabelId, LabelSource>,
275 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
276 /// Instead, we use id of expression (`92`) to identify the field.
277 field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
278 field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
280 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
282 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
283 /// the source map (since they're just as volatile).
284 diagnostics: Vec<BodyDiagnostic>,
287 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
288 pub struct SyntheticSyntax;
290 #[derive(Debug, Eq, PartialEq)]
291 pub enum BodyDiagnostic {
292 InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
293 MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
294 UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>>, krate: CrateId },
295 UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
299 pub(crate) fn body_with_source_map_query(
300 db: &dyn DefDatabase,
302 ) -> (Arc<Body>, Arc<BodySourceMap>) {
303 let _p = profile::span("body_with_source_map_query");
304 let mut params = None;
306 let (file_id, module, body) = match def {
307 DefWithBodyId::FunctionId(f) => {
308 let f = f.lookup(db);
309 let src = f.source(db);
310 params = src.value.param_list();
311 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
313 DefWithBodyId::ConstId(c) => {
314 let c = c.lookup(db);
315 let src = c.source(db);
316 (src.file_id, c.module(db), src.value.body())
318 DefWithBodyId::StaticId(s) => {
319 let s = s.lookup(db);
320 let src = s.source(db);
321 (src.file_id, s.module(db), src.value.body())
324 let expander = Expander::new(db, file_id, module);
325 let (mut body, source_map) = Body::new(db, expander, params, body);
326 body.shrink_to_fit();
327 (Arc::new(body), Arc::new(source_map))
330 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
331 db.body_with_source_map(def).0
334 /// Returns an iterator over all block expressions in this body that define inner items.
337 db: &'a dyn DefDatabase,
338 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
341 .map(move |&block| (block, db.block_def_map(block).expect("block ID without DefMap")))
344 pub fn pattern_representative(&self, pat: PatId) -> PatId {
345 self.or_pats.get(&pat).and_then(|pats| pats.first().copied()).unwrap_or(pat)
348 /// Retrieves all ident patterns this pattern shares the ident with.
349 pub fn ident_patterns_for<'slf>(&'slf self, pat: &'slf PatId) -> &'slf [PatId] {
350 match self.or_pats.get(pat) {
351 Some(pats) => &**pats,
352 None => std::slice::from_ref(pat),
356 pub fn pretty_print(&self, db: &dyn DefDatabase, owner: DefWithBodyId) -> String {
357 pretty::print_body_hir(db, self, owner)
361 db: &dyn DefDatabase,
363 params: Option<ast::ParamList>,
364 body: Option<ast::Expr>,
365 ) -> (Body, BodySourceMap) {
366 lower::lower(db, expander, params, body)
369 fn shrink_to_fit(&mut self) {
370 let Self { _c: _, body_expr: _, block_scopes, or_pats, exprs, labels, params, pats } = self;
371 block_scopes.shrink_to_fit();
372 or_pats.shrink_to_fit();
373 exprs.shrink_to_fit();
374 labels.shrink_to_fit();
375 params.shrink_to_fit();
376 pats.shrink_to_fit();
380 impl Default for Body {
381 fn default() -> Self {
383 body_expr: dummy_expr_id(),
384 exprs: Default::default(),
385 pats: Default::default(),
386 or_pats: Default::default(),
387 labels: Default::default(),
388 params: Default::default(),
389 block_scopes: Default::default(),
390 _c: Default::default(),
395 impl Index<ExprId> for Body {
398 fn index(&self, expr: ExprId) -> &Expr {
403 impl Index<PatId> for Body {
406 fn index(&self, pat: PatId) -> &Pat {
411 impl Index<LabelId> for Body {
414 fn index(&self, label: LabelId) -> &Label {
419 // FIXME: Change `node_` prefix to something more reasonable.
420 // Perhaps `expr_syntax` and `expr_id`?
422 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
423 self.expr_map_back[expr].clone()
426 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
427 let src = node.map(AstPtr::new);
428 self.expr_map.get(&src).cloned()
431 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
432 let src = node.map(AstPtr::new);
433 self.expansions.get(&src).cloned()
436 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
437 self.pat_map_back[pat].clone()
440 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
441 let src = node.map(|it| Either::Left(AstPtr::new(it)));
442 self.pat_map.get(&src).cloned()
445 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
446 let src = node.map(|it| Either::Right(AstPtr::new(it)));
447 self.pat_map.get(&src).cloned()
450 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
451 self.label_map_back[label].clone()
454 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
455 let src = node.map(AstPtr::new);
456 self.label_map.get(&src).cloned()
459 pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
460 self.field_map_back[&expr].clone()
462 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
463 let src = node.map(AstPtr::new);
464 self.field_map.get(&src).cloned()
467 pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroExpr>) -> Option<ExprId> {
468 let src = node.map(AstPtr::new).map(AstPtr::upcast::<ast::MacroExpr>).map(AstPtr::upcast);
469 self.expr_map.get(&src).copied()
472 /// Get a reference to the body source map's diagnostics.
473 pub fn diagnostics(&self) -> &[BodyDiagnostic] {