1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
9 use std::{mem, ops::Index, sync::Arc};
11 use arena::{map::ArenaMap, Arena};
14 use drop_bomb::DropBomb;
17 ast_id_map::AstIdMap, diagnostics::DiagnosticSink, hygiene::Hygiene, AstId, HirFileId, InFile,
20 use rustc_hash::FxHashMap;
21 use syntax::{ast, AstNode, AstPtr};
24 pub(crate) use lower::LowerCtx;
29 expr::{Expr, ExprId, Pat, PatId},
30 item_scope::BuiltinShadowMode,
31 item_scope::ItemScope,
33 path::{ModPath, Path},
35 AsMacroCall, DefWithBodyId, HasModule, Lookup, ModuleId,
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,
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>,
51 recursion_limit: usize,
55 const EXPANSION_RECURSION_LIMIT: usize = 32;
58 const EXPANSION_RECURSION_LIMIT: usize = 128;
63 current_file_id: HirFileId,
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 }
71 pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs {
72 Attrs::new(owner, &self.hygiene)
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)
84 current_file_id: HirFileId,
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);
100 pub(crate) fn enter_expand<T: ast::AstNode>(
102 db: &dyn DefDatabase,
103 local_scope: Option<&ItemScope>,
104 macro_call: ast::MacroCall,
105 ) -> Option<(Mark, T)> {
106 self.recursion_limit += 1;
107 if self.recursion_limit > EXPANSION_RECURSION_LIMIT {
108 mark::hit!(your_stack_belongs_to_me);
112 let macro_call = InFile::new(self.current_file_id, ¯o_call);
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)) {
120 self.resolve_path_as_macro(db, &path)
123 if let Some(call_id) = macro_call.as_call_id(db, self.crate_def_map.krate, resolver) {
124 let file_id = call_id.as_file();
125 if let Some(node) = db.parse_or_expand(file_id) {
126 if let Some(expr) = T::cast(node) {
127 log::debug!("macro expansion {:#?}", expr.syntax());
130 file_id: self.current_file_id,
131 ast_id_map: mem::take(&mut self.ast_id_map),
132 bomb: DropBomb::new("expansion mark dropped"),
134 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
135 self.current_file_id = file_id;
136 self.ast_id_map = db.ast_id_map(file_id);
137 return Some((mark, expr));
142 // FIXME: Instead of just dropping the error from expansion
147 pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
148 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
149 self.current_file_id = mark.file_id;
150 self.ast_id_map = mem::take(&mut mark.ast_id_map);
151 self.recursion_limit -= 1;
155 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
156 InFile { file_id: self.current_file_id, value }
159 pub(crate) fn parse_attrs(&self, owner: &dyn ast::AttrsOwner) -> Attrs {
160 self.cfg_expander.parse_attrs(owner)
163 pub(crate) fn cfg_options(&self) -> &CfgOptions {
164 &self.cfg_expander.cfg_options
167 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
168 Path::from_src(path, &self.cfg_expander.hygiene)
171 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
173 .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
178 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
179 let file_local_id = self.ast_id_map.ast_id(item);
180 AstId::new(self.current_file_id, file_local_id)
184 pub(crate) struct Mark {
186 ast_id_map: Arc<AstIdMap>,
190 /// The body of an item (function, const etc.).
191 #[derive(Debug, Eq, PartialEq)]
193 pub exprs: Arena<Expr>,
194 pub pats: Arena<Pat>,
195 /// The patterns for the function's parameters. While the parameter types are
196 /// part of the function signature, the patterns are not (they don't change
197 /// the external type of the function).
199 /// If this `Body` is for the body of a constant, this will just be
201 pub params: Vec<PatId>,
202 /// The `ExprId` of the actual body expression.
203 pub body_expr: ExprId,
204 pub item_scope: ItemScope,
207 pub type ExprPtr = AstPtr<ast::Expr>;
208 pub type ExprSource = InFile<ExprPtr>;
210 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
211 pub type PatSource = InFile<PatPtr>;
213 /// An item body together with the mapping from syntax nodes to HIR expression
214 /// IDs. This is needed to go from e.g. a position in a file to the HIR
215 /// expression containing it; but for type inference etc., we want to operate on
216 /// a structure that is agnostic to the actual positions of expressions in the
217 /// file, so that we don't recompute types whenever some whitespace is typed.
219 /// One complication here is that, due to macro expansion, a single `Body` might
220 /// be spread across several files. So, for each ExprId and PatId, we record
221 /// both the HirFileId and the position inside the file. However, we only store
222 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
223 /// this properly for macros.
224 #[derive(Default, Debug, Eq, PartialEq)]
225 pub struct BodySourceMap {
226 expr_map: FxHashMap<ExprSource, ExprId>,
227 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
228 pat_map: FxHashMap<PatSource, PatId>,
229 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
230 field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
231 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
233 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
234 /// the source map (since they're just as volatile).
235 diagnostics: Vec<diagnostics::BodyDiagnostic>,
238 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
239 pub struct SyntheticSyntax;
242 pub(crate) fn body_with_source_map_query(
243 db: &dyn DefDatabase,
245 ) -> (Arc<Body>, Arc<BodySourceMap>) {
246 let _p = profile::span("body_with_source_map_query");
247 let mut params = None;
249 let (file_id, module, body) = match def {
250 DefWithBodyId::FunctionId(f) => {
251 let f = f.lookup(db);
252 let src = f.source(db);
253 params = src.value.param_list();
254 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
256 DefWithBodyId::ConstId(c) => {
257 let c = c.lookup(db);
258 let src = c.source(db);
259 (src.file_id, c.module(db), src.value.body())
261 DefWithBodyId::StaticId(s) => {
262 let s = s.lookup(db);
263 let src = s.source(db);
264 (src.file_id, s.module(db), src.value.body())
267 let expander = Expander::new(db, file_id, module);
268 let (body, source_map) = Body::new(db, def, expander, params, body);
269 (Arc::new(body), Arc::new(source_map))
272 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
273 db.body_with_source_map(def).0
277 db: &dyn DefDatabase,
280 params: Option<ast::ParamList>,
281 body: Option<ast::Expr>,
282 ) -> (Body, BodySourceMap) {
283 lower::lower(db, def, expander, params, body)
287 impl Index<ExprId> for Body {
290 fn index(&self, expr: ExprId) -> &Expr {
295 impl Index<PatId> for Body {
298 fn index(&self, pat: PatId) -> &Pat {
304 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
305 self.expr_map_back[expr].clone()
308 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
309 let src = node.map(|it| AstPtr::new(it));
310 self.expr_map.get(&src).cloned()
313 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
314 let src = node.map(|it| AstPtr::new(it));
315 self.expansions.get(&src).cloned()
318 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
319 self.pat_map_back[pat].clone()
322 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
323 let src = node.map(|it| Either::Left(AstPtr::new(it)));
324 self.pat_map.get(&src).cloned()
327 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
328 let src = node.map(|it| Either::Right(AstPtr::new(it)));
329 self.pat_map.get(&src).cloned()
332 pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
333 self.field_map[&(expr, field)].clone()
336 pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
337 for diag in &self.diagnostics {