1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
6 use std::{mem, ops::Index, sync::Arc};
8 use arena::{map::ArenaMap, Arena};
11 use drop_bomb::DropBomb;
13 use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, AstId, HirFileId, InFile, MacroDefId};
14 use rustc_hash::FxHashMap;
15 use syntax::{ast, AstNode, AstPtr};
18 pub(crate) use lower::LowerCtx;
23 expr::{Expr, ExprId, Pat, PatId},
24 item_scope::BuiltinShadowMode,
25 item_scope::ItemScope,
27 path::{ModPath, Path},
29 AsMacroCall, DefWithBodyId, HasModule, Lookup, ModuleId,
32 /// A subset of Expander that only deals with cfg attributes. We only need it to
33 /// avoid cyclic queries in crate def map during enum processing.
34 pub(crate) struct CfgExpander {
35 cfg_options: CfgOptions,
39 pub(crate) struct Expander {
40 cfg_expander: CfgExpander,
41 crate_def_map: Arc<CrateDefMap>,
42 current_file_id: HirFileId,
43 ast_id_map: Arc<AstIdMap>,
45 recursion_limit: usize,
49 const EXPANSION_RECURSION_LIMIT: usize = 32;
52 const EXPANSION_RECURSION_LIMIT: usize = 128;
57 current_file_id: HirFileId,
60 let hygiene = Hygiene::new(db.upcast(), current_file_id);
61 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
62 CfgExpander { cfg_options, hygiene }
65 pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs {
66 Attrs::new(owner, &self.hygiene)
69 pub(crate) fn is_cfg_enabled(&self, owner: &dyn ast::AttrsOwner) -> bool {
70 let attrs = self.parse_attrs(owner);
71 attrs.is_cfg_enabled(&self.cfg_options)
78 current_file_id: HirFileId,
81 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
82 let crate_def_map = db.crate_def_map(module.krate);
83 let ast_id_map = db.ast_id_map(current_file_id);
94 pub(crate) fn enter_expand<T: ast::AstNode>(
97 local_scope: Option<&ItemScope>,
98 macro_call: ast::MacroCall,
99 ) -> Option<(Mark, T)> {
100 self.recursion_limit += 1;
101 if self.recursion_limit > EXPANSION_RECURSION_LIMIT {
102 mark::hit!(your_stack_belongs_to_me);
106 let macro_call = InFile::new(self.current_file_id, ¯o_call);
108 let resolver = |path: ModPath| -> Option<MacroDefId> {
109 if let Some(local_scope) = local_scope {
110 if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) {
114 self.resolve_path_as_macro(db, &path)
117 if let Some(call_id) = macro_call.as_call_id(db, self.crate_def_map.krate, resolver) {
118 let file_id = call_id.as_file();
119 if let Some(node) = db.parse_or_expand(file_id) {
120 if let Some(expr) = T::cast(node) {
121 log::debug!("macro expansion {:#?}", expr.syntax());
124 file_id: self.current_file_id,
125 ast_id_map: mem::take(&mut self.ast_id_map),
126 bomb: DropBomb::new("expansion mark dropped"),
128 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
129 self.current_file_id = file_id;
130 self.ast_id_map = db.ast_id_map(file_id);
131 return Some((mark, expr));
136 // FIXME: Instead of just dropping the error from expansion
141 pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
142 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
143 self.current_file_id = mark.file_id;
144 self.ast_id_map = mem::take(&mut mark.ast_id_map);
145 self.recursion_limit -= 1;
149 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
150 InFile { file_id: self.current_file_id, value }
153 pub(crate) fn is_cfg_enabled(&self, owner: &dyn ast::AttrsOwner) -> bool {
154 self.cfg_expander.is_cfg_enabled(owner)
157 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
158 Path::from_src(path, &self.cfg_expander.hygiene)
161 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
163 .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
168 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
169 let file_local_id = self.ast_id_map.ast_id(item);
170 AstId::new(self.current_file_id, file_local_id)
174 pub(crate) struct Mark {
176 ast_id_map: Arc<AstIdMap>,
180 /// The body of an item (function, const etc.).
181 #[derive(Debug, Eq, PartialEq)]
183 pub exprs: Arena<Expr>,
184 pub pats: Arena<Pat>,
185 /// The patterns for the function's parameters. While the parameter types are
186 /// part of the function signature, the patterns are not (they don't change
187 /// the external type of the function).
189 /// If this `Body` is for the body of a constant, this will just be
191 pub params: Vec<PatId>,
192 /// The `ExprId` of the actual body expression.
193 pub body_expr: ExprId,
194 pub item_scope: ItemScope,
197 pub type ExprPtr = AstPtr<ast::Expr>;
198 pub type ExprSource = InFile<ExprPtr>;
200 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
201 pub type PatSource = InFile<PatPtr>;
203 /// An item body together with the mapping from syntax nodes to HIR expression
204 /// IDs. This is needed to go from e.g. a position in a file to the HIR
205 /// expression containing it; but for type inference etc., we want to operate on
206 /// a structure that is agnostic to the actual positions of expressions in the
207 /// file, so that we don't recompute types whenever some whitespace is typed.
209 /// One complication here is that, due to macro expansion, a single `Body` might
210 /// be spread across several files. So, for each ExprId and PatId, we record
211 /// both the HirFileId and the position inside the file. However, we only store
212 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
213 /// this properly for macros.
214 #[derive(Default, Debug, Eq, PartialEq)]
215 pub struct BodySourceMap {
216 expr_map: FxHashMap<ExprSource, ExprId>,
217 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
218 pat_map: FxHashMap<PatSource, PatId>,
219 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
220 field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
221 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
224 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
225 pub struct SyntheticSyntax;
228 pub(crate) fn body_with_source_map_query(
229 db: &dyn DefDatabase,
231 ) -> (Arc<Body>, Arc<BodySourceMap>) {
232 let _p = profile::span("body_with_source_map_query");
233 let mut params = None;
235 let (file_id, module, body) = match def {
236 DefWithBodyId::FunctionId(f) => {
237 let f = f.lookup(db);
238 let src = f.source(db);
239 params = src.value.param_list();
240 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
242 DefWithBodyId::ConstId(c) => {
243 let c = c.lookup(db);
244 let src = c.source(db);
245 (src.file_id, c.module(db), src.value.body())
247 DefWithBodyId::StaticId(s) => {
248 let s = s.lookup(db);
249 let src = s.source(db);
250 (src.file_id, s.module(db), src.value.body())
253 let expander = Expander::new(db, file_id, module);
254 let (body, source_map) = Body::new(db, def, expander, params, body);
255 (Arc::new(body), Arc::new(source_map))
258 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
259 db.body_with_source_map(def).0
263 db: &dyn DefDatabase,
266 params: Option<ast::ParamList>,
267 body: Option<ast::Expr>,
268 ) -> (Body, BodySourceMap) {
269 lower::lower(db, def, expander, params, body)
273 impl Index<ExprId> for Body {
276 fn index(&self, expr: ExprId) -> &Expr {
281 impl Index<PatId> for Body {
284 fn index(&self, pat: PatId) -> &Pat {
290 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
291 self.expr_map_back[expr].clone()
294 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
295 let src = node.map(|it| AstPtr::new(it));
296 self.expr_map.get(&src).cloned()
299 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
300 let src = node.map(|it| AstPtr::new(it));
301 self.expansions.get(&src).cloned()
304 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
305 self.pat_map_back[pat].clone()
308 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
309 let src = node.map(|it| Either::Left(AstPtr::new(it)));
310 self.pat_map.get(&src).cloned()
313 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
314 let src = node.map(|it| Either::Right(AstPtr::new(it)));
315 self.pat_map.get(&src).cloned()
318 pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
319 self.field_map[&(expr, field)].clone()
325 use base_db::{fixture::WithFixture, SourceDatabase};
326 use test_utils::mark;
328 use crate::ModuleDefId;
332 fn lower(ra_fixture: &str) -> Arc<Body> {
333 let (db, file_id) = crate::test_db::TestDB::with_single_file(ra_fixture);
335 let krate = db.crate_graph().iter().next().unwrap();
336 let def_map = db.crate_def_map(krate);
337 let module = def_map.modules_for_file(file_id).next().unwrap();
338 let module = &def_map[module];
339 let fn_def = match module.scope.declarations().next().unwrap() {
340 ModuleDefId::FunctionId(it) => it,
344 db.body(fn_def.into())
348 fn your_stack_belongs_to_me() {
349 mark::check!(your_stack_belongs_to_me);
352 macro_rules! n_nuple {
355 (n_nuple!($($rest)*)None,)
358 fn main() { n_nuple!(1,2,3); }