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