]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
Merge #6256
[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 pub mod scope;
5
6 use std::{mem, ops::Index, sync::Arc};
7
8 use arena::{map::ArenaMap, Arena};
9 use base_db::CrateId;
10 use cfg::CfgOptions;
11 use drop_bomb::DropBomb;
12 use either::Either;
13 use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, AstId, HirFileId, InFile, MacroDefId};
14 use rustc_hash::FxHashMap;
15 use syntax::{ast, AstNode, AstPtr};
16 use test_utils::mark;
17
18 pub(crate) use lower::LowerCtx;
19
20 use crate::{
21     attr::Attrs,
22     db::DefDatabase,
23     expr::{Expr, ExprId, Pat, PatId},
24     item_scope::BuiltinShadowMode,
25     item_scope::ItemScope,
26     nameres::CrateDefMap,
27     path::{ModPath, Path},
28     src::HasSource,
29     AsMacroCall, DefWithBodyId, HasModule, Lookup, ModuleId,
30 };
31
32 /// A subset of Expander that only deals with cfg attributes. We only need it to
33 /// avoid cyclic queries in crate def map during enum processing.
34 pub(crate) struct CfgExpander {
35     cfg_options: CfgOptions,
36     hygiene: Hygiene,
37 }
38
39 pub(crate) struct Expander {
40     cfg_expander: CfgExpander,
41     crate_def_map: Arc<CrateDefMap>,
42     current_file_id: HirFileId,
43     ast_id_map: Arc<AstIdMap>,
44     module: ModuleId,
45     recursion_limit: usize,
46 }
47
48 #[cfg(test)]
49 const EXPANSION_RECURSION_LIMIT: usize = 32;
50
51 #[cfg(not(test))]
52 const EXPANSION_RECURSION_LIMIT: usize = 128;
53
54 impl CfgExpander {
55     pub(crate) fn new(
56         db: &dyn DefDatabase,
57         current_file_id: HirFileId,
58         krate: CrateId,
59     ) -> CfgExpander {
60         let hygiene = Hygiene::new(db.upcast(), current_file_id);
61         let cfg_options = db.crate_graph()[krate].cfg_options.clone();
62         CfgExpander { cfg_options, hygiene }
63     }
64
65     pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs {
66         Attrs::new(owner, &self.hygiene)
67     }
68
69     pub(crate) fn is_cfg_enabled(&self, owner: &dyn ast::AttrsOwner) -> bool {
70         let attrs = self.parse_attrs(owner);
71         attrs.is_cfg_enabled(&self.cfg_options)
72     }
73 }
74
75 impl Expander {
76     pub(crate) fn new(
77         db: &dyn DefDatabase,
78         current_file_id: HirFileId,
79         module: ModuleId,
80     ) -> Expander {
81         let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
82         let crate_def_map = db.crate_def_map(module.krate);
83         let ast_id_map = db.ast_id_map(current_file_id);
84         Expander {
85             cfg_expander,
86             crate_def_map,
87             current_file_id,
88             ast_id_map,
89             module,
90             recursion_limit: 0,
91         }
92     }
93
94     pub(crate) fn enter_expand<T: ast::AstNode>(
95         &mut self,
96         db: &dyn DefDatabase,
97         local_scope: Option<&ItemScope>,
98         macro_call: ast::MacroCall,
99     ) -> Option<(Mark, T)> {
100         self.recursion_limit += 1;
101         if self.recursion_limit > EXPANSION_RECURSION_LIMIT {
102             mark::hit!(your_stack_belongs_to_me);
103             return None;
104         }
105
106         let macro_call = InFile::new(self.current_file_id, &macro_call);
107
108         let resolver = |path: ModPath| -> Option<MacroDefId> {
109             if let Some(local_scope) = local_scope {
110                 if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) {
111                     return Some(def);
112                 }
113             }
114             self.resolve_path_as_macro(db, &path)
115         };
116
117         if let Some(call_id) = macro_call.as_call_id(db, self.crate_def_map.krate, resolver) {
118             let file_id = call_id.as_file();
119             if let Some(node) = db.parse_or_expand(file_id) {
120                 if let Some(expr) = T::cast(node) {
121                     log::debug!("macro expansion {:#?}", expr.syntax());
122
123                     let mark = Mark {
124                         file_id: self.current_file_id,
125                         ast_id_map: mem::take(&mut self.ast_id_map),
126                         bomb: DropBomb::new("expansion mark dropped"),
127                     };
128                     self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
129                     self.current_file_id = file_id;
130                     self.ast_id_map = db.ast_id_map(file_id);
131                     return Some((mark, expr));
132                 }
133             }
134         }
135
136         // FIXME: Instead of just dropping the error from expansion
137         // report it
138         None
139     }
140
141     pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
142         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
143         self.current_file_id = mark.file_id;
144         self.ast_id_map = mem::take(&mut mark.ast_id_map);
145         self.recursion_limit -= 1;
146         mark.bomb.defuse();
147     }
148
149     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
150         InFile { file_id: self.current_file_id, value }
151     }
152
153     pub(crate) fn is_cfg_enabled(&self, owner: &dyn ast::AttrsOwner) -> bool {
154         self.cfg_expander.is_cfg_enabled(owner)
155     }
156
157     fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
158         Path::from_src(path, &self.cfg_expander.hygiene)
159     }
160
161     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
162         self.crate_def_map
163             .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
164             .0
165             .take_macros()
166     }
167
168     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
169         let file_local_id = self.ast_id_map.ast_id(item);
170         AstId::new(self.current_file_id, file_local_id)
171     }
172 }
173
174 pub(crate) struct Mark {
175     file_id: HirFileId,
176     ast_id_map: Arc<AstIdMap>,
177     bomb: DropBomb,
178 }
179
180 /// The body of an item (function, const etc.).
181 #[derive(Debug, Eq, PartialEq)]
182 pub struct Body {
183     pub exprs: Arena<Expr>,
184     pub pats: Arena<Pat>,
185     /// The patterns for the function's parameters. While the parameter types are
186     /// part of the function signature, the patterns are not (they don't change
187     /// the external type of the function).
188     ///
189     /// If this `Body` is for the body of a constant, this will just be
190     /// empty.
191     pub params: Vec<PatId>,
192     /// The `ExprId` of the actual body expression.
193     pub body_expr: ExprId,
194     pub item_scope: ItemScope,
195 }
196
197 pub type ExprPtr = AstPtr<ast::Expr>;
198 pub type ExprSource = InFile<ExprPtr>;
199
200 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
201 pub type PatSource = InFile<PatPtr>;
202
203 /// An item body together with the mapping from syntax nodes to HIR expression
204 /// IDs. This is needed to go from e.g. a position in a file to the HIR
205 /// expression containing it; but for type inference etc., we want to operate on
206 /// a structure that is agnostic to the actual positions of expressions in the
207 /// file, so that we don't recompute types whenever some whitespace is typed.
208 ///
209 /// One complication here is that, due to macro expansion, a single `Body` might
210 /// be spread across several files. So, for each ExprId and PatId, we record
211 /// both the HirFileId and the position inside the file. However, we only store
212 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
213 /// this properly for macros.
214 #[derive(Default, Debug, Eq, PartialEq)]
215 pub struct BodySourceMap {
216     expr_map: FxHashMap<ExprSource, ExprId>,
217     expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
218     pat_map: FxHashMap<PatSource, PatId>,
219     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
220     field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
221     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
222 }
223
224 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
225 pub struct SyntheticSyntax;
226
227 impl Body {
228     pub(crate) fn body_with_source_map_query(
229         db: &dyn DefDatabase,
230         def: DefWithBodyId,
231     ) -> (Arc<Body>, Arc<BodySourceMap>) {
232         let _p = profile::span("body_with_source_map_query");
233         let mut params = None;
234
235         let (file_id, module, body) = match def {
236             DefWithBodyId::FunctionId(f) => {
237                 let f = f.lookup(db);
238                 let src = f.source(db);
239                 params = src.value.param_list();
240                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
241             }
242             DefWithBodyId::ConstId(c) => {
243                 let c = c.lookup(db);
244                 let src = c.source(db);
245                 (src.file_id, c.module(db), src.value.body())
246             }
247             DefWithBodyId::StaticId(s) => {
248                 let s = s.lookup(db);
249                 let src = s.source(db);
250                 (src.file_id, s.module(db), src.value.body())
251             }
252         };
253         let expander = Expander::new(db, file_id, module);
254         let (body, source_map) = Body::new(db, def, expander, params, body);
255         (Arc::new(body), Arc::new(source_map))
256     }
257
258     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
259         db.body_with_source_map(def).0
260     }
261
262     fn new(
263         db: &dyn DefDatabase,
264         def: DefWithBodyId,
265         expander: Expander,
266         params: Option<ast::ParamList>,
267         body: Option<ast::Expr>,
268     ) -> (Body, BodySourceMap) {
269         lower::lower(db, def, expander, params, body)
270     }
271 }
272
273 impl Index<ExprId> for Body {
274     type Output = Expr;
275
276     fn index(&self, expr: ExprId) -> &Expr {
277         &self.exprs[expr]
278     }
279 }
280
281 impl Index<PatId> for Body {
282     type Output = Pat;
283
284     fn index(&self, pat: PatId) -> &Pat {
285         &self.pats[pat]
286     }
287 }
288
289 impl BodySourceMap {
290     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
291         self.expr_map_back[expr].clone()
292     }
293
294     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
295         let src = node.map(|it| AstPtr::new(it));
296         self.expr_map.get(&src).cloned()
297     }
298
299     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
300         let src = node.map(|it| AstPtr::new(it));
301         self.expansions.get(&src).cloned()
302     }
303
304     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
305         self.pat_map_back[pat].clone()
306     }
307
308     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
309         let src = node.map(|it| Either::Left(AstPtr::new(it)));
310         self.pat_map.get(&src).cloned()
311     }
312
313     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
314         let src = node.map(|it| Either::Right(AstPtr::new(it)));
315         self.pat_map.get(&src).cloned()
316     }
317
318     pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
319         self.field_map[&(expr, field)].clone()
320     }
321 }
322
323 #[cfg(test)]
324 mod tests {
325     use base_db::{fixture::WithFixture, SourceDatabase};
326     use test_utils::mark;
327
328     use crate::ModuleDefId;
329
330     use super::*;
331
332     fn lower(ra_fixture: &str) -> Arc<Body> {
333         let (db, file_id) = crate::test_db::TestDB::with_single_file(ra_fixture);
334
335         let krate = db.crate_graph().iter().next().unwrap();
336         let def_map = db.crate_def_map(krate);
337         let module = def_map.modules_for_file(file_id).next().unwrap();
338         let module = &def_map[module];
339         let fn_def = match module.scope.declarations().next().unwrap() {
340             ModuleDefId::FunctionId(it) => it,
341             _ => panic!(),
342         };
343
344         db.body(fn_def.into())
345     }
346
347     #[test]
348     fn your_stack_belongs_to_me() {
349         mark::check!(your_stack_belongs_to_me);
350         lower(
351             "
352 macro_rules! n_nuple {
353     ($e:tt) => ();
354     ($($rest:tt)*) => {{
355         (n_nuple!($($rest)*)None,)
356     }};
357 }
358 fn main() { n_nuple!(1,2,3); }
359 ",
360         );
361     }
362 }