1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
8 use std::{mem, ops::Index, sync::Arc};
11 use cfg::{CfgExpr, CfgOptions};
12 use drop_bomb::DropBomb;
15 ast_id_map::AstIdMap, hygiene::Hygiene, AstId, ExpandError, ExpandResult, HirFileId, InFile,
18 use la_arena::{Arena, ArenaMap};
21 use rustc_hash::FxHashMap;
22 use smallvec::SmallVec;
23 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
26 attr::{Attrs, RawAttrs},
28 expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
29 item_scope::BuiltinShadowMode,
32 path::{ModPath, Path},
34 AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, MacroId, ModuleId,
38 pub use lower::LowerCtx;
40 /// A subset of Expander that only deals with cfg attributes. We only need it to
41 /// avoid cyclic queries in crate def map during enum processing.
43 pub(crate) struct CfgExpander {
44 cfg_options: CfgOptions,
51 cfg_expander: CfgExpander,
53 current_file_id: HirFileId,
54 ast_id_map: Arc<AstIdMap>,
55 module: LocalModuleId,
56 recursion_limit: usize,
62 current_file_id: HirFileId,
65 let hygiene = Hygiene::new(db.upcast(), current_file_id);
66 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
67 CfgExpander { cfg_options, hygiene, krate }
70 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
71 RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
74 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
75 let attrs = self.parse_attrs(db, owner);
76 attrs.is_cfg_enabled(&self.cfg_options)
81 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
82 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
83 let def_map = module.def_map(db);
84 let ast_id_map = db.ast_id_map(current_file_id);
90 module: module.local_id,
95 pub fn enter_expand<T: ast::AstNode>(
98 macro_call: ast::MacroCall,
99 ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
100 if self.recursion_limit(db).check(self.recursion_limit + 1).is_err() {
101 cov_mark::hit!(your_stack_belongs_to_me);
102 return Ok(ExpandResult::only_err(ExpandError::Other(
103 "reached recursion limit during macro expansion".into(),
107 let macro_call = InFile::new(self.current_file_id, ¯o_call);
110 |path| self.resolve_path_as_macro(db, &path).map(|it| macro_id_to_def_id(db, it));
114 macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
115 err.get_or_insert(e);
117 let call_id = match call_id {
120 return Ok(ExpandResult { value: None, err });
124 Ok(self.enter_expand_inner(db, call_id, err))
127 pub fn enter_expand_id<T: ast::AstNode>(
129 db: &dyn DefDatabase,
130 call_id: MacroCallId,
131 ) -> ExpandResult<Option<(Mark, T)>> {
132 self.enter_expand_inner(db, call_id, None)
135 fn enter_expand_inner<T: ast::AstNode>(
137 db: &dyn DefDatabase,
138 call_id: MacroCallId,
139 mut err: Option<ExpandError>,
140 ) -> ExpandResult<Option<(Mark, T)>> {
142 err = db.macro_expand_error(call_id);
145 let file_id = call_id.as_file();
147 let raw_node = match db.parse_or_expand(file_id) {
150 // Only `None` if the macro expansion produced no usable AST.
152 tracing::warn!("no error despite `parse_or_expand` failing");
155 return ExpandResult::only_err(err.unwrap_or_else(|| {
156 ExpandError::Other("failed to parse macro invocation".into())
161 let node = match T::cast(raw_node) {
164 // This can happen without being an error, so only forward previous errors.
165 return ExpandResult { value: None, err };
169 tracing::debug!("macro expansion {:#?}", node.syntax());
171 self.recursion_limit += 1;
173 file_id: self.current_file_id,
174 ast_id_map: mem::take(&mut self.ast_id_map),
175 bomb: DropBomb::new("expansion mark dropped"),
177 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
178 self.current_file_id = file_id;
179 self.ast_id_map = db.ast_id_map(file_id);
181 ExpandResult { value: Some((mark, node)), err }
184 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
185 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
186 self.current_file_id = mark.file_id;
187 self.ast_id_map = mem::take(&mut mark.ast_id_map);
188 self.recursion_limit -= 1;
192 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
193 InFile { file_id: self.current_file_id, value }
196 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
197 self.cfg_expander.parse_attrs(db, owner)
200 pub(crate) fn cfg_options(&self) -> &CfgOptions {
201 &self.cfg_expander.cfg_options
204 pub fn current_file_id(&self) -> HirFileId {
208 fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
209 let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
210 Path::from_src(path, &ctx)
213 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroId> {
214 self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
217 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
218 let file_local_id = self.ast_id_map.ast_id(item);
219 AstId::new(self.current_file_id, file_local_id)
222 fn recursion_limit(&self, db: &dyn DefDatabase) -> Limit {
223 let limit = db.crate_limits(self.cfg_expander.krate).recursion_limit as _;
226 return Limit::new(limit);
228 // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
230 return Limit::new(std::cmp::min(32, limit));
237 ast_id_map: Arc<AstIdMap>,
241 /// The body of an item (function, const etc.).
242 #[derive(Debug, Eq, PartialEq)]
244 pub exprs: Arena<Expr>,
245 pub pats: Arena<Pat>,
246 pub or_pats: FxHashMap<PatId, Arc<[PatId]>>,
247 pub labels: Arena<Label>,
248 /// The patterns for the function's parameters. While the parameter types are
249 /// part of the function signature, the patterns are not (they don't change
250 /// the external type of the function).
252 /// If this `Body` is for the body of a constant, this will just be
254 pub params: Vec<PatId>,
255 /// The `ExprId` of the actual body expression.
256 pub body_expr: ExprId,
257 /// Block expressions in this body that may contain inner items.
258 block_scopes: Vec<BlockId>,
262 pub type ExprPtr = AstPtr<ast::Expr>;
263 pub type ExprSource = InFile<ExprPtr>;
265 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
266 pub type PatSource = InFile<PatPtr>;
268 pub type LabelPtr = AstPtr<ast::Label>;
269 pub type LabelSource = InFile<LabelPtr>;
270 /// An item body together with the mapping from syntax nodes to HIR expression
271 /// IDs. This is needed to go from e.g. a position in a file to the HIR
272 /// expression containing it; but for type inference etc., we want to operate on
273 /// a structure that is agnostic to the actual positions of expressions in the
274 /// file, so that we don't recompute types whenever some whitespace is typed.
276 /// One complication here is that, due to macro expansion, a single `Body` might
277 /// be spread across several files. So, for each ExprId and PatId, we record
278 /// both the HirFileId and the position inside the file. However, we only store
279 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
280 /// this properly for macros.
281 #[derive(Default, Debug, Eq, PartialEq)]
282 pub struct BodySourceMap {
283 expr_map: FxHashMap<ExprSource, ExprId>,
284 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
286 pat_map: FxHashMap<PatSource, PatId>,
287 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
289 label_map: FxHashMap<LabelSource, LabelId>,
290 label_map_back: ArenaMap<LabelId, LabelSource>,
292 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
293 /// Instead, we use id of expression (`92`) to identify the field.
294 field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
295 field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
297 /// Maps a macro call to its lowered expressions, a single one if it expands to an expression,
298 /// or multiple if it expands to MacroStmts.
299 macro_call_to_exprs: FxHashMap<InFile<AstPtr<ast::MacroCall>>, SmallVec<[ExprId; 1]>>,
301 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
303 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
304 /// the source map (since they're just as volatile).
305 diagnostics: Vec<BodyDiagnostic>,
308 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
309 pub struct SyntheticSyntax;
311 #[derive(Debug, Eq, PartialEq)]
312 pub enum BodyDiagnostic {
313 InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
314 MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
315 UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
316 UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
320 pub(crate) fn body_with_source_map_query(
321 db: &dyn DefDatabase,
323 ) -> (Arc<Body>, Arc<BodySourceMap>) {
324 let _p = profile::span("body_with_source_map_query");
325 let mut params = None;
327 let (file_id, module, body) = match def {
328 DefWithBodyId::FunctionId(f) => {
329 let f = f.lookup(db);
330 let src = f.source(db);
331 params = src.value.param_list();
332 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
334 DefWithBodyId::ConstId(c) => {
335 let c = c.lookup(db);
336 let src = c.source(db);
337 (src.file_id, c.module(db), src.value.body())
339 DefWithBodyId::StaticId(s) => {
340 let s = s.lookup(db);
341 let src = s.source(db);
342 (src.file_id, s.module(db), src.value.body())
345 let expander = Expander::new(db, file_id, module);
346 let (mut body, source_map) = Body::new(db, expander, params, body);
347 body.shrink_to_fit();
348 (Arc::new(body), Arc::new(source_map))
351 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
352 db.body_with_source_map(def).0
355 /// Returns an iterator over all block expressions in this body that define inner items.
358 db: &'a dyn DefDatabase,
359 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
362 .map(move |&block| (block, db.block_def_map(block).expect("block ID without DefMap")))
365 pub fn pattern_representative(&self, pat: PatId) -> PatId {
366 self.or_pats.get(&pat).and_then(|pats| pats.first().copied()).unwrap_or(pat)
369 /// Retrieves all ident patterns this pattern shares the ident with.
370 pub fn ident_patterns_for<'slf>(&'slf self, pat: &'slf PatId) -> &'slf [PatId] {
371 match self.or_pats.get(pat) {
372 Some(pats) => &**pats,
373 None => std::slice::from_ref(pat),
378 db: &dyn DefDatabase,
380 params: Option<ast::ParamList>,
381 body: Option<ast::Expr>,
382 ) -> (Body, BodySourceMap) {
383 lower::lower(db, expander, params, body)
386 fn shrink_to_fit(&mut self) {
387 let Self { _c: _, body_expr: _, block_scopes, or_pats, exprs, labels, params, pats } = self;
388 block_scopes.shrink_to_fit();
389 or_pats.shrink_to_fit();
390 exprs.shrink_to_fit();
391 labels.shrink_to_fit();
392 params.shrink_to_fit();
393 pats.shrink_to_fit();
397 impl Index<ExprId> for Body {
400 fn index(&self, expr: ExprId) -> &Expr {
405 impl Index<PatId> for Body {
408 fn index(&self, pat: PatId) -> &Pat {
413 impl Index<LabelId> for Body {
416 fn index(&self, label: LabelId) -> &Label {
421 // FIXME: Change `node_` prefix to something more reasonable.
422 // Perhaps `expr_syntax` and `expr_id`?
424 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
425 self.expr_map_back[expr].clone()
428 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
429 let src = node.map(AstPtr::new);
430 self.expr_map.get(&src).cloned()
433 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
434 let src = node.map(AstPtr::new);
435 self.expansions.get(&src).cloned()
438 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
439 self.pat_map_back[pat].clone()
442 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
443 let src = node.map(|it| Either::Left(AstPtr::new(it)));
444 self.pat_map.get(&src).cloned()
447 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
448 let src = node.map(|it| Either::Right(AstPtr::new(it)));
449 self.pat_map.get(&src).cloned()
452 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
453 self.label_map_back[label].clone()
456 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
457 let src = node.map(AstPtr::new);
458 self.label_map.get(&src).cloned()
461 pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
462 self.field_map_back[&expr].clone()
464 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
465 let src = node.map(AstPtr::new);
466 self.field_map.get(&src).cloned()
469 pub fn macro_expansion_expr(&self, node: InFile<&ast::MacroCall>) -> Option<&[ExprId]> {
470 let src = node.map(AstPtr::new);
471 self.macro_call_to_exprs.get(&src).map(|it| &**it)
474 /// Get a reference to the body source map's diagnostics.
475 pub fn diagnostics(&self) -> &[BodyDiagnostic] {