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,
16 MacroCallId, MacroDefId,
18 use la_arena::{Arena, ArenaMap};
21 use rustc_hash::FxHashMap;
22 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
25 attr::{Attrs, RawAttrs},
27 expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
28 item_scope::BuiltinShadowMode,
30 path::{ModPath, Path},
32 AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleId,
36 pub use lower::LowerCtx;
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.
41 pub(crate) struct CfgExpander {
42 cfg_options: CfgOptions,
49 cfg_expander: CfgExpander,
51 current_file_id: HirFileId,
52 ast_id_map: Arc<AstIdMap>,
53 module: LocalModuleId,
54 recursion_limit: usize,
58 static EXPANSION_RECURSION_LIMIT: Limit = Limit::new(32);
61 static EXPANSION_RECURSION_LIMIT: Limit = Limit::new(128);
66 current_file_id: HirFileId,
69 let hygiene = Hygiene::new(db.upcast(), current_file_id);
70 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
71 CfgExpander { cfg_options, hygiene, krate }
74 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
75 RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
78 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> bool {
79 let attrs = self.parse_attrs(db, owner);
80 attrs.is_cfg_enabled(&self.cfg_options)
85 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
86 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
87 let def_map = module.def_map(db);
88 let ast_id_map = db.ast_id_map(current_file_id);
94 module: module.local_id,
99 pub fn enter_expand<T: ast::AstNode>(
101 db: &dyn DefDatabase,
102 macro_call: ast::MacroCall,
103 ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
104 if EXPANSION_RECURSION_LIMIT.check(self.recursion_limit + 1).is_err() {
105 cov_mark::hit!(your_stack_belongs_to_me);
106 return Ok(ExpandResult::str_err(
107 "reached recursion limit during macro expansion".into(),
111 let macro_call = InFile::new(self.current_file_id, ¯o_call);
114 |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
118 macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
119 err.get_or_insert(e);
121 let call_id = match call_id {
124 return Ok(ExpandResult { value: None, err });
128 Ok(self.enter_expand_inner(db, call_id, err))
131 pub fn enter_expand_id<T: ast::AstNode>(
133 db: &dyn DefDatabase,
134 call_id: MacroCallId,
135 ) -> ExpandResult<Option<(Mark, T)>> {
136 self.enter_expand_inner(db, call_id, None)
139 fn enter_expand_inner<T: ast::AstNode>(
141 db: &dyn DefDatabase,
142 call_id: MacroCallId,
143 mut err: Option<ExpandError>,
144 ) -> ExpandResult<Option<(Mark, T)>> {
146 err = db.macro_expand_error(call_id);
149 let file_id = call_id.as_file();
151 let raw_node = match db.parse_or_expand(file_id) {
154 // Only `None` if the macro expansion produced no usable AST.
156 tracing::warn!("no error despite `parse_or_expand` failing");
159 return ExpandResult::only_err(err.unwrap_or_else(|| {
160 mbe::ExpandError::Other("failed to parse macro invocation".into())
165 let node = match T::cast(raw_node) {
168 // This can happen without being an error, so only forward previous errors.
169 return ExpandResult { value: None, err };
173 tracing::debug!("macro expansion {:#?}", node.syntax());
175 self.recursion_limit += 1;
177 file_id: self.current_file_id,
178 ast_id_map: mem::take(&mut self.ast_id_map),
179 bomb: DropBomb::new("expansion mark dropped"),
181 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
182 self.current_file_id = file_id;
183 self.ast_id_map = db.ast_id_map(file_id);
185 ExpandResult { value: Some((mark, node)), err }
188 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
189 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
190 self.current_file_id = mark.file_id;
191 self.ast_id_map = mem::take(&mut mark.ast_id_map);
192 self.recursion_limit -= 1;
196 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
197 InFile { file_id: self.current_file_id, value }
200 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::HasAttrs) -> Attrs {
201 self.cfg_expander.parse_attrs(db, owner)
204 pub(crate) fn cfg_options(&self) -> &CfgOptions {
205 &self.cfg_expander.cfg_options
208 pub fn current_file_id(&self) -> HirFileId {
212 fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
213 let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
214 Path::from_src(path, &ctx)
217 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
218 self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
221 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
222 let file_local_id = self.ast_id_map.ast_id(item);
223 AstId::new(self.current_file_id, file_local_id)
230 ast_id_map: Arc<AstIdMap>,
234 /// The body of an item (function, const etc.).
235 #[derive(Debug, Eq, PartialEq)]
237 pub exprs: Arena<Expr>,
238 pub pats: Arena<Pat>,
239 pub labels: Arena<Label>,
240 /// The patterns for the function's parameters. While the parameter types are
241 /// part of the function signature, the patterns are not (they don't change
242 /// the external type of the function).
244 /// If this `Body` is for the body of a constant, this will just be
246 pub params: Vec<PatId>,
247 /// The `ExprId` of the actual body expression.
248 pub body_expr: ExprId,
249 /// Block expressions in this body that may contain inner items.
250 block_scopes: Vec<BlockId>,
254 pub type ExprPtr = AstPtr<ast::Expr>;
255 pub type ExprSource = InFile<ExprPtr>;
257 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
258 pub type PatSource = InFile<PatPtr>;
260 pub type LabelPtr = AstPtr<ast::Label>;
261 pub type LabelSource = InFile<LabelPtr>;
262 /// An item body together with the mapping from syntax nodes to HIR expression
263 /// IDs. This is needed to go from e.g. a position in a file to the HIR
264 /// expression containing it; but for type inference etc., we want to operate on
265 /// a structure that is agnostic to the actual positions of expressions in the
266 /// file, so that we don't recompute types whenever some whitespace is typed.
268 /// One complication here is that, due to macro expansion, a single `Body` might
269 /// be spread across several files. So, for each ExprId and PatId, we record
270 /// both the HirFileId and the position inside the file. However, we only store
271 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
272 /// this properly for macros.
273 #[derive(Default, Debug, Eq, PartialEq)]
274 pub struct BodySourceMap {
275 expr_map: FxHashMap<ExprSource, ExprId>,
276 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
278 pat_map: FxHashMap<PatSource, PatId>,
279 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
281 label_map: FxHashMap<LabelSource, LabelId>,
282 label_map_back: ArenaMap<LabelId, LabelSource>,
284 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
285 /// Instead, we use id of expression (`92`) to identify the field.
286 field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
287 field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
289 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
291 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
292 /// the source map (since they're just as volatile).
293 diagnostics: Vec<BodyDiagnostic>,
296 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
297 pub struct SyntheticSyntax;
299 #[derive(Debug, Eq, PartialEq)]
300 pub enum BodyDiagnostic {
301 InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
302 MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
303 UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
304 UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
308 pub(crate) fn body_with_source_map_query(
309 db: &dyn DefDatabase,
311 ) -> (Arc<Body>, Arc<BodySourceMap>) {
312 let _p = profile::span("body_with_source_map_query");
313 let mut params = None;
315 let (file_id, module, body) = match def {
316 DefWithBodyId::FunctionId(f) => {
317 let f = f.lookup(db);
318 let src = f.source(db);
319 params = src.value.param_list();
320 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
322 DefWithBodyId::ConstId(c) => {
323 let c = c.lookup(db);
324 let src = c.source(db);
325 (src.file_id, c.module(db), src.value.body())
327 DefWithBodyId::StaticId(s) => {
328 let s = s.lookup(db);
329 let src = s.source(db);
330 (src.file_id, s.module(db), src.value.body())
333 let expander = Expander::new(db, file_id, module);
334 let (mut body, source_map) = Body::new(db, expander, params, body);
335 body.shrink_to_fit();
336 (Arc::new(body), Arc::new(source_map))
339 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
340 db.body_with_source_map(def).0
343 /// Returns an iterator over all block expressions in this body that define inner items.
346 db: &'a dyn DefDatabase,
347 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
350 .map(move |block| (*block, db.block_def_map(*block).expect("block ID without DefMap")))
354 db: &dyn DefDatabase,
356 params: Option<ast::ParamList>,
357 body: Option<ast::Expr>,
358 ) -> (Body, BodySourceMap) {
359 lower::lower(db, expander, params, body)
362 fn shrink_to_fit(&mut self) {
363 let Self { _c: _, body_expr: _, block_scopes, exprs, labels, params, pats } = self;
364 block_scopes.shrink_to_fit();
365 exprs.shrink_to_fit();
366 labels.shrink_to_fit();
367 params.shrink_to_fit();
368 pats.shrink_to_fit();
372 impl Index<ExprId> for Body {
375 fn index(&self, expr: ExprId) -> &Expr {
380 impl Index<PatId> for Body {
383 fn index(&self, pat: PatId) -> &Pat {
388 impl Index<LabelId> for Body {
391 fn index(&self, label: LabelId) -> &Label {
396 // FIXME: Change `node_` prefix to something more reasonable.
397 // Perhaps `expr_syntax` and `expr_id`?
399 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
400 self.expr_map_back[expr].clone()
403 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
404 let src = node.map(|it| AstPtr::new(it));
405 self.expr_map.get(&src).cloned()
408 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
409 let src = node.map(|it| AstPtr::new(it));
410 self.expansions.get(&src).cloned()
413 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
414 self.pat_map_back[pat].clone()
417 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
418 let src = node.map(|it| Either::Left(AstPtr::new(it)));
419 self.pat_map.get(&src).cloned()
422 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
423 let src = node.map(|it| Either::Right(AstPtr::new(it)));
424 self.pat_map.get(&src).cloned()
427 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
428 self.label_map_back[label].clone()
431 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
432 let src = node.map(|it| AstPtr::new(it));
433 self.label_map.get(&src).cloned()
436 pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
437 self.field_map_back[&expr].clone()
439 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
440 let src = node.map(|it| AstPtr::new(it));
441 self.field_map.get(&src).cloned()
444 /// Get a reference to the body source map's diagnostics.
445 pub fn diagnostics(&self) -> &[BodyDiagnostic] {