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