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, ExpandResult, HirFileId, InFile, MacroDefId,
17 use la_arena::{Arena, ArenaMap};
19 use rustc_hash::FxHashMap;
20 use syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
23 attr::{Attrs, RawAttrs},
25 expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
26 item_scope::BuiltinShadowMode,
28 path::{ModPath, Path},
30 AsMacroCall, BlockId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleId,
34 pub use lower::LowerCtx;
36 /// A subset of Expander that only deals with cfg attributes. We only need it to
37 /// avoid cyclic queries in crate def map during enum processing.
39 pub(crate) struct CfgExpander {
40 cfg_options: CfgOptions,
47 cfg_expander: CfgExpander,
49 current_file_id: HirFileId,
50 ast_id_map: Arc<AstIdMap>,
51 module: LocalModuleId,
52 recursion_limit: usize,
56 const EXPANSION_RECURSION_LIMIT: usize = 32;
59 const EXPANSION_RECURSION_LIMIT: usize = 128;
64 current_file_id: HirFileId,
67 let hygiene = Hygiene::new(db.upcast(), current_file_id);
68 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
69 CfgExpander { cfg_options, hygiene, krate }
72 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
73 RawAttrs::new(db, owner, &self.hygiene).filter(db, self.krate)
76 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> bool {
77 let attrs = self.parse_attrs(db, owner);
78 attrs.is_cfg_enabled(&self.cfg_options)
83 pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
84 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
85 let def_map = module.def_map(db);
86 let ast_id_map = db.ast_id_map(current_file_id);
92 module: module.local_id,
97 pub fn enter_expand<T: ast::AstNode>(
100 macro_call: ast::MacroCall,
101 ) -> Result<ExpandResult<Option<(Mark, T)>>, UnresolvedMacro> {
102 if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
103 cov_mark::hit!(your_stack_belongs_to_me);
104 return Ok(ExpandResult::str_err(
105 "reached recursion limit during macro expansion".into(),
109 let macro_call = InFile::new(self.current_file_id, ¯o_call);
112 |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
116 macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
117 err.get_or_insert(e);
119 let call_id = match call_id {
122 return Ok(ExpandResult { value: None, err });
127 err = db.macro_expand_error(call_id);
130 let file_id = call_id.as_file();
132 let raw_node = match db.parse_or_expand(file_id) {
135 // Only `None` if the macro expansion produced no usable AST.
137 log::warn!("no error despite `parse_or_expand` failing");
140 return Ok(ExpandResult::only_err(err.unwrap_or_else(|| {
141 mbe::ExpandError::Other("failed to parse macro invocation".into())
146 let node = match T::cast(raw_node) {
149 // This can happen without being an error, so only forward previous errors.
150 return Ok(ExpandResult { value: None, err });
154 log::debug!("macro expansion {:#?}", node.syntax());
156 self.recursion_limit += 1;
158 file_id: self.current_file_id,
159 ast_id_map: mem::take(&mut self.ast_id_map),
160 bomb: DropBomb::new("expansion mark dropped"),
162 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
163 self.current_file_id = file_id;
164 self.ast_id_map = db.ast_id_map(file_id);
166 Ok(ExpandResult { value: Some((mark, node)), err })
169 pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
170 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
171 self.current_file_id = mark.file_id;
172 self.ast_id_map = mem::take(&mut mark.ast_id_map);
173 self.recursion_limit -= 1;
177 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
178 InFile { file_id: self.current_file_id, value }
181 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
182 self.cfg_expander.parse_attrs(db, owner)
185 pub(crate) fn cfg_options(&self) -> &CfgOptions {
186 &self.cfg_expander.cfg_options
189 pub fn current_file_id(&self) -> HirFileId {
193 fn parse_path(&mut self, db: &dyn DefDatabase, path: ast::Path) -> Option<Path> {
194 let ctx = LowerCtx::with_hygiene(db, &self.cfg_expander.hygiene);
195 Path::from_src(path, &ctx)
198 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
199 self.def_map.resolve_path(db, self.module, path, BuiltinShadowMode::Other).0.take_macros()
202 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
203 let file_local_id = self.ast_id_map.ast_id(item);
204 AstId::new(self.current_file_id, file_local_id)
211 ast_id_map: Arc<AstIdMap>,
215 /// The body of an item (function, const etc.).
216 #[derive(Debug, Eq, PartialEq)]
218 pub exprs: Arena<Expr>,
219 pub pats: Arena<Pat>,
220 pub labels: Arena<Label>,
221 /// The patterns for the function's parameters. While the parameter types are
222 /// part of the function signature, the patterns are not (they don't change
223 /// the external type of the function).
225 /// If this `Body` is for the body of a constant, this will just be
227 pub params: Vec<PatId>,
228 /// The `ExprId` of the actual body expression.
229 pub body_expr: ExprId,
230 /// Block expressions in this body that may contain inner items.
231 block_scopes: Vec<BlockId>,
235 pub type ExprPtr = AstPtr<ast::Expr>;
236 pub type ExprSource = InFile<ExprPtr>;
238 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
239 pub type PatSource = InFile<PatPtr>;
241 pub type LabelPtr = AstPtr<ast::Label>;
242 pub type LabelSource = InFile<LabelPtr>;
243 /// An item body together with the mapping from syntax nodes to HIR expression
244 /// IDs. This is needed to go from e.g. a position in a file to the HIR
245 /// expression containing it; but for type inference etc., we want to operate on
246 /// a structure that is agnostic to the actual positions of expressions in the
247 /// file, so that we don't recompute types whenever some whitespace is typed.
249 /// One complication here is that, due to macro expansion, a single `Body` might
250 /// be spread across several files. So, for each ExprId and PatId, we record
251 /// both the HirFileId and the position inside the file. However, we only store
252 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
253 /// this properly for macros.
254 #[derive(Default, Debug, Eq, PartialEq)]
255 pub struct BodySourceMap {
256 expr_map: FxHashMap<ExprSource, ExprId>,
257 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
259 pat_map: FxHashMap<PatSource, PatId>,
260 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
262 label_map: FxHashMap<LabelSource, LabelId>,
263 label_map_back: ArenaMap<LabelId, LabelSource>,
265 /// We don't create explicit nodes for record fields (`S { record_field: 92 }`).
266 /// Instead, we use id of expression (`92`) to identify the field.
267 field_map: FxHashMap<InFile<AstPtr<ast::RecordExprField>>, ExprId>,
268 field_map_back: FxHashMap<ExprId, InFile<AstPtr<ast::RecordExprField>>>,
270 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
272 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
273 /// the source map (since they're just as volatile).
274 diagnostics: Vec<BodyDiagnostic>,
277 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
278 pub struct SyntheticSyntax;
280 #[derive(Debug, Eq, PartialEq)]
281 pub enum BodyDiagnostic {
282 InactiveCode { node: InFile<SyntaxNodePtr>, cfg: CfgExpr, opts: CfgOptions },
283 MacroError { node: InFile<AstPtr<ast::MacroCall>>, message: String },
284 UnresolvedProcMacro { node: InFile<AstPtr<ast::MacroCall>> },
285 UnresolvedMacroCall { node: InFile<AstPtr<ast::MacroCall>>, path: ModPath },
289 pub(crate) fn body_with_source_map_query(
290 db: &dyn DefDatabase,
292 ) -> (Arc<Body>, Arc<BodySourceMap>) {
293 let _p = profile::span("body_with_source_map_query");
294 let mut params = None;
296 let (file_id, module, body) = match def {
297 DefWithBodyId::FunctionId(f) => {
298 let f = f.lookup(db);
299 let src = f.source(db);
300 params = src.value.param_list();
301 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
303 DefWithBodyId::ConstId(c) => {
304 let c = c.lookup(db);
305 let src = c.source(db);
306 (src.file_id, c.module(db), src.value.body())
308 DefWithBodyId::StaticId(s) => {
309 let s = s.lookup(db);
310 let src = s.source(db);
311 (src.file_id, s.module(db), src.value.body())
314 let expander = Expander::new(db, file_id, module);
315 let (mut body, source_map) = Body::new(db, expander, params, body);
316 body.shrink_to_fit();
317 (Arc::new(body), Arc::new(source_map))
320 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
321 db.body_with_source_map(def).0
324 /// Returns an iterator over all block expressions in this body that define inner items.
327 db: &'a dyn DefDatabase,
328 ) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + '_ {
331 .map(move |block| (*block, db.block_def_map(*block).expect("block ID without DefMap")))
335 db: &dyn DefDatabase,
337 params: Option<ast::ParamList>,
338 body: Option<ast::Expr>,
339 ) -> (Body, BodySourceMap) {
340 lower::lower(db, expander, params, body)
343 fn shrink_to_fit(&mut self) {
344 let Self { _c: _, body_expr: _, block_scopes, exprs, labels, params, pats } = self;
345 block_scopes.shrink_to_fit();
346 exprs.shrink_to_fit();
347 labels.shrink_to_fit();
348 params.shrink_to_fit();
349 pats.shrink_to_fit();
353 impl Index<ExprId> for Body {
356 fn index(&self, expr: ExprId) -> &Expr {
361 impl Index<PatId> for Body {
364 fn index(&self, pat: PatId) -> &Pat {
369 impl Index<LabelId> for Body {
372 fn index(&self, label: LabelId) -> &Label {
377 // FIXME: Change `node_` prefix to something more reasonable.
378 // Perhaps `expr_syntax` and `expr_id`?
380 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
381 self.expr_map_back[expr].clone()
384 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
385 let src = node.map(|it| AstPtr::new(it));
386 self.expr_map.get(&src).cloned()
389 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
390 let src = node.map(|it| AstPtr::new(it));
391 self.expansions.get(&src).cloned()
394 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
395 self.pat_map_back[pat].clone()
398 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
399 let src = node.map(|it| Either::Left(AstPtr::new(it)));
400 self.pat_map.get(&src).cloned()
403 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
404 let src = node.map(|it| Either::Right(AstPtr::new(it)));
405 self.pat_map.get(&src).cloned()
408 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
409 self.label_map_back[label].clone()
412 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
413 let src = node.map(|it| AstPtr::new(it));
414 self.label_map.get(&src).cloned()
417 pub fn field_syntax(&self, expr: ExprId) -> InFile<AstPtr<ast::RecordExprField>> {
418 self.field_map_back[&expr].clone()
420 pub fn node_field(&self, node: InFile<&ast::RecordExprField>) -> Option<ExprId> {
421 let src = node.map(|it| AstPtr::new(it));
422 self.field_map.get(&src).cloned()
425 /// Get a reference to the body source map's diagnostics.
426 pub fn diagnostics(&self) -> &[BodyDiagnostic] {