]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body.rs
Propagate eager expansion errors
[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 arena::{map::ArenaMap, Arena};
12 use base_db::CrateId;
13 use cfg::CfgOptions;
14 use drop_bomb::DropBomb;
15 use either::Either;
16 use hir_expand::{
17     ast_id_map::AstIdMap, diagnostics::DiagnosticSink, hygiene::Hygiene, AstId, ExpandResult,
18     HirFileId, InFile, MacroDefId,
19 };
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,
28     db::DefDatabase,
29     expr::{Expr, ExprId, Pat, PatId},
30     item_scope::BuiltinShadowMode,
31     item_scope::ItemScope,
32     nameres::CrateDefMap,
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 }
44
45 pub(crate) struct Expander {
46     cfg_expander: CfgExpander,
47     crate_def_map: Arc<CrateDefMap>,
48     current_file_id: HirFileId,
49     ast_id_map: Arc<AstIdMap>,
50     module: ModuleId,
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 }
69     }
70
71     pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs {
72         Attrs::new(owner, &self.hygiene)
73     }
74
75     pub(crate) fn is_cfg_enabled(&self, owner: &dyn ast::AttrsOwner) -> bool {
76         let attrs = self.parse_attrs(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 crate_def_map = db.crate_def_map(module.krate);
89         let ast_id_map = db.ast_id_map(current_file_id);
90         Expander {
91             cfg_expander,
92             crate_def_map,
93             current_file_id,
94             ast_id_map,
95             module,
96             recursion_limit: 0,
97         }
98     }
99
100     pub(crate) fn enter_expand<T: ast::AstNode>(
101         &mut self,
102         db: &dyn DefDatabase,
103         local_scope: Option<&ItemScope>,
104         macro_call: ast::MacroCall,
105     ) -> ExpandResult<Option<(Mark, T)>> {
106         self.recursion_limit += 1;
107         if self.recursion_limit > 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         let mark = Mark {
169             file_id: self.current_file_id,
170             ast_id_map: mem::take(&mut self.ast_id_map),
171             bomb: DropBomb::new("expansion mark dropped"),
172         };
173         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
174         self.current_file_id = file_id;
175         self.ast_id_map = db.ast_id_map(file_id);
176
177         ExpandResult { value: Some((mark, node)), err }
178     }
179
180     pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
181         self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
182         self.current_file_id = mark.file_id;
183         self.ast_id_map = mem::take(&mut mark.ast_id_map);
184         self.recursion_limit -= 1;
185         mark.bomb.defuse();
186     }
187
188     pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
189         InFile { file_id: self.current_file_id, value }
190     }
191
192     pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs {
193         self.cfg_expander.parse_attrs(owner)
194     }
195
196     pub(crate) fn cfg_options(&self) -> &CfgOptions {
197         &self.cfg_expander.cfg_options
198     }
199
200     fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
201         Path::from_src(path, &self.cfg_expander.hygiene)
202     }
203
204     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
205         self.crate_def_map
206             .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
207             .0
208             .take_macros()
209     }
210
211     fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
212         let file_local_id = self.ast_id_map.ast_id(item);
213         AstId::new(self.current_file_id, file_local_id)
214     }
215 }
216
217 pub(crate) struct Mark {
218     file_id: HirFileId,
219     ast_id_map: Arc<AstIdMap>,
220     bomb: DropBomb,
221 }
222
223 /// The body of an item (function, const etc.).
224 #[derive(Debug, Eq, PartialEq)]
225 pub struct Body {
226     pub exprs: Arena<Expr>,
227     pub pats: Arena<Pat>,
228     /// The patterns for the function's parameters. While the parameter types are
229     /// part of the function signature, the patterns are not (they don't change
230     /// the external type of the function).
231     ///
232     /// If this `Body` is for the body of a constant, this will just be
233     /// empty.
234     pub params: Vec<PatId>,
235     /// The `ExprId` of the actual body expression.
236     pub body_expr: ExprId,
237     pub item_scope: ItemScope,
238 }
239
240 pub type ExprPtr = AstPtr<ast::Expr>;
241 pub type ExprSource = InFile<ExprPtr>;
242
243 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
244 pub type PatSource = InFile<PatPtr>;
245
246 /// An item body together with the mapping from syntax nodes to HIR expression
247 /// IDs. This is needed to go from e.g. a position in a file to the HIR
248 /// expression containing it; but for type inference etc., we want to operate on
249 /// a structure that is agnostic to the actual positions of expressions in the
250 /// file, so that we don't recompute types whenever some whitespace is typed.
251 ///
252 /// One complication here is that, due to macro expansion, a single `Body` might
253 /// be spread across several files. So, for each ExprId and PatId, we record
254 /// both the HirFileId and the position inside the file. However, we only store
255 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
256 /// this properly for macros.
257 #[derive(Default, Debug, Eq, PartialEq)]
258 pub struct BodySourceMap {
259     expr_map: FxHashMap<ExprSource, ExprId>,
260     expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
261     pat_map: FxHashMap<PatSource, PatId>,
262     pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
263     field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
264     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
265
266     /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
267     /// the source map (since they're just as volatile).
268     diagnostics: Vec<diagnostics::BodyDiagnostic>,
269 }
270
271 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
272 pub struct SyntheticSyntax;
273
274 impl Body {
275     pub(crate) fn body_with_source_map_query(
276         db: &dyn DefDatabase,
277         def: DefWithBodyId,
278     ) -> (Arc<Body>, Arc<BodySourceMap>) {
279         let _p = profile::span("body_with_source_map_query");
280         let mut params = None;
281
282         let (file_id, module, body) = match def {
283             DefWithBodyId::FunctionId(f) => {
284                 let f = f.lookup(db);
285                 let src = f.source(db);
286                 params = src.value.param_list();
287                 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
288             }
289             DefWithBodyId::ConstId(c) => {
290                 let c = c.lookup(db);
291                 let src = c.source(db);
292                 (src.file_id, c.module(db), src.value.body())
293             }
294             DefWithBodyId::StaticId(s) => {
295                 let s = s.lookup(db);
296                 let src = s.source(db);
297                 (src.file_id, s.module(db), src.value.body())
298             }
299         };
300         let expander = Expander::new(db, file_id, module);
301         let (body, source_map) = Body::new(db, def, expander, params, body);
302         (Arc::new(body), Arc::new(source_map))
303     }
304
305     pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
306         db.body_with_source_map(def).0
307     }
308
309     fn new(
310         db: &dyn DefDatabase,
311         def: DefWithBodyId,
312         expander: Expander,
313         params: Option<ast::ParamList>,
314         body: Option<ast::Expr>,
315     ) -> (Body, BodySourceMap) {
316         lower::lower(db, def, expander, params, body)
317     }
318 }
319
320 impl Index<ExprId> for Body {
321     type Output = Expr;
322
323     fn index(&self, expr: ExprId) -> &Expr {
324         &self.exprs[expr]
325     }
326 }
327
328 impl Index<PatId> for Body {
329     type Output = Pat;
330
331     fn index(&self, pat: PatId) -> &Pat {
332         &self.pats[pat]
333     }
334 }
335
336 impl BodySourceMap {
337     pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
338         self.expr_map_back[expr].clone()
339     }
340
341     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
342         let src = node.map(|it| AstPtr::new(it));
343         self.expr_map.get(&src).cloned()
344     }
345
346     pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
347         let src = node.map(|it| AstPtr::new(it));
348         self.expansions.get(&src).cloned()
349     }
350
351     pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
352         self.pat_map_back[pat].clone()
353     }
354
355     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
356         let src = node.map(|it| Either::Left(AstPtr::new(it)));
357         self.pat_map.get(&src).cloned()
358     }
359
360     pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
361         let src = node.map(|it| Either::Right(AstPtr::new(it)));
362         self.pat_map.get(&src).cloned()
363     }
364
365     pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
366         self.field_map[&(expr, field)].clone()
367     }
368
369     pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
370         for diag in &self.diagnostics {
371             diag.add_to(sink);
372         }
373     }
374 }