]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
Rename `CrateDefMap` to `DefMap`
[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 rustc_hash::FxHashMap;
21 use syntax::{ast, AstNode, AstPtr};
22 use test_utils::mark;
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     item_scope::ItemScope,
32     nameres::DefMap,
33     path::{ModPath, Path},
34     src::HasSource,
35     AsMacroCall, DefWithBodyId, HasModule, Lookup, ModuleId,
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     crate_def_map: Arc<DefMap>,
49     current_file_id: HirFileId,
50     ast_id_map: Arc<AstIdMap>,
51     module: ModuleId,
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 crate_def_map = db.crate_def_map(module.krate);
90         let ast_id_map = db.ast_id_map(current_file_id);
91         Expander {
92             cfg_expander,
93             crate_def_map,
94             current_file_id,
95             ast_id_map,
96             module,
97             recursion_limit: 0,
98         }
99     }
100
101     pub(crate) fn enter_expand<T: ast::AstNode>(
102         &mut self,
103         db: &dyn DefDatabase,
104         local_scope: Option<&ItemScope>,
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 = |path: ModPath| -> Option<MacroDefId> {
115             if let Some(local_scope) = local_scope {
116                 if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) {
117                     return Some(def);
118                 }
119             }
120             self.resolve_path_as_macro(db, &path)
121         };
122
123         let mut err = None;
124         let call_id =
125             macro_call.as_call_id_with_errors(db, self.crate_def_map.krate, resolver, &mut |e| {
126                 err.get_or_insert(e);
127             });
128         let call_id = match call_id {
129             Some(it) => it,
130             None => {
131                 if err.is_none() {
132                     eprintln!("no error despite `as_call_id_with_errors` returning `None`");
133                 }
134                 return ExpandResult { value: None, err };
135             }
136         };
137
138         if err.is_none() {
139             err = db.macro_expand_error(call_id);
140         }
141
142         let file_id = call_id.as_file();
143
144         let raw_node = match db.parse_or_expand(file_id) {
145             Some(it) => it,
146             None => {
147                 // Only `None` if the macro expansion produced no usable AST.
148                 if err.is_none() {
149                     log::warn!("no error despite `parse_or_expand` failing");
150                 }
151
152                 return ExpandResult::only_err(err.unwrap_or_else(|| {
153                     mbe::ExpandError::Other("failed to parse macro invocation".into())
154                 }));
155             }
156         };
157
158         let node = match T::cast(raw_node) {
159             Some(it) => it,
160             None => {
161                 // This can happen without being an error, so only forward previous errors.
162                 return ExpandResult { value: None, err };
163             }
164         };
165
166         log::debug!("macro expansion {:#?}", node.syntax());
167
168         self.recursion_limit += 1;
169         let mark = Mark {
170             file_id: self.current_file_id,
171             ast_id_map: mem::take(&mut self.ast_id_map),
172             bomb: DropBomb::new("expansion mark dropped"),
173         };
174         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
175         self.current_file_id = file_id;
176         self.ast_id_map = db.ast_id_map(file_id);
177
178         ExpandResult { value: Some((mark, node)), err }
179     }
180
181     pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
182         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
183         self.current_file_id = mark.file_id;
184         self.ast_id_map = mem::take(&mut mark.ast_id_map);
185         self.recursion_limit -= 1;
186         mark.bomb.defuse();
187     }
188
189     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
190         InFile { file_id: self.current_file_id, value }
191     }
192
193     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
194         self.cfg_expander.parse_attrs(db, owner)
195     }
196
197     pub(crate) fn cfg_options(&self) -> &CfgOptions {
198         &self.cfg_expander.cfg_options
199     }
200
201     fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
202         Path::from_src(path, &self.cfg_expander.hygiene)
203     }
204
205     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
206         self.crate_def_map
207             .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
208             .0
209             .take_macros()
210     }
211
212     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
213         let file_local_id = self.ast_id_map.ast_id(item);
214         AstId::new(self.current_file_id, file_local_id)
215     }
216 }
217
218 pub(crate) struct Mark {
219     file_id: HirFileId,
220     ast_id_map: Arc<AstIdMap>,
221     bomb: DropBomb,
222 }
223
224 /// The body of an item (function, const etc.).
225 #[derive(Debug, Eq, PartialEq)]
226 pub struct Body {
227     pub exprs: Arena<Expr>,
228     pub pats: Arena<Pat>,
229     pub labels: Arena<Label>,
230     /// The patterns for the function's parameters. While the parameter types are
231     /// part of the function signature, the patterns are not (they don't change
232     /// the external type of the function).
233     ///
234     /// If this `Body` is for the body of a constant, this will just be
235     /// empty.
236     pub params: Vec<PatId>,
237     /// The `ExprId` of the actual body expression.
238     pub body_expr: ExprId,
239     pub item_scope: ItemScope,
240 }
241
242 pub type ExprPtr = AstPtr<ast::Expr>;
243 pub type ExprSource = InFile<ExprPtr>;
244
245 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
246 pub type PatSource = InFile<PatPtr>;
247
248 pub type LabelPtr = AstPtr<ast::Label>;
249 pub type LabelSource = InFile<LabelPtr>;
250 /// An item body together with the mapping from syntax nodes to HIR expression
251 /// IDs. This is needed to go from e.g. a position in a file to the HIR
252 /// expression containing it; but for type inference etc., we want to operate on
253 /// a structure that is agnostic to the actual positions of expressions in the
254 /// file, so that we don't recompute types whenever some whitespace is typed.
255 ///
256 /// One complication here is that, due to macro expansion, a single `Body` might
257 /// be spread across several files. So, for each ExprId and PatId, we record
258 /// both the HirFileId and the position inside the file. However, we only store
259 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
260 /// this properly for macros.
261 #[derive(Default, Debug, Eq, PartialEq)]
262 pub struct BodySourceMap {
263     expr_map: FxHashMap<ExprSource, ExprId>,
264     expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
265     pat_map: FxHashMap<PatSource, PatId>,
266     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
267     label_map: FxHashMap<LabelSource, LabelId>,
268     label_map_back: ArenaMap<LabelId, LabelSource>,
269     field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
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<diagnostics::BodyDiagnostic>,
275 }
276
277 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
278 pub struct SyntheticSyntax;
279
280 impl Body {
281     pub(crate) fn body_with_source_map_query(
282         db: &dyn DefDatabase,
283         def: DefWithBodyId,
284     ) -> (Arc<Body>, Arc<BodySourceMap>) {
285         let _p = profile::span("body_with_source_map_query");
286         let mut params = None;
287
288         let (file_id, module, body) = match def {
289             DefWithBodyId::FunctionId(f) => {
290                 let f = f.lookup(db);
291                 let src = f.source(db);
292                 params = src.value.param_list();
293                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
294             }
295             DefWithBodyId::ConstId(c) => {
296                 let c = c.lookup(db);
297                 let src = c.source(db);
298                 (src.file_id, c.module(db), src.value.body())
299             }
300             DefWithBodyId::StaticId(s) => {
301                 let s = s.lookup(db);
302                 let src = s.source(db);
303                 (src.file_id, s.module(db), src.value.body())
304             }
305         };
306         let expander = Expander::new(db, file_id, module);
307         let (body, source_map) = Body::new(db, def, expander, params, body);
308         (Arc::new(body), Arc::new(source_map))
309     }
310
311     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
312         db.body_with_source_map(def).0
313     }
314
315     fn new(
316         db: &dyn DefDatabase,
317         def: DefWithBodyId,
318         expander: Expander,
319         params: Option<ast::ParamList>,
320         body: Option<ast::Expr>,
321     ) -> (Body, BodySourceMap) {
322         lower::lower(db, def, expander, params, body)
323     }
324 }
325
326 impl Index<ExprId> for Body {
327     type Output = Expr;
328
329     fn index(&self, expr: ExprId) -> &Expr {
330         &self.exprs[expr]
331     }
332 }
333
334 impl Index<PatId> for Body {
335     type Output = Pat;
336
337     fn index(&self, pat: PatId) -> &Pat {
338         &self.pats[pat]
339     }
340 }
341
342 impl Index<LabelId> for Body {
343     type Output = Label;
344
345     fn index(&self, label: LabelId) -> &Label {
346         &self.labels[label]
347     }
348 }
349
350 impl BodySourceMap {
351     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
352         self.expr_map_back[expr].clone()
353     }
354
355     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
356         let src = node.map(|it| AstPtr::new(it));
357         self.expr_map.get(&src).cloned()
358     }
359
360     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
361         let src = node.map(|it| AstPtr::new(it));
362         self.expansions.get(&src).cloned()
363     }
364
365     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
366         self.pat_map_back[pat].clone()
367     }
368
369     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
370         let src = node.map(|it| Either::Left(AstPtr::new(it)));
371         self.pat_map.get(&src).cloned()
372     }
373
374     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
375         let src = node.map(|it| Either::Right(AstPtr::new(it)));
376         self.pat_map.get(&src).cloned()
377     }
378
379     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
380         self.label_map_back[label].clone()
381     }
382
383     pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
384         let src = node.map(|it| AstPtr::new(it));
385         self.label_map.get(&src).cloned()
386     }
387
388     pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
389         self.field_map[&(expr, field)].clone()
390     }
391
392     pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
393         for diag in &self.diagnostics {
394             diag.add_to(sink);
395         }
396     }
397 }