]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
parameters.split_last()
[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 #[cfg(test)]
5 mod tests;
6 pub mod scope;
7
8 use std::{mem, ops::Index, sync::Arc};
9
10 use base_db::CrateId;
11 use cfg::{CfgExpr, CfgOptions};
12 use drop_bomb::DropBomb;
13 use either::Either;
14 use hir_expand::{
15     ast_id_map::AstIdMap, hygiene::Hygiene, AstId, ExpandError, ExpandResult, HirFileId, InFile,
16     MacroCallId, MacroDefId,
17 };
18 use la_arena::{Arena, ArenaMap};
19 use limit::Limit;
20 use profile::Count;
21 use rustc_hash::FxHashMap;
22 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
23
24 use crate::{
25     attr::{Attrs, RawAttrs},
26     db::DefDatabase,
27     expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
28     item_scope::BuiltinShadowMode,
29     nameres::DefMap,
30     path::{ModPath, Path},
31     src::HasSource,
32     AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleId,
33     UnresolvedMacro,
34 };
35
36 pub use lower::LowerCtx;
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 #[derive(Debug)]
41 pub(crate) struct CfgExpander {
42     cfg_options: CfgOptions,
43     hygiene: Hygiene,
44     krate: CrateId,
45 }
46
47 #[derive(Debug)]
48 pub struct Expander {
49     cfg_expander: CfgExpander,
50     def_map: Arc<DefMap>,
51     current_file_id: HirFileId,
52     ast_id_map: Arc<AstIdMap>,
53     module: LocalModuleId,
54     recursion_limit: usize,
55 }
56
57 impl CfgExpander {
58     pub(crate) fn new(
59         db: &dyn DefDatabase,
60         current_file_id: HirFileId,
61         krate: CrateId,
62     ) -> CfgExpander {
63         let hygiene = Hygiene::new(db.upcast(), current_file_id);
64         let cfg_options = db.crate_graph()[krate].cfg_options.clone();
65         CfgExpander { cfg_options, hygiene, krate }
66     }
67
68     pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
69         RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
70     }
71
72     pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
73         let attrs = self.parse_attrs(db, owner);
74         attrs.is_cfg_enabled(&self.cfg_options)
75     }
76 }
77
78 impl Expander {
79     pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
80         let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
81         let def_map = module.def_map(db);
82         let ast_id_map = db.ast_id_map(current_file_id);
83         Expander {
84             cfg_expander,
85             def_map,
86             current_file_id,
87             ast_id_map,
88             module: module.local_id,
89             recursion_limit: 0,
90         }
91     }
92
93     pub fn enter_expand<T: ast::AstNode>(
94         &mut self,
95         db: &dyn DefDatabase,
96         macro_call: ast::MacroCall,
97     ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
98         if self.recursion_limit(db).check(self.recursion_limit + 1).is_err() {
99             cov_mark::hit!(your_stack_belongs_to_me);
100             return Ok(ExpandResult::str_err(
101                 "reached recursion limit during macro expansion".into(),
102             ));
103         }
104
105         let macro_call = InFile::new(self.current_file_id, &macro_call);
106
107         let resolver =
108             |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
109
110         let mut err = None;
111         let call_id =
112             macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
113                 err.get_or_insert(e);
114             })?;
115         let call_id = match call_id {
116             Ok(it) => it,
117             Err(_) => {
118                 return Ok(ExpandResult { value: None, err });
119             }
120         };
121
122         Ok(self.enter_expand_inner(db, call_id, err))
123     }
124
125     pub fn enter_expand_id<T: ast::AstNode>(
126         &mut self,
127         db: &dyn DefDatabase,
128         call_id: MacroCallId,
129     ) -> ExpandResult<Option<(Mark, T)>> {
130         self.enter_expand_inner(db, call_id, None)
131     }
132
133     fn enter_expand_inner<T: ast::AstNode>(
134         &mut self,
135         db: &dyn DefDatabase,
136         call_id: MacroCallId,
137         mut err: Option<ExpandError>,
138     ) -> ExpandResult<Option<(Mark, T)>> {
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                     tracing::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         tracing::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 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::HasAttrs) -> 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     pub fn current_file_id(&self) -> HirFileId {
203         self.current_file_id
204     }
205
206     fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
207         let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
208         Path::from_src(path, &ctx)
209     }
210
211     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
212         self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
213     }
214
215     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
216         let file_local_id = self.ast_id_map.ast_id(item);
217         AstId::new(self.current_file_id, file_local_id)
218     }
219
220     fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
221         let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
222
223         #[cfg(not(test))]
224         return Limit::new(limit);
225
226         // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
227         #[cfg(test)]
228         return Limit::new(std::cmp::min(32, limit));
229     }
230 }
231
232 #[derive(Debug)]
233 pub struct Mark {
234     file_id: HirFileId,
235     ast_id_map: Arc<AstIdMap>,
236     bomb: DropBomb,
237 }
238
239 /// The body of an item (function, const etc.).
240 #[derive(Debug, Eq, PartialEq)]
241 pub struct Body {
242     pub exprs: Arena<Expr>,
243     pub pats: Arena<Pat>,
244     pub labels: Arena<Label>,
245     /// The patterns for the function's parameters. While the parameter types are
246     /// part of the function signature, the patterns are not (they don't change
247     /// the external type of the function).
248     ///
249     /// If this `Body` is for the body of a constant, this will just be
250     /// empty.
251     pub params: Vec<PatId>,
252     /// The `ExprId` of the actual body expression.
253     pub body_expr: ExprId,
254     /// Block expressions in this body that may contain inner items.
255     block_scopes: Vec<BlockId>,
256     _c: Count<Self>,
257 }
258
259 pub type ExprPtr = AstPtr<ast::Expr>;
260 pub type ExprSource = InFile<ExprPtr>;
261
262 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
263 pub type PatSource = InFile<PatPtr>;
264
265 pub type LabelPtr = AstPtr<ast::Label>;
266 pub type LabelSource = InFile<LabelPtr>;
267 /// An item body together with the mapping from syntax nodes to HIR expression
268 /// IDs. This is needed to go from e.g. a position in a file to the HIR
269 /// expression containing it; but for type inference etc., we want to operate on
270 /// a structure that is agnostic to the actual positions of expressions in the
271 /// file, so that we don't recompute types whenever some whitespace is typed.
272 ///
273 /// One complication here is that, due to macro expansion, a single `Body` might
274 /// be spread across several files. So, for each ExprId and PatId, we record
275 /// both the HirFileId and the position inside the file. However, we only store
276 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
277 /// this properly for macros.
278 #[derive(Default, Debug, Eq, PartialEq)]
279 pub struct BodySourceMap {
280     expr_map: FxHashMap<ExprSource, ExprId>,
281     expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
282
283     pat_map: FxHashMap<PatSource, PatId>,
284     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
285
286     label_map: FxHashMap<LabelSource, LabelId>,
287     label_map_back: ArenaMap<LabelId, LabelSource>,
288
289     /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
290     /// Instead, we use id of expression (`92`) to identify the field.
291     field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
292     field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
293
294     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
295
296     /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
297     /// the source map (since they're just as volatile).
298     diagnostics: Vec<BodyDiagnostic>,
299 }
300
301 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
302 pub struct SyntheticSyntax;
303
304 #[derive(Debug, Eq, PartialEq)]
305 pub enum BodyDiagnostic {
306     InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
307     MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
308     UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
309     UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
310 }
311
312 impl Body {
313     pub(crate) fn body_with_source_map_query(
314         db: &dyn DefDatabase,
315         def: DefWithBodyId,
316     ) -> (Arc<Body>, Arc<BodySourceMap>) {
317         let _p = profile::span("body_with_source_map_query");
318         let mut params = None;
319
320         let (file_id, module, body) = match def {
321             DefWithBodyId::FunctionId(f) => {
322                 let f = f.lookup(db);
323                 let src = f.source(db);
324                 params = src.value.param_list();
325                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
326             }
327             DefWithBodyId::ConstId(c) => {
328                 let c = c.lookup(db);
329                 let src = c.source(db);
330                 (src.file_id, c.module(db), src.value.body())
331             }
332             DefWithBodyId::StaticId(s) => {
333                 let s = s.lookup(db);
334                 let src = s.source(db);
335                 (src.file_id, s.module(db), src.value.body())
336             }
337         };
338         let expander = Expander::new(db, file_id, module);
339         let (mut body, source_map) = Body::new(db, expander, params, body);
340         body.shrink_to_fit();
341         (Arc::new(body), Arc::new(source_map))
342     }
343
344     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
345         db.body_with_source_map(def).0
346     }
347
348     /// Returns an iterator over all block expressions in this body that define inner items.
349     pub fn blocks<'a>(
350         &'a self,
351         db: &'a dyn DefDatabase,
352     ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
353         self.block_scopes
354             .iter()
355             .map(move |block| (*block, db.block_def_map(*block).expect("block ID without DefMap")))
356     }
357
358     fn new(
359         db: &dyn DefDatabase,
360         expander: Expander,
361         params: Option<ast::ParamList>,
362         body: Option<ast::Expr>,
363     ) -> (Body, BodySourceMap) {
364         lower::lower(db, expander, params, body)
365     }
366
367     fn shrink_to_fit(&mut self) {
368         let Self { _c: _, body_expr: _, block_scopes, exprs, labels, params, pats } = self;
369         block_scopes.shrink_to_fit();
370         exprs.shrink_to_fit();
371         labels.shrink_to_fit();
372         params.shrink_to_fit();
373         pats.shrink_to_fit();
374     }
375 }
376
377 impl Index<ExprId> for Body {
378     type Output = Expr;
379
380     fn index(&self, expr: ExprId) -> &Expr {
381         &self.exprs[expr]
382     }
383 }
384
385 impl Index<PatId> for Body {
386     type Output = Pat;
387
388     fn index(&self, pat: PatId) -> &Pat {
389         &self.pats[pat]
390     }
391 }
392
393 impl Index<LabelId> for Body {
394     type Output = Label;
395
396     fn index(&self, label: LabelId) -> &Label {
397         &self.labels[label]
398     }
399 }
400
401 // FIXME: Change `node_` prefix to something more reasonable.
402 // Perhaps `expr_syntax` and `expr_id`?
403 impl BodySourceMap {
404     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
405         self.expr_map_back[expr].clone()
406     }
407
408     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
409         let src = node.map(|it| AstPtr::new(it));
410         self.expr_map.get(&src).cloned()
411     }
412
413     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
414         let src = node.map(|it| AstPtr::new(it));
415         self.expansions.get(&src).cloned()
416     }
417
418     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
419         self.pat_map_back[pat].clone()
420     }
421
422     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
423         let src = node.map(|it| Either::Left(AstPtr::new(it)));
424         self.pat_map.get(&src).cloned()
425     }
426
427     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
428         let src = node.map(|it| Either::Right(AstPtr::new(it)));
429         self.pat_map.get(&src).cloned()
430     }
431
432     pub fn label_syntax(&self, label: LabelId) -> LabelSource {
433         self.label_map_back[label].clone()
434     }
435
436     pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
437         let src = node.map(|it| AstPtr::new(it));
438         self.label_map.get(&src).cloned()
439     }
440
441     pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
442         self.field_map_back[&expr].clone()
443     }
444     pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
445         let src = node.map(|it| AstPtr::new(it));
446         self.field_map.get(&src).cloned()
447     }
448
449     /// Get a reference to the body source map's diagnostics.
450     pub fn diagnostics(&self) -> &[BodyDiagnostic] {
451         &self.diagnostics
452     }
453 }