]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
Use block_def_map in body lowering
[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     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             def_map: 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         macro_call: ast::MacroCall,
106     ) -> ExpandResult<Option<(Mark, T)>> {
107         if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
108             mark::hit!(your_stack_belongs_to_me);
109             return ExpandResult::str_err("reached recursion limit during macro expansion".into());
110         }
111
112         let macro_call = InFile::new(self.current_file_id, &macro_call);
113
114         let resolver =
115             |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
116
117         let mut err = None;
118         let call_id =
119             macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
120                 err.get_or_insert(e);
121             });
122         let call_id = match call_id {
123             Some(it) => it,
124             None => {
125                 if err.is_none() {
126                     eprintln!("no error despite `as_call_id_with_errors` returning `None`");
127                 }
128                 return ExpandResult { value: None, err };
129             }
130         };
131
132         if err.is_none() {
133             err = db.macro_expand_error(call_id);
134         }
135
136         let file_id = call_id.as_file();
137
138         let raw_node = match db.parse_or_expand(file_id) {
139             Some(it) => it,
140             None => {
141                 // Only `None` if the macro expansion produced no usable AST.
142                 if err.is_none() {
143                     log::warn!("no error despite `parse_or_expand` failing");
144                 }
145
146                 return ExpandResult::only_err(err.unwrap_or_else(|| {
147                     mbe::ExpandError::Other("failed to parse macro invocation".into())
148                 }));
149             }
150         };
151
152         let node = match T::cast(raw_node) {
153             Some(it) => it,
154             None => {
155                 // This can happen without being an error, so only forward previous errors.
156                 return ExpandResult { value: None, err };
157             }
158         };
159
160         log::debug!("macro expansion {:#?}", node.syntax());
161
162         self.recursion_limit += 1;
163         let mark = Mark {
164             file_id: self.current_file_id,
165             ast_id_map: mem::take(&mut self.ast_id_map),
166             bomb: DropBomb::new("expansion mark dropped"),
167         };
168         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
169         self.current_file_id = file_id;
170         self.ast_id_map = db.ast_id_map(file_id);
171
172         ExpandResult { value: Some((mark, node)), err }
173     }
174
175     pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
176         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
177         self.current_file_id = mark.file_id;
178         self.ast_id_map = mem::take(&mut mark.ast_id_map);
179         self.recursion_limit -= 1;
180         mark.bomb.defuse();
181     }
182
183     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
184         InFile { file_id: self.current_file_id, value }
185     }
186
187     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
188         self.cfg_expander.parse_attrs(db, owner)
189     }
190
191     pub(crate) fn cfg_options(&self) -> &CfgOptions {
192         &self.cfg_expander.cfg_options
193     }
194
195     fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
196         Path::from_src(path, &self.cfg_expander.hygiene)
197     }
198
199     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
200         self.def_map
201             .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
202             .0
203             .take_macros()
204     }
205
206     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
207         let file_local_id = self.ast_id_map.ast_id(item);
208         AstId::new(self.current_file_id, file_local_id)
209     }
210 }
211
212 pub(crate) struct Mark {
213     file_id: HirFileId,
214     ast_id_map: Arc<AstIdMap>,
215     bomb: DropBomb,
216 }
217
218 /// The body of an item (function, const etc.).
219 #[derive(Debug, Eq, PartialEq)]
220 pub struct Body {
221     pub exprs: Arena<Expr>,
222     pub pats: Arena<Pat>,
223     pub labels: Arena<Label>,
224     /// The patterns for the function's parameters. While the parameter types are
225     /// part of the function signature, the patterns are not (they don't change
226     /// the external type of the function).
227     ///
228     /// If this `Body` is for the body of a constant, this will just be
229     /// empty.
230     pub params: Vec<PatId>,
231     /// The `ExprId` of the actual body expression.
232     pub body_expr: ExprId,
233     pub item_scope: ItemScope,
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     pat_map: FxHashMap<PatSource, PatId>,
261     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
262     label_map: FxHashMap<LabelSource, LabelId>,
263     label_map_back: ArenaMap<LabelId, LabelSource>,
264     field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
265     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
266
267     /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
268     /// the source map (since they're just as volatile).
269     diagnostics: Vec<diagnostics::BodyDiagnostic>,
270 }
271
272 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
273 pub struct SyntheticSyntax;
274
275 impl Body {
276     pub(crate) fn body_with_source_map_query(
277         db: &dyn DefDatabase,
278         def: DefWithBodyId,
279     ) -> (Arc<Body>, Arc<BodySourceMap>) {
280         let _p = profile::span("body_with_source_map_query");
281         let mut params = None;
282
283         let (file_id, module, body) = match def {
284             DefWithBodyId::FunctionId(f) => {
285                 let f = f.lookup(db);
286                 let src = f.source(db);
287                 params = src.value.param_list();
288                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
289             }
290             DefWithBodyId::ConstId(c) => {
291                 let c = c.lookup(db);
292                 let src = c.source(db);
293                 (src.file_id, c.module(db), src.value.body())
294             }
295             DefWithBodyId::StaticId(s) => {
296                 let s = s.lookup(db);
297                 let src = s.source(db);
298                 (src.file_id, s.module(db), src.value.body())
299             }
300         };
301         let expander = Expander::new(db, file_id, module);
302         let (body, source_map) = Body::new(db, def, expander, params, body);
303         (Arc::new(body), Arc::new(source_map))
304     }
305
306     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
307         db.body_with_source_map(def).0
308     }
309
310     fn new(
311         db: &dyn DefDatabase,
312         def: DefWithBodyId,
313         expander: Expander,
314         params: Option<ast::ParamList>,
315         body: Option<ast::Expr>,
316     ) -> (Body, BodySourceMap) {
317         lower::lower(db, def, expander, params, body)
318     }
319 }
320
321 impl Index<ExprId> for Body {
322     type Output = Expr;
323
324     fn index(&self, expr: ExprId) -> &Expr {
325         &self.exprs[expr]
326     }
327 }
328
329 impl Index<PatId> for Body {
330     type Output = Pat;
331
332     fn index(&self, pat: PatId) -> &Pat {
333         &self.pats[pat]
334     }
335 }
336
337 impl Index<LabelId> for Body {
338     type Output = Label;
339
340     fn index(&self, label: LabelId) -> &Label {
341         &self.labels[label]
342     }
343 }
344
345 impl BodySourceMap {
346     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
347         self.expr_map_back[expr].clone()
348     }
349
350     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
351         let src = node.map(|it| AstPtr::new(it));
352         self.expr_map.get(&src).cloned()
353     }
354
355     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
356         let src = node.map(|it| AstPtr::new(it));
357         self.expansions.get(&src).cloned()
358     }
359
360     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
361         self.pat_map_back[pat].clone()
362     }
363
364     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
365         let src = node.map(|it| Either::Left(AstPtr::new(it)));
366         self.pat_map.get(&src).cloned()
367     }
368
369     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
370         let src = node.map(|it| Either::Right(AstPtr::new(it)));
371         self.pat_map.get(&src).cloned()
372     }
373
374     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
375         self.label_map_back[label].clone()
376     }
377
378     pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
379         let src = node.map(|it| AstPtr::new(it));
380         self.label_map.get(&src).cloned()
381     }
382
383     pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
384         self.field_map[&(expr, field)].clone()
385     }
386
387     pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
388         for diag in &self.diagnostics {
389             diag.add_to(sink);
390         }
391     }
392 }