1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
6 use std::{ops::Index, sync::Arc};
9 use hir_expand::{hygiene::Hygiene, AstId, HirFileId, InFile, MacroCallKind, MacroDefId};
10 use ra_arena::{map::ArenaMap, Arena};
11 use ra_syntax::{ast, AstNode, AstPtr};
12 use rustc_hash::FxHashMap;
16 expr::{Expr, ExprId, Pat, PatId},
17 nameres::{BuiltinShadowMode, CrateDefMap},
18 path::{ModPath, Path},
20 DefWithBodyId, HasModule, Lookup, ModuleDefId, ModuleId,
24 crate_def_map: Arc<CrateDefMap>,
25 current_file_id: HirFileId,
31 fn new(db: &impl DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
32 let crate_def_map = db.crate_def_map(module.krate);
33 let hygiene = Hygiene::new(db, current_file_id);
34 Expander { crate_def_map, current_file_id, hygiene, module }
39 db: &impl DefDatabase,
40 macro_call: ast::MacroCall,
41 ) -> Option<(Mark, ast::Expr)> {
42 let ast_id = AstId::new(
44 db.ast_id_map(self.current_file_id).ast_id(¯o_call),
47 if let Some(path) = macro_call.path().and_then(|path| self.parse_mod_path(path)) {
48 if let Some(def) = self.resolve_path_as_macro(db, &path) {
49 let call_id = def.as_call_id(db, MacroCallKind::FnLike(ast_id));
50 let file_id = call_id.as_file();
51 if let Some(node) = db.parse_or_expand(file_id) {
52 if let Some(expr) = ast::Expr::cast(node) {
53 log::debug!("macro expansion {:#?}", expr.syntax());
55 let mark = Mark { file_id: self.current_file_id };
56 self.hygiene = Hygiene::new(db, file_id);
57 self.current_file_id = file_id;
59 return Some((mark, expr));
65 // FIXME: Instead of just dropping the error from expansion
70 fn exit(&mut self, db: &impl DefDatabase, mark: Mark) {
71 self.hygiene = Hygiene::new(db, mark.file_id);
72 self.current_file_id = mark.file_id;
73 std::mem::forget(mark);
76 fn to_source<T>(&self, value: T) -> InFile<T> {
77 InFile { file_id: self.current_file_id, value }
80 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
81 Path::from_src(path, &self.hygiene)
84 fn parse_mod_path(&mut self, path: ast::Path) -> Option<ModPath> {
85 ModPath::from_src(path, &self.hygiene)
88 fn resolve_path_as_macro(&self, db: &impl DefDatabase, path: &ModPath) -> Option<MacroDefId> {
90 .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
102 if !std::thread::panicking() {
103 panic!("dropped mark")
108 /// The body of an item (function, const etc.).
109 #[derive(Debug, Eq, PartialEq)]
111 pub exprs: Arena<ExprId, Expr>,
112 pub pats: Arena<PatId, Pat>,
113 /// The patterns for the function's parameters. While the parameter types are
114 /// part of the function signature, the patterns are not (they don't change
115 /// the external type of the function).
117 /// If this `Body` is for the body of a constant, this will just be
119 pub params: Vec<PatId>,
120 /// The `ExprId` of the actual body expression.
121 pub body_expr: ExprId,
122 pub defs: Vec<ModuleDefId>,
125 pub type ExprPtr = Either<AstPtr<ast::Expr>, AstPtr<ast::RecordField>>;
126 pub type ExprSource = InFile<ExprPtr>;
128 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
129 pub type PatSource = InFile<PatPtr>;
131 /// An item body together with the mapping from syntax nodes to HIR expression
132 /// IDs. This is needed to go from e.g. a position in a file to the HIR
133 /// expression containing it; but for type inference etc., we want to operate on
134 /// a structure that is agnostic to the actual positions of expressions in the
135 /// file, so that we don't recompute types whenever some whitespace is typed.
137 /// One complication here is that, due to macro expansion, a single `Body` might
138 /// be spread across several files. So, for each ExprId and PatId, we record
139 /// both the HirFileId and the position inside the file. However, we only store
140 /// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
141 /// this properly for macros.
142 #[derive(Default, Debug, Eq, PartialEq)]
143 pub struct BodySourceMap {
144 expr_map: FxHashMap<ExprSource, ExprId>,
145 expr_map_back: ArenaMap<ExprId, ExprSource>,
146 pat_map: FxHashMap<PatSource, PatId>,
147 pat_map_back: ArenaMap<PatId, PatSource>,
148 field_map: FxHashMap<(ExprId, usize), AstPtr<ast::RecordField>>,
152 pub(crate) fn body_with_source_map_query(
153 db: &impl DefDatabase,
155 ) -> (Arc<Body>, Arc<BodySourceMap>) {
156 let mut params = None;
158 let (file_id, module, body) = match def {
159 DefWithBodyId::FunctionId(f) => {
160 let f = f.lookup(db);
161 let src = f.source(db);
162 params = src.value.param_list();
163 (src.file_id, f.module(db), src.value.body().map(ast::Expr::from))
165 DefWithBodyId::ConstId(c) => {
166 let c = c.lookup(db);
167 let src = c.source(db);
168 (src.file_id, c.module(db), src.value.body())
170 DefWithBodyId::StaticId(s) => {
171 let s = s.lookup(db);
172 let src = s.source(db);
173 (src.file_id, s.module(db), src.value.body())
176 let expander = Expander::new(db, file_id, module);
177 let (body, source_map) = Body::new(db, expander, params, body);
178 (Arc::new(body), Arc::new(source_map))
181 pub(crate) fn body_query(db: &impl DefDatabase, def: DefWithBodyId) -> Arc<Body> {
182 db.body_with_source_map(def).0
186 db: &impl DefDatabase,
188 params: Option<ast::ParamList>,
189 body: Option<ast::Expr>,
190 ) -> (Body, BodySourceMap) {
191 lower::lower(db, expander, params, body)
195 impl Index<ExprId> for Body {
198 fn index(&self, expr: ExprId) -> &Expr {
203 impl Index<PatId> for Body {
206 fn index(&self, pat: PatId) -> &Pat {
212 pub fn expr_syntax(&self, expr: ExprId) -> Option<ExprSource> {
213 self.expr_map_back.get(expr).copied()
216 pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
217 let src = node.map(|it| Either::Left(AstPtr::new(it)));
218 self.expr_map.get(&src).cloned()
221 pub fn pat_syntax(&self, pat: PatId) -> Option<PatSource> {
222 self.pat_map_back.get(pat).copied()
225 pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
226 let src = node.map(|it| Either::Left(AstPtr::new(it)));
227 self.pat_map.get(&src).cloned()
230 pub fn field_syntax(&self, expr: ExprId, field: usize) -> AstPtr<ast::RecordField> {
231 self.field_map[&(expr, field)]