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},
30 src::{HasChildSource, HasSource},
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>;
254 pub type FieldPtr = AstPtr<ast::RecordExprField>;
255 pub type FieldSource = InFile<FieldPtr>;
257 /// An item body together with the mapping from syntax nodes to HIR expression
258 /// IDs. This is needed to go from e.g. a position in a file to the HIR
259 /// expression containing it; but for type inference etc., we want to operate on
260 /// a structure that is agnostic to the actual positions of expressions in the
261 /// file, so that we don't recompute types whenever some whitespace is typed.
263 /// One complication here is that, due to macro expansion, a single `Body` might
264 /// be spread across several files. So, for each ExprId and PatId, we record
265 /// both the HirFileId and the position inside the file. However, we only store
266 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
267 /// this properly for macros.
268 #[derive(Default, Debug, Eq, PartialEq)]
269 pub struct BodySourceMap {
270 expr_map: FxHashMap<ExprSource, ExprId>,
271 expr_map_back: ArenaMap<ExprId, ExprSource>,
273 pat_map: FxHashMap<PatSource, PatId>,
274 pat_map_back: ArenaMap<PatId, PatSource>,
276 label_map: FxHashMap<LabelSource, LabelId>,
277 label_map_back: ArenaMap<LabelId, LabelSource>,
279 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
280 /// Instead, we use id of expression (`92`) to identify the field.
281 field_map: FxHashMap<FieldSource, ExprId>,
282 field_map_back: FxHashMap<ExprId, FieldSource>,
284 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
286 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
287 /// the source map (since they're just as volatile).
288 diagnostics: Vec<BodyDiagnostic>,
291 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
292 pub struct SyntheticSyntax;
294 #[derive(Debug, Eq, PartialEq)]
295 pub enum BodyDiagnostic {
296 InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
297 MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
298 UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>>, krate: CrateId },
299 UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
303 pub(crate) fn body_with_source_map_query(
304 db: &dyn DefDatabase,
306 ) -> (Arc<Body>, Arc<BodySourceMap>) {
307 let _p = profile::span("body_with_source_map_query");
308 let mut params = None;
310 let (file_id, module, body) = match def {
311 DefWithBodyId::FunctionId(f) => {
312 let f = f.lookup(db);
313 let src = f.source(db);
314 params = src.value.param_list().map(|param_list| {
315 let item_tree = f.id.item_tree(db);
316 let func = &item_tree[f.id.value];
317 let krate = f.container.module(db).krate;
318 let crate_graph = db.crate_graph();
321 func.params.clone().map(move |param| {
323 .attrs(db, krate, param.into())
324 .is_cfg_enabled(&crate_graph[krate].cfg_options)
328 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
330 DefWithBodyId::ConstId(c) => {
331 let c = c.lookup(db);
332 let src = c.source(db);
333 (src.file_id, c.module(db), src.value.body())
335 DefWithBodyId::StaticId(s) => {
336 let s = s.lookup(db);
337 let src = s.source(db);
338 (src.file_id, s.module(db), src.value.body())
340 DefWithBodyId::VariantId(v) => {
341 let e = v.parent.lookup(db);
342 let src = v.parent.child_source(db);
343 let variant = &src.value[v.local_id];
344 (src.file_id, e.container, variant.expr())
347 let expander = Expander::new(db, file_id, module);
348 let (mut body, source_map) = Body::new(db, expander, params, body);
349 body.shrink_to_fit();
351 (Arc::new(body), Arc::new(source_map))
354 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
355 db.body_with_source_map(def).0
358 /// Returns an iterator over all block expressions in this body that define inner items.
361 db: &'a dyn DefDatabase,
362 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
365 .map(move |&block| (block, db.block_def_map(block).expect("block ID without DefMap")))
368 pub fn pattern_representative(&self, pat: PatId) -> PatId {
369 self.or_pats.get(&pat).and_then(|pats| pats.first().copied()).unwrap_or(pat)
372 /// Retrieves all ident patterns this pattern shares the ident with.
373 pub fn ident_patterns_for<'slf>(&'slf self, pat: &'slf PatId) -> &'slf [PatId] {
374 match self.or_pats.get(pat) {
375 Some(pats) => &**pats,
376 None => std::slice::from_ref(pat),
380 pub fn pretty_print(&self, db: &dyn DefDatabase, owner: DefWithBodyId) -> String {
381 pretty::print_body_hir(db, self, owner)
385 db: &dyn DefDatabase,
387 params: Option<(ast::ParamList, impl Iterator<Item = bool>)>,
388 body: Option<ast::Expr>,
389 ) -> (Body, BodySourceMap) {
390 lower::lower(db, expander, params, body)
393 fn shrink_to_fit(&mut self) {
394 let Self { _c: _, body_expr: _, block_scopes, or_pats, exprs, labels, params, pats } = self;
395 block_scopes.shrink_to_fit();
396 or_pats.shrink_to_fit();
397 exprs.shrink_to_fit();
398 labels.shrink_to_fit();
399 params.shrink_to_fit();
400 pats.shrink_to_fit();
404 impl Default for Body {
405 fn default() -> Self {
407 body_expr: dummy_expr_id(),
408 exprs: Default::default(),
409 pats: Default::default(),
410 or_pats: Default::default(),
411 labels: Default::default(),
412 params: Default::default(),
413 block_scopes: Default::default(),
414 _c: Default::default(),
419 impl Index<ExprId> for Body {
422 fn index(&self, expr: ExprId) -> &Expr {
427 impl Index<PatId> for Body {
430 fn index(&self, pat: PatId) -> &Pat {
435 impl Index<LabelId> for Body {
438 fn index(&self, label: LabelId) -> &Label {
443 // FIXME: Change `node_` prefix to something more reasonable.
444 // Perhaps `expr_syntax` and `expr_id`?
446 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
447 self.expr_map_back.get(expr).cloned().ok_or(SyntheticSyntax)
450 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
451 let src = node.map(AstPtr::new);
452 self.expr_map.get(&src).cloned()
455 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
456 let src = node.map(AstPtr::new);
457 self.expansions.get(&src).cloned()
460 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
461 self.pat_map_back.get(pat).cloned().ok_or(SyntheticSyntax)
464 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
465 let src = node.map(|it| Either::Left(AstPtr::new(it)));
466 self.pat_map.get(&src).cloned()
469 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
470 let src = node.map(|it| Either::Right(AstPtr::new(it)));
471 self.pat_map.get(&src).cloned()
474 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
475 self.label_map_back[label].clone()
478 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
479 let src = node.map(AstPtr::new);
480 self.label_map.get(&src).cloned()
483 pub fn field_syntax(&self, expr: ExprId) -> FieldSource {
484 self.field_map_back[&expr].clone()
487 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
488 let src = node.map(AstPtr::new);
489 self.field_map.get(&src).cloned()
492 pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroExpr>) -> Option<ExprId> {
493 let src = node.map(AstPtr::new).map(AstPtr::upcast::<ast::MacroExpr>).map(AstPtr::upcast);
494 self.expr_map.get(&src).copied()
497 /// Get a reference to the body source map's diagnostics.
498 pub fn diagnostics(&self) -> &[BodyDiagnostic] {