]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
Merge #11194
[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, MacroDefId,
17 };
18 use la_arena::{Arena, ArenaMap};
19 use limit::Limit;
20 use profile::Count;
21 use rustc_hash::FxHashMap;
22 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
23
24 use crate::{
25     attr::{Attrs, RawAttrs},
26     db::DefDatabase,
27     expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
28     item_scope::BuiltinShadowMode,
29     nameres::DefMap,
30     path::{ModPath, Path},
31     src::HasSource,
32     AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleId,
33     UnresolvedMacro,
34 };
35
36 pub use lower::LowerCtx;
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 static EXPANSION_RECURSION_LIMIT: Limit = Limit::new(32);
59
60 #[cfg(not(test))]
61 static EXPANSION_RECURSION_LIMIT: Limit = Limit::new(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::HasAttrs) -> 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::HasAttrs) -> 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 EXPANSION_RECURSION_LIMIT.check(self.recursion_limit + 1).is_err() {
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         Ok(self.enter_expand_inner(db, call_id, err))
129     }
130
131     pub fn enter_expand_id<T: ast::AstNode>(
132         &mut self,
133         db: &dyn DefDatabase,
134         call_id: MacroCallId,
135     ) -> ExpandResult<Option<(Mark, T)>> {
136         self.enter_expand_inner(db, call_id, None)
137     }
138
139     fn enter_expand_inner<T: ast::AstNode>(
140         &mut self,
141         db: &dyn DefDatabase,
142         call_id: MacroCallId,
143         mut err: Option<ExpandError>,
144     ) -> ExpandResult<Option<(Mark, T)>> {
145         if err.is_none() {
146             err = db.macro_expand_error(call_id);
147         }
148
149         let file_id = call_id.as_file();
150
151         let raw_node = match db.parse_or_expand(file_id) {
152             Some(it) => it,
153             None => {
154                 // Only `None` if the macro expansion produced no usable AST.
155                 if err.is_none() {
156                     tracing::warn!("no error despite `parse_or_expand` failing");
157                 }
158
159                 return ExpandResult::only_err(err.unwrap_or_else(|| {
160                     mbe::ExpandError::Other("failed to parse macro invocation".into())
161                 }));
162             }
163         };
164
165         let node = match T::cast(raw_node) {
166             Some(it) => it,
167             None => {
168                 // This can happen without being an error, so only forward previous errors.
169                 return ExpandResult { value: None, err };
170             }
171         };
172
173         tracing::debug!("macro expansion {:#?}", node.syntax());
174
175         self.recursion_limit += 1;
176         let mark = Mark {
177             file_id: self.current_file_id,
178             ast_id_map: mem::take(&mut self.ast_id_map),
179             bomb: DropBomb::new("expansion mark dropped"),
180         };
181         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
182         self.current_file_id = file_id;
183         self.ast_id_map = db.ast_id_map(file_id);
184
185         ExpandResult { value: Some((mark, node)), err }
186     }
187
188     pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
189         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
190         self.current_file_id = mark.file_id;
191         self.ast_id_map = mem::take(&mut mark.ast_id_map);
192         self.recursion_limit -= 1;
193         mark.bomb.defuse();
194     }
195
196     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
197         InFile { file_id: self.current_file_id, value }
198     }
199
200     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
201         self.cfg_expander.parse_attrs(db, owner)
202     }
203
204     pub(crate) fn cfg_options(&self) -> &CfgOptions {
205         &self.cfg_expander.cfg_options
206     }
207
208     pub fn current_file_id(&self) -> HirFileId {
209         self.current_file_id
210     }
211
212     fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
213         let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
214         Path::from_src(path, &ctx)
215     }
216
217     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
218         self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
219     }
220
221     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
222         let file_local_id = self.ast_id_map.ast_id(item);
223         AstId::new(self.current_file_id, file_local_id)
224     }
225 }
226
227 #[derive(Debug)]
228 pub struct Mark {
229     file_id: HirFileId,
230     ast_id_map: Arc<AstIdMap>,
231     bomb: DropBomb,
232 }
233
234 /// The body of an item (function, const etc.).
235 #[derive(Debug, Eq, PartialEq)]
236 pub struct Body {
237     pub exprs: Arena<Expr>,
238     pub pats: Arena<Pat>,
239     pub labels: Arena<Label>,
240     /// The patterns for the function's parameters. While the parameter types are
241     /// part of the function signature, the patterns are not (they don't change
242     /// the external type of the function).
243     ///
244     /// If this `Body` is for the body of a constant, this will just be
245     /// empty.
246     pub params: Vec<PatId>,
247     /// The `ExprId` of the actual body expression.
248     pub body_expr: ExprId,
249     /// Block expressions in this body that may contain inner items.
250     block_scopes: Vec<BlockId>,
251     _c: Count<Self>,
252 }
253
254 pub type ExprPtr = AstPtr<ast::Expr>;
255 pub type ExprSource = InFile<ExprPtr>;
256
257 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
258 pub type PatSource = InFile<PatPtr>;
259
260 pub type LabelPtr = AstPtr<ast::Label>;
261 pub type LabelSource = InFile<LabelPtr>;
262 /// An item body together with the mapping from syntax nodes to HIR expression
263 /// IDs. This is needed to go from e.g. a position in a file to the HIR
264 /// expression containing it; but for type inference etc., we want to operate on
265 /// a structure that is agnostic to the actual positions of expressions in the
266 /// file, so that we don't recompute types whenever some whitespace is typed.
267 ///
268 /// One complication here is that, due to macro expansion, a single `Body` might
269 /// be spread across several files. So, for each ExprId and PatId, we record
270 /// both the HirFileId and the position inside the file. However, we only store
271 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
272 /// this properly for macros.
273 #[derive(Default, Debug, Eq, PartialEq)]
274 pub struct BodySourceMap {
275     expr_map: FxHashMap<ExprSource, ExprId>,
276     expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
277
278     pat_map: FxHashMap<PatSource, PatId>,
279     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
280
281     label_map: FxHashMap<LabelSource, LabelId>,
282     label_map_back: ArenaMap<LabelId, LabelSource>,
283
284     /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
285     /// Instead, we use id of expression (`92`) to identify the field.
286     field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
287     field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
288
289     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
290
291     /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
292     /// the source map (since they're just as volatile).
293     diagnostics: Vec<BodyDiagnostic>,
294 }
295
296 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
297 pub struct SyntheticSyntax;
298
299 #[derive(Debug, Eq, PartialEq)]
300 pub enum BodyDiagnostic {
301     InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
302     MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
303     UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
304     UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
305 }
306
307 impl Body {
308     pub(crate) fn body_with_source_map_query(
309         db: &dyn DefDatabase,
310         def: DefWithBodyId,
311     ) -> (Arc<Body>, Arc<BodySourceMap>) {
312         let _p = profile::span("body_with_source_map_query");
313         let mut params = None;
314
315         let (file_id, module, body) = match def {
316             DefWithBodyId::FunctionId(f) => {
317                 let f = f.lookup(db);
318                 let src = f.source(db);
319                 params = src.value.param_list();
320                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
321             }
322             DefWithBodyId::ConstId(c) => {
323                 let c = c.lookup(db);
324                 let src = c.source(db);
325                 (src.file_id, c.module(db), src.value.body())
326             }
327             DefWithBodyId::StaticId(s) => {
328                 let s = s.lookup(db);
329                 let src = s.source(db);
330                 (src.file_id, s.module(db), src.value.body())
331             }
332         };
333         let expander = Expander::new(db, file_id, module);
334         let (mut body, source_map) = Body::new(db, expander, params, body);
335         body.shrink_to_fit();
336         (Arc::new(body), Arc::new(source_map))
337     }
338
339     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
340         db.body_with_source_map(def).0
341     }
342
343     /// Returns an iterator over all block expressions in this body that define inner items.
344     pub fn blocks<'a>(
345         &'a self,
346         db: &'a dyn DefDatabase,
347     ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
348         self.block_scopes
349             .iter()
350             .map(move |block| (*block, db.block_def_map(*block).expect("block ID without DefMap")))
351     }
352
353     fn new(
354         db: &dyn DefDatabase,
355         expander: Expander,
356         params: Option<ast::ParamList>,
357         body: Option<ast::Expr>,
358     ) -> (Body, BodySourceMap) {
359         lower::lower(db, expander, params, body)
360     }
361
362     fn shrink_to_fit(&mut self) {
363         let Self { _c: _, body_expr: _, block_scopes, exprs, labels, params, pats } = self;
364         block_scopes.shrink_to_fit();
365         exprs.shrink_to_fit();
366         labels.shrink_to_fit();
367         params.shrink_to_fit();
368         pats.shrink_to_fit();
369     }
370 }
371
372 impl Index<ExprId> for Body {
373     type Output = Expr;
374
375     fn index(&self, expr: ExprId) -> &Expr {
376         &self.exprs[expr]
377     }
378 }
379
380 impl Index<PatId> for Body {
381     type Output = Pat;
382
383     fn index(&self, pat: PatId) -> &Pat {
384         &self.pats[pat]
385     }
386 }
387
388 impl Index<LabelId> for Body {
389     type Output = Label;
390
391     fn index(&self, label: LabelId) -> &Label {
392         &self.labels[label]
393     }
394 }
395
396 // FIXME: Change `node_` prefix to something more reasonable.
397 // Perhaps `expr_syntax` and `expr_id`?
398 impl BodySourceMap {
399     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
400         self.expr_map_back[expr].clone()
401     }
402
403     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
404         let src = node.map(|it| AstPtr::new(it));
405         self.expr_map.get(&src).cloned()
406     }
407
408     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
409         let src = node.map(|it| AstPtr::new(it));
410         self.expansions.get(&src).cloned()
411     }
412
413     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
414         self.pat_map_back[pat].clone()
415     }
416
417     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
418         let src = node.map(|it| Either::Left(AstPtr::new(it)));
419         self.pat_map.get(&src).cloned()
420     }
421
422     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
423         let src = node.map(|it| Either::Right(AstPtr::new(it)));
424         self.pat_map.get(&src).cloned()
425     }
426
427     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
428         self.label_map_back[label].clone()
429     }
430
431     pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
432         let src = node.map(|it| AstPtr::new(it));
433         self.label_map.get(&src).cloned()
434     }
435
436     pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
437         self.field_map_back[&expr].clone()
438     }
439     pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
440         let src = node.map(|it| AstPtr::new(it));
441         self.field_map.get(&src).cloned()
442     }
443
444     /// Get a reference to the body source map's diagnostics.
445     pub fn diagnostics(&self) -> &[BodyDiagnostic] {
446         &self.diagnostics
447     }
448 }