]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir_def/src/body.rs
332c509e17063d3b520ad91d2c0bf944b477f54a
[rust.git] / crates / ra_hir_def / src / body.rs
1 //! Defines `Body`: a lowered representation of bodies of functions, statics and
2 //! consts.
3 mod lower;
4 pub mod scope;
5
6 use std::{ops::Index, sync::Arc};
7
8 use either::Either;
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;
13
14 use crate::{
15     db::DefDatabase,
16     expr::{Expr, ExprId, Pat, PatId},
17     nameres::{BuiltinShadowMode, CrateDefMap},
18     path::{ModPath, Path},
19     src::HasSource,
20     DefWithBodyId, HasModule, Lookup, ModuleDefId, ModuleId,
21 };
22
23 struct Expander {
24     crate_def_map: Arc<CrateDefMap>,
25     current_file_id: HirFileId,
26     hygiene: Hygiene,
27     module: ModuleId,
28 }
29
30 impl Expander {
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 }
35     }
36
37     fn enter_expand(
38         &mut self,
39         db: &impl DefDatabase,
40         macro_call: ast::MacroCall,
41     ) -> Option<(Mark, ast::Expr)> {
42         let ast_id = AstId::new(
43             self.current_file_id,
44             db.ast_id_map(self.current_file_id).ast_id(&macro_call),
45         );
46
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());
54
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;
58
59                         return Some((mark, expr));
60                     }
61                 }
62             }
63         }
64
65         // FIXME: Instead of just dropping the error from expansion
66         // report it
67         None
68     }
69
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);
74     }
75
76     fn to_source<T>(&self, value: T) -> InFile<T> {
77         InFile { file_id: self.current_file_id, value }
78     }
79
80     fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
81         Path::from_src(path, &self.hygiene)
82     }
83
84     fn parse_mod_path(&mut self, path: ast::Path) -> Option<ModPath> {
85         ModPath::from_src(path, &self.hygiene)
86     }
87
88     fn resolve_path_as_macro(&self, db: &impl DefDatabase, path: &ModPath) -> Option<MacroDefId> {
89         self.crate_def_map
90             .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
91             .0
92             .take_macros()
93     }
94 }
95
96 struct Mark {
97     file_id: HirFileId,
98 }
99
100 impl Drop for Mark {
101     fn drop(&mut self) {
102         if !std::thread::panicking() {
103             panic!("dropped mark")
104         }
105     }
106 }
107
108 /// The body of an item (function, const etc.).
109 #[derive(Debug, Eq, PartialEq)]
110 pub struct Body {
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).
116     ///
117     /// If this `Body` is for the body of a constant, this will just be
118     /// empty.
119     pub params: Vec<PatId>,
120     /// The `ExprId` of the actual body expression.
121     pub body_expr: ExprId,
122     pub defs: Vec<ModuleDefId>,
123 }
124
125 pub type ExprPtr = Either<AstPtr<ast::Expr>, AstPtr<ast::RecordField>>;
126 pub type ExprSource = InFile<ExprPtr>;
127
128 pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
129 pub type PatSource = InFile<PatPtr>;
130
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.
136 ///
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>>,
149 }
150
151 impl Body {
152     pub(crate) fn body_with_source_map_query(
153         db: &impl DefDatabase,
154         def: DefWithBodyId,
155     ) -> (Arc<Body>, Arc<BodySourceMap>) {
156         let mut params = None;
157
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))
164             }
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())
169             }
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())
174             }
175         };
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))
179     }
180
181     pub(crate) fn body_query(db: &impl DefDatabase, def: DefWithBodyId) -> Arc<Body> {
182         db.body_with_source_map(def).0
183     }
184
185     fn new(
186         db: &impl DefDatabase,
187         expander: Expander,
188         params: Option<ast::ParamList>,
189         body: Option<ast::Expr>,
190     ) -> (Body, BodySourceMap) {
191         lower::lower(db, expander, params, body)
192     }
193 }
194
195 impl Index<ExprId> for Body {
196     type Output = Expr;
197
198     fn index(&self, expr: ExprId) -> &Expr {
199         &self.exprs[expr]
200     }
201 }
202
203 impl Index<PatId> for Body {
204     type Output = Pat;
205
206     fn index(&self, pat: PatId) -> &Pat {
207         &self.pats[pat]
208     }
209 }
210
211 impl BodySourceMap {
212     pub fn expr_syntax(&self, expr: ExprId) -> Option<ExprSource> {
213         self.expr_map_back.get(expr).copied()
214     }
215
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()
219     }
220
221     pub fn pat_syntax(&self, pat: PatId) -> Option<PatSource> {
222         self.pat_map_back.get(pat).copied()
223     }
224
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()
228     }
229
230     pub fn field_syntax(&self, expr: ExprId, field: usize) -> AstPtr<ast::RecordField> {
231         self.field_map[&(expr, field)]
232     }
233 }