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