]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
Merge #11866
[rust.git] / 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
8 use std::{mem, ops::Index, sync::Arc};
9
10 use base_db::CrateId;
11 use cfg::{CfgExpr, CfgOptions};
12 use drop_bomb::DropBomb;
13 use either::Either;
14 use hir_expand::{
15     ast_id_map::AstIdMap, hygiene::Hygiene, AstId, ExpandError, ExpandResult, HirFileId, InFile,
16     MacroCallId,
17 };
18 use la_arena::{Arena, ArenaMap};
19 use limit::Limit;
20 use profile::Count;
21 use rustc_hash::FxHashMap;
22 use smallvec::SmallVec;
23 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
24
25 use crate::{
26     attr::{Attrs, RawAttrs},
27     db::DefDatabase,
28     expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
29     item_scope::BuiltinShadowMode,
30     macro_id_to_def_id,
31     nameres::DefMap,
32     path::{ModPath, Path},
33     src::HasSource,
34     AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, MacroId, ModuleId,
35     UnresolvedMacro,
36 };
37
38 pub use lower::LowerCtx;
39
40 /// A subset of Expander that only deals with cfg attributes. We only need it to
41 /// avoid cyclic queries in crate def map during enum processing.
42 #[derive(Debug)]
43 pub(crate) struct CfgExpander {
44     cfg_options: CfgOptions,
45     hygiene: Hygiene,
46     krate: CrateId,
47 }
48
49 #[derive(Debug)]
50 pub struct Expander {
51     cfg_expander: CfgExpander,
52     def_map: Arc<DefMap>,
53     current_file_id: HirFileId,
54     ast_id_map: Arc<AstIdMap>,
55     module: LocalModuleId,
56     recursion_limit: usize,
57 }
58
59 impl CfgExpander {
60     pub(crate) fn new(
61         db: &dyn DefDatabase,
62         current_file_id: HirFileId,
63         krate: CrateId,
64     ) -> CfgExpander {
65         let hygiene = Hygiene::new(db.upcast(), current_file_id);
66         let cfg_options = db.crate_graph()[krate].cfg_options.clone();
67         CfgExpander { cfg_options, hygiene, krate }
68     }
69
70     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
71         RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
72     }
73
74     pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
75         let attrs = self.parse_attrs(db, owner);
76         attrs.is_cfg_enabled(&self.cfg_options)
77     }
78 }
79
80 impl Expander {
81     pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
82         let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
83         let def_map = module.def_map(db);
84         let ast_id_map = db.ast_id_map(current_file_id);
85         Expander {
86             cfg_expander,
87             def_map,
88             current_file_id,
89             ast_id_map,
90             module: module.local_id,
91             recursion_limit: 0,
92         }
93     }
94
95     pub fn enter_expand<T: ast::AstNode>(
96         &mut self,
97         db: &dyn DefDatabase,
98         macro_call: ast::MacroCall,
99     ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
100         if self.recursion_limit(db).check(self.recursion_limit + 1).is_err() {
101             cov_mark::hit!(your_stack_belongs_to_me);
102             return Ok(ExpandResult::only_err(ExpandError::Other(
103                 "reached recursion limit during macro expansion".into(),
104             )));
105         }
106
107         let macro_call = InFile::new(self.current_file_id, &macro_call);
108
109         let resolver =
110             |path| self.resolve_path_as_macro(db, &path).map(|it| macro_id_to_def_id(db, it));
111
112         let mut err = None;
113         let call_id =
114             macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
115                 err.get_or_insert(e);
116             })?;
117         let call_id = match call_id {
118             Ok(it) => it,
119             Err(_) => {
120                 return Ok(ExpandResult { value: None, err });
121             }
122         };
123
124         Ok(self.enter_expand_inner(db, call_id, err))
125     }
126
127     pub fn enter_expand_id<T: ast::AstNode>(
128         &mut self,
129         db: &dyn DefDatabase,
130         call_id: MacroCallId,
131     ) -> ExpandResult<Option<(Mark, T)>> {
132         self.enter_expand_inner(db, call_id, None)
133     }
134
135     fn enter_expand_inner<T: ast::AstNode>(
136         &mut self,
137         db: &dyn DefDatabase,
138         call_id: MacroCallId,
139         mut err: Option<ExpandError>,
140     ) -> ExpandResult<Option<(Mark, T)>> {
141         if err.is_none() {
142             err = db.macro_expand_error(call_id);
143         }
144
145         let file_id = call_id.as_file();
146
147         let raw_node = match db.parse_or_expand(file_id) {
148             Some(it) => it,
149             None => {
150                 // Only `None` if the macro expansion produced no usable AST.
151                 if err.is_none() {
152                     tracing::warn!("no error despite `parse_or_expand` failing");
153                 }
154
155                 return ExpandResult::only_err(err.unwrap_or_else(|| {
156                     ExpandError::Other("failed to parse macro invocation".into())
157                 }));
158             }
159         };
160
161         let node = match T::cast(raw_node) {
162             Some(it) => it,
163             None => {
164                 // This can happen without being an error, so only forward previous errors.
165                 return ExpandResult { value: None, err };
166             }
167         };
168
169         tracing::debug!("macro expansion {:#?}", node.syntax());
170
171         self.recursion_limit += 1;
172         let mark = Mark {
173             file_id: self.current_file_id,
174             ast_id_map: mem::take(&mut self.ast_id_map),
175             bomb: DropBomb::new("expansion mark dropped"),
176         };
177         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
178         self.current_file_id = file_id;
179         self.ast_id_map = db.ast_id_map(file_id);
180
181         ExpandResult { value: Some((mark, node)), err }
182     }
183
184     pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
185         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
186         self.current_file_id = mark.file_id;
187         self.ast_id_map = mem::take(&mut mark.ast_id_map);
188         self.recursion_limit -= 1;
189         mark.bomb.defuse();
190     }
191
192     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
193         InFile { file_id: self.current_file_id, value }
194     }
195
196     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
197         self.cfg_expander.parse_attrs(db, owner)
198     }
199
200     pub(crate) fn cfg_options(&self) -> &CfgOptions {
201         &self.cfg_expander.cfg_options
202     }
203
204     pub fn current_file_id(&self) -> HirFileId {
205         self.current_file_id
206     }
207
208     fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
209         let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
210         Path::from_src(path, &ctx)
211     }
212
213     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroId> {
214         self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
215     }
216
217     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
218         let file_local_id = self.ast_id_map.ast_id(item);
219         AstId::new(self.current_file_id, file_local_id)
220     }
221
222     fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
223         let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
224
225         #[cfg(not(test))]
226         return Limit::new(limit);
227
228         // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
229         #[cfg(test)]
230         return Limit::new(std::cmp::min(32, limit));
231     }
232 }
233
234 #[derive(Debug)]
235 pub struct Mark {
236     file_id: HirFileId,
237     ast_id_map: Arc<AstIdMap>,
238     bomb: DropBomb,
239 }
240
241 /// The body of an item (function, const etc.).
242 #[derive(Debug, Eq, PartialEq)]
243 pub struct Body {
244     pub exprs: Arena<Expr>,
245     pub pats: Arena<Pat>,
246     pub or_pats: FxHashMap<PatId, Arc<[PatId]>>,
247     pub labels: Arena<Label>,
248     /// The patterns for the function's parameters. While the parameter types are
249     /// part of the function signature, the patterns are not (they don't change
250     /// the external type of the function).
251     ///
252     /// If this `Body` is for the body of a constant, this will just be
253     /// empty.
254     pub params: Vec<PatId>,
255     /// The `ExprId` of the actual body expression.
256     pub body_expr: ExprId,
257     /// Block expressions in this body that may contain inner items.
258     block_scopes: Vec<BlockId>,
259     _c: Count<Self>,
260 }
261
262 pub type ExprPtr = AstPtr<ast::Expr>;
263 pub type ExprSource = InFile<ExprPtr>;
264
265 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
266 pub type PatSource = InFile<PatPtr>;
267
268 pub type LabelPtr = AstPtr<ast::Label>;
269 pub type LabelSource = InFile<LabelPtr>;
270 /// An item body together with the mapping from syntax nodes to HIR expression
271 /// IDs. This is needed to go from e.g. a position in a file to the HIR
272 /// expression containing it; but for type inference etc., we want to operate on
273 /// a structure that is agnostic to the actual positions of expressions in the
274 /// file, so that we don't recompute types whenever some whitespace is typed.
275 ///
276 /// One complication here is that, due to macro expansion, a single `Body` might
277 /// be spread across several files. So, for each ExprId and PatId, we record
278 /// both the HirFileId and the position inside the file. However, we only store
279 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
280 /// this properly for macros.
281 #[derive(Default, Debug, Eq, PartialEq)]
282 pub struct BodySourceMap {
283     expr_map: FxHashMap<ExprSource, ExprId>,
284     expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
285
286     pat_map: FxHashMap<PatSource, PatId>,
287     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
288
289     label_map: FxHashMap<LabelSource, LabelId>,
290     label_map_back: ArenaMap<LabelId, LabelSource>,
291
292     /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
293     /// Instead, we use id of expression (`92`) to identify the field.
294     field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
295     field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
296
297     /// Maps a macro call to its lowered expressions, a single one if it expands to an expression,
298     /// or multiple if it expands to MacroStmts.
299     macro_call_to_exprs: FxHashMap<InFile<AstPtr<ast::MacroCall>>, SmallVec<[ExprId; 1]>>,
300
301     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
302
303     /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
304     /// the source map (since they're just as volatile).
305     diagnostics: Vec<BodyDiagnostic>,
306 }
307
308 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
309 pub struct SyntheticSyntax;
310
311 #[derive(Debug, Eq, PartialEq)]
312 pub enum BodyDiagnostic {
313     InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
314     MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
315     UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
316     UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
317 }
318
319 impl Body {
320     pub(crate) fn body_with_source_map_query(
321         db: &dyn DefDatabase,
322         def: DefWithBodyId,
323     ) -> (Arc<Body>, Arc<BodySourceMap>) {
324         let _p = profile::span("body_with_source_map_query");
325         let mut params = None;
326
327         let (file_id, module, body) = match def {
328             DefWithBodyId::FunctionId(f) => {
329                 let f = f.lookup(db);
330                 let src = f.source(db);
331                 params = src.value.param_list();
332                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
333             }
334             DefWithBodyId::ConstId(c) => {
335                 let c = c.lookup(db);
336                 let src = c.source(db);
337                 (src.file_id, c.module(db), src.value.body())
338             }
339             DefWithBodyId::StaticId(s) => {
340                 let s = s.lookup(db);
341                 let src = s.source(db);
342                 (src.file_id, s.module(db), src.value.body())
343             }
344         };
345         let expander = Expander::new(db, file_id, module);
346         let (mut body, source_map) = Body::new(db, expander, params, body);
347         body.shrink_to_fit();
348         (Arc::new(body), Arc::new(source_map))
349     }
350
351     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
352         db.body_with_source_map(def).0
353     }
354
355     /// Returns an iterator over all block expressions in this body that define inner items.
356     pub fn blocks<'a>(
357         &'a self,
358         db: &'a dyn DefDatabase,
359     ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
360         self.block_scopes
361             .iter()
362             .map(move |&block| (block, db.block_def_map(block).expect("block ID without DefMap")))
363     }
364
365     pub fn pattern_representative(&self, pat: PatId) -> PatId {
366         self.or_pats.get(&pat).and_then(|pats| pats.first().copied()).unwrap_or(pat)
367     }
368
369     /// Retrieves all ident patterns this pattern shares the ident with.
370     pub fn ident_patterns_for<'slf>(&'slf self, pat: &'slf PatId) -> &'slf [PatId] {
371         match self.or_pats.get(pat) {
372             Some(pats) => &**pats,
373             None => std::slice::from_ref(pat),
374         }
375     }
376
377     fn new(
378         db: &dyn DefDatabase,
379         expander: Expander,
380         params: Option<ast::ParamList>,
381         body: Option<ast::Expr>,
382     ) -> (Body, BodySourceMap) {
383         lower::lower(db, expander, params, body)
384     }
385
386     fn shrink_to_fit(&mut self) {
387         let Self { _c: _, body_expr: _, block_scopes, or_pats, exprs, labels, params, pats } = self;
388         block_scopes.shrink_to_fit();
389         or_pats.shrink_to_fit();
390         exprs.shrink_to_fit();
391         labels.shrink_to_fit();
392         params.shrink_to_fit();
393         pats.shrink_to_fit();
394     }
395 }
396
397 impl Index<ExprId> for Body {
398     type Output = Expr;
399
400     fn index(&self, expr: ExprId) -> &Expr {
401         &self.exprs[expr]
402     }
403 }
404
405 impl Index<PatId> for Body {
406     type Output = Pat;
407
408     fn index(&self, pat: PatId) -> &Pat {
409         &self.pats[pat]
410     }
411 }
412
413 impl Index<LabelId> for Body {
414     type Output = Label;
415
416     fn index(&self, label: LabelId) -> &Label {
417         &self.labels[label]
418     }
419 }
420
421 // FIXME: Change `node_` prefix to something more reasonable.
422 // Perhaps `expr_syntax` and `expr_id`?
423 impl BodySourceMap {
424     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
425         self.expr_map_back[expr].clone()
426     }
427
428     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
429         let src = node.map(AstPtr::new);
430         self.expr_map.get(&src).cloned()
431     }
432
433     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
434         let src = node.map(AstPtr::new);
435         self.expansions.get(&src).cloned()
436     }
437
438     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
439         self.pat_map_back[pat].clone()
440     }
441
442     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
443         let src = node.map(|it| Either::Left(AstPtr::new(it)));
444         self.pat_map.get(&src).cloned()
445     }
446
447     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
448         let src = node.map(|it| Either::Right(AstPtr::new(it)));
449         self.pat_map.get(&src).cloned()
450     }
451
452     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
453         self.label_map_back[label].clone()
454     }
455
456     pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
457         let src = node.map(AstPtr::new);
458         self.label_map.get(&src).cloned()
459     }
460
461     pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
462         self.field_map_back[&expr].clone()
463     }
464     pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
465         let src = node.map(AstPtr::new);
466         self.field_map.get(&src).cloned()
467     }
468
469     pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroCall>) -> Option<&[ExprId]> {
470         let src = node.map(AstPtr::new);
471         self.macro_call_to_exprs.get(&src).map(|it| &**it)
472     }
473
474     /// Get a reference to the body source map's diagnostics.
475     pub fn diagnostics(&self) -> &[BodyDiagnostic] {
476         &self.diagnostics
477     }
478 }