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