]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/body.rs
:arrow_up: rust-analyzer
[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::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 /// 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.
258 ///
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>>,
268
269     pat_map: FxHashMap<PatSource, PatId>,
270     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
271
272     label_map: FxHashMap<LabelSource, LabelId>,
273     label_map_back: ArenaMap<LabelId, LabelSource>,
274
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>>>,
279
280     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
281
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>,
285 }
286
287 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
288 pub struct SyntheticSyntax;
289
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 },
296 }
297
298 impl Body {
299     pub(crate) fn body_with_source_map_query(
300         db: &dyn DefDatabase,
301         def: DefWithBodyId,
302     ) -> (Arc<Body>, Arc<BodySourceMap>) {
303         let _p = profile::span("body_with_source_map_query");
304         let mut params = None;
305
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))
312             }
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())
317             }
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())
322             }
323         };
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))
328     }
329
330     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
331         db.body_with_source_map(def).0
332     }
333
334     /// Returns an iterator over all block expressions in this body that define inner items.
335     pub fn blocks<'a>(
336         &'a self,
337         db: &'a dyn DefDatabase,
338     ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
339         self.block_scopes
340             .iter()
341             .map(move |&block| (block, db.block_def_map(block).expect("block ID without DefMap")))
342     }
343
344     pub fn pattern_representative(&self, pat: PatId) -> PatId {
345         self.or_pats.get(&pat).and_then(|pats| pats.first().copied()).unwrap_or(pat)
346     }
347
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),
353         }
354     }
355
356     pub fn pretty_print(&self, db: &dyn DefDatabase, owner: DefWithBodyId) -> String {
357         pretty::print_body_hir(db, self, owner)
358     }
359
360     fn new(
361         db: &dyn DefDatabase,
362         expander: Expander,
363         params: Option<ast::ParamList>,
364         body: Option<ast::Expr>,
365     ) -> (Body, BodySourceMap) {
366         lower::lower(db, expander, params, body)
367     }
368
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();
377     }
378 }
379
380 impl Default for Body {
381     fn default() -> Self {
382         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(),
391         }
392     }
393 }
394
395 impl Index<ExprId> for Body {
396     type Output = Expr;
397
398     fn index(&self, expr: ExprId) -> &Expr {
399         &self.exprs[expr]
400     }
401 }
402
403 impl Index<PatId> for Body {
404     type Output = Pat;
405
406     fn index(&self, pat: PatId) -> &Pat {
407         &self.pats[pat]
408     }
409 }
410
411 impl Index<LabelId> for Body {
412     type Output = Label;
413
414     fn index(&self, label: LabelId) -> &Label {
415         &self.labels[label]
416     }
417 }
418
419 // FIXME: Change `node_` prefix to something more reasonable.
420 // Perhaps `expr_syntax` and `expr_id`?
421 impl BodySourceMap {
422     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
423         self.expr_map_back[expr].clone()
424     }
425
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()
429     }
430
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()
434     }
435
436     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
437         self.pat_map_back[pat].clone()
438     }
439
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()
443     }
444
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()
448     }
449
450     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
451         self.label_map_back[label].clone()
452     }
453
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()
457     }
458
459     pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
460         self.field_map_back[&expr].clone()
461     }
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()
465     }
466
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()
470     }
471
472     /// Get a reference to the body source map's diagnostics.
473     pub fn diagnostics(&self) -> &[BodyDiagnostic] {
474         &self.diagnostics
475     }
476 }