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