1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
9 use std::{mem, ops::Index, sync::Arc};
13 use drop_bomb::DropBomb;
16 ast_id_map::AstIdMap, diagnostics::DiagnosticSink, hygiene::Hygiene, AstId, ExpandResult,
17 HirFileId, InFile, MacroDefId,
19 use la_arena::{Arena, ArenaMap};
21 use rustc_hash::FxHashMap;
22 use syntax::{ast, AstNode, AstPtr};
25 pub(crate) use lower::LowerCtx;
28 attr::{Attrs, RawAttrs},
30 expr::{Expr, ExprId, Label, LabelId, Pat, PatId},
31 item_scope::BuiltinShadowMode,
32 item_scope::ItemScope,
34 path::{ModPath, Path},
36 AsMacroCall, DefWithBodyId, HasModule, Lookup, ModuleId,
39 /// A subset of Expander that only deals with cfg attributes. We only need it to
40 /// avoid cyclic queries in crate def map during enum processing.
41 pub(crate) struct CfgExpander {
42 cfg_options: CfgOptions,
47 pub(crate) struct Expander {
48 cfg_expander: CfgExpander,
49 crate_def_map: Arc<DefMap>,
50 current_file_id: HirFileId,
51 ast_id_map: Arc<AstIdMap>,
53 recursion_limit: usize,
57 const EXPANSION_RECURSION_LIMIT: usize = 32;
60 const EXPANSION_RECURSION_LIMIT: usize = 128;
65 current_file_id: HirFileId,
68 let hygiene = Hygiene::new(db.upcast(), current_file_id);
69 let cfg_options = db.crate_graph()[krate].cfg_options.clone();
70 CfgExpander { cfg_options, hygiene, krate }
73 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
74 RawAttrs::new(owner, &self.hygiene).filter(db, self.krate)
77 pub(crate) fn is_cfg_enabled(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> bool {
78 let attrs = self.parse_attrs(db, owner);
79 attrs.is_cfg_enabled(&self.cfg_options)
86 current_file_id: HirFileId,
89 let cfg_expander = CfgExpander::new(db, current_file_id, module.krate);
90 let crate_def_map = module.def_map(db);
91 let ast_id_map = db.ast_id_map(current_file_id);
102 pub(crate) fn enter_expand<T: ast::AstNode>(
104 db: &dyn DefDatabase,
105 local_scope: Option<&ItemScope>,
106 macro_call: ast::MacroCall,
107 ) -> ExpandResult<Option<(Mark, T)>> {
108 if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
109 mark::hit!(your_stack_belongs_to_me);
110 return ExpandResult::str_err("reached recursion limit during macro expansion".into());
113 let macro_call = InFile::new(self.current_file_id, ¯o_call);
115 let resolver = |path: ModPath| -> Option<MacroDefId> {
116 if let Some(local_scope) = local_scope {
117 if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) {
121 self.resolve_path_as_macro(db, &path)
126 macro_call.as_call_id_with_errors(db, self.crate_def_map.krate(), resolver, &mut |e| {
127 err.get_or_insert(e);
129 let call_id = match call_id {
133 eprintln!("no error despite `as_call_id_with_errors` returning `None`");
135 return ExpandResult { value: None, err };
140 err = db.macro_expand_error(call_id);
143 let file_id = call_id.as_file();
145 let raw_node = match db.parse_or_expand(file_id) {
148 // Only `None` if the macro expansion produced no usable AST.
150 log::warn!("no error despite `parse_or_expand` failing");
153 return ExpandResult::only_err(err.unwrap_or_else(|| {
154 mbe::ExpandError::Other("failed to parse macro invocation".into())
159 let node = match T::cast(raw_node) {
162 // This can happen without being an error, so only forward previous errors.
163 return ExpandResult { value: None, err };
167 log::debug!("macro expansion {:#?}", node.syntax());
169 self.recursion_limit += 1;
171 file_id: self.current_file_id,
172 ast_id_map: mem::take(&mut self.ast_id_map),
173 bomb: DropBomb::new("expansion mark dropped"),
175 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), file_id);
176 self.current_file_id = file_id;
177 self.ast_id_map = db.ast_id_map(file_id);
179 ExpandResult { value: Some((mark, node)), err }
182 pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
183 self.cfg_expander.hygiene = Hygiene::new(db.upcast(), mark.file_id);
184 self.current_file_id = mark.file_id;
185 self.ast_id_map = mem::take(&mut mark.ast_id_map);
186 self.recursion_limit -= 1;
190 pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
191 InFile { file_id: self.current_file_id, value }
194 pub(crate) fn parse_attrs(&self, db: &dyn DefDatabase, owner: &dyn ast::AttrsOwner) -> Attrs {
195 self.cfg_expander.parse_attrs(db, owner)
198 pub(crate) fn cfg_options(&self) -> &CfgOptions {
199 &self.cfg_expander.cfg_options
202 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
203 Path::from_src(path, &self.cfg_expander.hygiene)
206 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
208 .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
213 fn ast_id<N: AstNode>(&self, item: &N) -> AstId<N> {
214 let file_local_id = self.ast_id_map.ast_id(item);
215 AstId::new(self.current_file_id, file_local_id)
219 pub(crate) struct Mark {
221 ast_id_map: Arc<AstIdMap>,
225 /// The body of an item (function, const etc.).
226 #[derive(Debug, Eq, PartialEq)]
228 pub exprs: Arena<Expr>,
229 pub pats: Arena<Pat>,
230 pub labels: Arena<Label>,
231 /// The patterns for the function's parameters. While the parameter types are
232 /// part of the function signature, the patterns are not (they don't change
233 /// the external type of the function).
235 /// If this `Body` is for the body of a constant, this will just be
237 pub params: Vec<PatId>,
238 /// The `ExprId` of the actual body expression.
239 pub body_expr: ExprId,
240 pub item_scope: ItemScope,
244 pub type ExprPtr = AstPtr<ast::Expr>;
245 pub type ExprSource = InFile<ExprPtr>;
247 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
248 pub type PatSource = InFile<PatPtr>;
250 pub type LabelPtr = AstPtr<ast::Label>;
251 pub type LabelSource = InFile<LabelPtr>;
252 /// An item body together with the mapping from syntax nodes to HIR expression
253 /// IDs. This is needed to go from e.g. a position in a file to the HIR
254 /// expression containing it; but for type inference etc., we want to operate on
255 /// a structure that is agnostic to the actual positions of expressions in the
256 /// file, so that we don't recompute types whenever some whitespace is typed.
258 /// One complication here is that, due to macro expansion, a single `Body` might
259 /// be spread across several files. So, for each ExprId and PatId, we record
260 /// both the HirFileId and the position inside the file. However, we only store
261 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
262 /// this properly for macros.
263 #[derive(Default, Debug, Eq, PartialEq)]
264 pub struct BodySourceMap {
265 expr_map: FxHashMap<ExprSource, ExprId>,
266 expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
267 pat_map: FxHashMap<PatSource, PatId>,
268 pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
269 label_map: FxHashMap<LabelSource, LabelId>,
270 label_map_back: ArenaMap<LabelId, LabelSource>,
271 field_map: FxHashMap<(ExprId, usize), InFile<AstPtr<ast::RecordExprField>>>,
272 expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
274 /// Diagnostics accumulated during body lowering. These contain `AstPtr`s and so are stored in
275 /// the source map (since they're just as volatile).
276 diagnostics: Vec<diagnostics::BodyDiagnostic>,
279 #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
280 pub struct SyntheticSyntax;
283 pub(crate) fn body_with_source_map_query(
284 db: &dyn DefDatabase,
286 ) -> (Arc<Body>, Arc<BodySourceMap>) {
287 let _p = profile::span("body_with_source_map_query");
288 let mut params = None;
290 let (file_id, module, body) = match def {
291 DefWithBodyId::FunctionId(f) => {
292 let f = f.lookup(db);
293 let src = f.source(db);
294 params = src.value.param_list();
295 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
297 DefWithBodyId::ConstId(c) => {
298 let c = c.lookup(db);
299 let src = c.source(db);
300 (src.file_id, c.module(db), src.value.body())
302 DefWithBodyId::StaticId(s) => {
303 let s = s.lookup(db);
304 let src = s.source(db);
305 (src.file_id, s.module(db), src.value.body())
308 let expander = Expander::new(db, file_id, module);
309 let (body, source_map) = Body::new(db, def, expander, params, body);
310 (Arc::new(body), Arc::new(source_map))
313 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
314 db.body_with_source_map(def).0
318 db: &dyn DefDatabase,
321 params: Option<ast::ParamList>,
322 body: Option<ast::Expr>,
323 ) -> (Body, BodySourceMap) {
324 lower::lower(db, def, expander, params, body)
328 impl Index<ExprId> for Body {
331 fn index(&self, expr: ExprId) -> &Expr {
336 impl Index<PatId> for Body {
339 fn index(&self, pat: PatId) -> &Pat {
344 impl Index<LabelId> for Body {
347 fn index(&self, label: LabelId) -> &Label {
353 pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
354 self.expr_map_back[expr].clone()
357 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
358 let src = node.map(|it| AstPtr::new(it));
359 self.expr_map.get(&src).cloned()
362 pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
363 let src = node.map(|it| AstPtr::new(it));
364 self.expansions.get(&src).cloned()
367 pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
368 self.pat_map_back[pat].clone()
371 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
372 let src = node.map(|it| Either::Left(AstPtr::new(it)));
373 self.pat_map.get(&src).cloned()
376 pub fn node_self_param(&self, node: InFile<&ast::SelfParam>) -> Option<PatId> {
377 let src = node.map(|it| Either::Right(AstPtr::new(it)));
378 self.pat_map.get(&src).cloned()
381 pub fn label_syntax(&self, label: LabelId) -> LabelSource {
382 self.label_map_back[label].clone()
385 pub fn node_label(&self, node: InFile<&ast::Label>) -> Option<LabelId> {
386 let src = node.map(|it| AstPtr::new(it));
387 self.label_map.get(&src).cloned()
390 pub fn field_syntax(&self, expr: ExprId, field: usize) -> InFile<AstPtr<ast::RecordExprField>> {
391 self.field_map[&(expr, field)].clone()
394 pub(crate) fn add_diagnostics(&self, _db: &dyn DefDatabase, sink: &mut DiagnosticSink<'_>) {
395 for diag in &self.diagnostics {