]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/body.rs
Rollup merge of #103204 - jyn514:autolabels, r=Mark-Simulacrum
[rust.git] / src / tools / rust-analyzer / crates / hir-def / src / body.rs
1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
2 //! consts.
3 mod lower;
4 #[cfg(test)]
5 mod tests;
6 pub mod scope;
7 mod pretty;
8
9 use std::{ops::Index, sync::Arc};
10
11 use base_db::CrateId;
12 use cfg::{CfgExpr, CfgOptions};
13 use drop_bomb::DropBomb;
14 use either::Either;
15 use hir_expand::{hygiene::Hygiene, ExpandError, ExpandResult, HirFileId, InFile, MacroCallId};
16 use la_arena::{Arena, ArenaMap};
17 use limit::Limit;
18 use profile::Count;
19 use rustc_hash::FxHashMap;
20 use syntax::{ast, AstPtr, SyntaxNodePtr};
21
22 use crate::{
23     attr::{Attrs, RawAttrs},
24     db::DefDatabase,
25     expr::{dummy_expr_id, Expr, ExprId, Label, LabelId, Pat, PatId},
26     item_scope::BuiltinShadowMode,
27     macro_id_to_def_id,
28     nameres::DefMap,
29     path::{ModPath, Path},
30     src::{HasChildSource, HasSource},
31     AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, MacroId, ModuleId,
32     UnresolvedMacro,
33 };
34
35 pub use lower::LowerCtx;
36
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.
39 #[derive(Debug)]
40 pub(crate) struct CfgExpander {
41     cfg_options: CfgOptions,
42     hygiene: Hygiene,
43     krate: CrateId,
44 }
45
46 #[derive(Debug)]
47 pub struct Expander {
48     cfg_expander: CfgExpander,
49     def_map: Arc<DefMap>,
50     current_file_id: HirFileId,
51     module: LocalModuleId,
52     recursion_limit: usize,
53 }
54
55 impl CfgExpander {
56     pub(crate) fn new(
57         db: &dyn DefDatabase,
58         current_file_id: HirFileId,
59         krate: CrateId,
60     ) -> CfgExpander {
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 }
64     }
65
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)
68     }
69
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)
73     }
74 }
75
76 impl Expander {
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);
80         Expander {
81             cfg_expander,
82             def_map,
83             current_file_id,
84             module: module.local_id,
85             recursion_limit: 0,
86         }
87     }
88
89     pub fn enter_expand<T: ast::AstNode>(
90         &mut self,
91         db: &dyn DefDatabase,
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(),
98             )));
99         }
100
101         let macro_call = InFile::new(self.current_file_id, &macro_call);
102
103         let resolver =
104             |path| self.resolve_path_as_macro(db, &path).map(|it| macro_id_to_def_id(db, it));
105
106         let mut err = None;
107         let call_id =
108             macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
109                 err.get_or_insert(e);
110             })?;
111         let call_id = match call_id {
112             Ok(it) => it,
113             Err(_) => {
114                 return Ok(ExpandResult { value: None, err });
115             }
116         };
117
118         Ok(self.enter_expand_inner(db, call_id, err))
119     }
120
121     pub fn enter_expand_id<T: ast::AstNode>(
122         &mut self,
123         db: &dyn DefDatabase,
124         call_id: MacroCallId,
125     ) -> ExpandResult<Option<(Mark, T)>> {
126         self.enter_expand_inner(db, call_id, None)
127     }
128
129     fn enter_expand_inner<T: ast::AstNode>(
130         &mut self,
131         db: &dyn DefDatabase,
132         call_id: MacroCallId,
133         mut err: Option<ExpandError>,
134     ) -> ExpandResult<Option<(Mark, T)>> {
135         if err.is_none() {
136             err = db.macro_expand_error(call_id);
137         }
138
139         let file_id = call_id.as_file();
140
141         let raw_node = match db.parse_or_expand(file_id) {
142             Some(it) => it,
143             None => {
144                 // Only `None` if the macro expansion produced no usable AST.
145                 if err.is_none() {
146                     tracing::warn!("no error despite `parse_or_expand` failing");
147                 }
148
149                 return ExpandResult::only_err(err.unwrap_or_else(|| {
150                     ExpandError::Other("failed to parse macro invocation".into())
151                 }));
152             }
153         };
154
155         let node = match T::cast(raw_node) {
156             Some(it) => it,
157             None => {
158                 // This can happen without being an error, so only forward previous errors.
159                 return ExpandResult { value: None, err };
160             }
161         };
162
163         tracing::debug!("macro expansion {:#?}", node.syntax());
164
165         self.recursion_limit += 1;
166         let mark =
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;
170
171         ExpandResult { value: Some((mark, node)), err }
172     }
173
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;
178         mark.bomb.defuse();
179     }
180
181     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
182         InFile { file_id: self.current_file_id, value }
183     }
184
185     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
186         self.cfg_expander.parse_attrs(db, owner)
187     }
188
189     pub(crate) fn cfg_options(&self) -> &CfgOptions {
190         &self.cfg_expander.cfg_options
191     }
192
193     pub fn current_file_id(&self) -> HirFileId {
194         self.current_file_id
195     }
196
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)
200     }
201
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()
204     }
205
206     fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
207         let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
208
209         #[cfg(not(test))]
210         return Limit::new(limit);
211
212         // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
213         #[cfg(test)]
214         return Limit::new(std::cmp::min(32, limit));
215     }
216 }
217
218 #[derive(Debug)]
219 pub struct Mark {
220     file_id: HirFileId,
221     bomb: DropBomb,
222 }
223
224 /// The body of an item (function, const etc.).
225 #[derive(Debug, Eq, PartialEq)]
226 pub struct Body {
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).
234     ///
235     /// If this `Body` is for the body of a constant, this will just be
236     /// empty.
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>,
242     _c: Count<Self>,
243 }
244
245 pub type ExprPtr = AstPtr<ast::Expr>;
246 pub type ExprSource = InFile<ExprPtr>;
247
248 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
249 pub type PatSource = InFile<PatPtr>;
250
251 pub type LabelPtr = AstPtr<ast::Label>;
252 pub type LabelSource = InFile<LabelPtr>;
253
254 pub type FieldPtr = AstPtr<ast::RecordExprField>;
255 pub type FieldSource = InFile<FieldPtr>;
256
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.
262 ///
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>,
272
273     pat_map: FxHashMap<PatSource, PatId>,
274     pat_map_back: ArenaMap<PatId, PatSource>,
275
276     label_map: FxHashMap<LabelSource, LabelId>,
277     label_map_back: ArenaMap<LabelId, LabelSource>,
278
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>,
283
284     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
285
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>,
289 }
290
291 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
292 pub struct SyntheticSyntax;
293
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 },
300 }
301
302 impl Body {
303     pub(crate) fn body_with_source_map_query(
304         db: &dyn DefDatabase,
305         def: DefWithBodyId,
306     ) -> (Arc<Body>, Arc<BodySourceMap>) {
307         let _p = profile::span("body_with_source_map_query");
308         let mut params = None;
309
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();
319                     (
320                         param_list,
321                         func.params.clone().map(move |param| {
322                             item_tree
323                                 .attrs(db, krate, param.into())
324                                 .is_cfg_enabled(&crate_graph[krate].cfg_options)
325                         }),
326                     )
327                 });
328                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
329             }
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())
334             }
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())
339             }
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())
345             }
346         };
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();
350
351         (Arc::new(body), Arc::new(source_map))
352     }
353
354     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
355         db.body_with_source_map(def).0
356     }
357
358     /// Returns an iterator over all block expressions in this body that define inner items.
359     pub fn blocks<'a>(
360         &'a self,
361         db: &'a dyn DefDatabase,
362     ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
363         self.block_scopes
364             .iter()
365             .map(move |&block| (block, db.block_def_map(block).expect("block ID without DefMap")))
366     }
367
368     pub fn pattern_representative(&self, pat: PatId) -> PatId {
369         self.or_pats.get(&pat).and_then(|pats| pats.first().copied()).unwrap_or(pat)
370     }
371
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),
377         }
378     }
379
380     pub fn pretty_print(&self, db: &dyn DefDatabase, owner: DefWithBodyId) -> String {
381         pretty::print_body_hir(db, self, owner)
382     }
383
384     fn new(
385         db: &dyn DefDatabase,
386         expander: Expander,
387         params: Option<(ast::ParamList, impl Iterator<Item = bool>)>,
388         body: Option<ast::Expr>,
389     ) -> (Body, BodySourceMap) {
390         lower::lower(db, expander, params, body)
391     }
392
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();
401     }
402 }
403
404 impl Default for Body {
405     fn default() -> Self {
406         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(),
415         }
416     }
417 }
418
419 impl Index<ExprId> for Body {
420     type Output = Expr;
421
422     fn index(&self, expr: ExprId) -> &Expr {
423         &self.exprs[expr]
424     }
425 }
426
427 impl Index<PatId> for Body {
428     type Output = Pat;
429
430     fn index(&self, pat: PatId) -> &Pat {
431         &self.pats[pat]
432     }
433 }
434
435 impl Index<LabelId> for Body {
436     type Output = Label;
437
438     fn index(&self, label: LabelId) -> &Label {
439         &self.labels[label]
440     }
441 }
442
443 // FIXME: Change `node_` prefix to something more reasonable.
444 // Perhaps `expr_syntax` and `expr_id`?
445 impl BodySourceMap {
446     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
447         self.expr_map_back.get(expr).cloned().ok_or(SyntheticSyntax)
448     }
449
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()
453     }
454
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()
458     }
459
460     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
461         self.pat_map_back.get(pat).cloned().ok_or(SyntheticSyntax)
462     }
463
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()
467     }
468
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()
472     }
473
474     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
475         self.label_map_back[label].clone()
476     }
477
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()
481     }
482
483     pub fn field_syntax(&self, expr: ExprId) -> FieldSource {
484         self.field_map_back[&expr].clone()
485     }
486
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()
490     }
491
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()
495     }
496
497     /// Get a reference to the body source map's diagnostics.
498     pub fn diagnostics(&self) -> &[BodyDiagnostic] {
499         &self.diagnostics
500     }
501 }