aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_def
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_def')
-rw-r--r--crates/ra_hir_def/src/body.rs238
-rw-r--r--crates/ra_hir_def/src/body/lower.rs595
-rw-r--r--crates/ra_hir_def/src/body/scope.rs165
-rw-r--r--crates/ra_hir_def/src/builtin_type.rs133
-rw-r--r--crates/ra_hir_def/src/db.rs12
-rw-r--r--crates/ra_hir_def/src/expr.rs421
-rw-r--r--crates/ra_hir_def/src/lib.rs12
-rw-r--r--crates/ra_hir_def/src/nameres/collector.rs36
-rw-r--r--crates/ra_hir_def/src/nameres/raw.rs7
-rw-r--r--crates/ra_hir_def/src/nameres/tests.rs31
10 files changed, 1623 insertions, 27 deletions
diff --git a/crates/ra_hir_def/src/body.rs b/crates/ra_hir_def/src/body.rs
new file mode 100644
index 000000000..85dc4feb0
--- /dev/null
+++ b/crates/ra_hir_def/src/body.rs
@@ -0,0 +1,238 @@
1//! FIXME: write short doc here
2mod lower;
3pub mod scope;
4
5use std::{ops::Index, sync::Arc};
6
7use hir_expand::{
8 either::Either, hygiene::Hygiene, AstId, HirFileId, MacroCallLoc, MacroDefId, MacroFileKind,
9 Source,
10};
11use ra_arena::{map::ArenaMap, Arena};
12use ra_syntax::{ast, AstNode, AstPtr};
13use rustc_hash::FxHashMap;
14
15use crate::{
16 db::DefDatabase2,
17 expr::{Expr, ExprId, Pat, PatId},
18 nameres::CrateDefMap,
19 path::Path,
20 AstItemDef, DefWithBodyId, ModuleId,
21};
22
23pub struct Expander {
24 crate_def_map: Arc<CrateDefMap>,
25 current_file_id: HirFileId,
26 hygiene: Hygiene,
27 module: ModuleId,
28}
29
30impl Expander {
31 pub fn new(db: &impl DefDatabase2, 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 DefDatabase2,
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_path(path)) {
48 if let Some(def) = self.resolve_path_as_macro(db, &path) {
49 let call_id = db.intern_macro(MacroCallLoc { def, ast_id });
50 let file_id = call_id.as_file(MacroFileKind::Expr);
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 DefDatabase2, 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, ast: T) -> Source<T> {
77 Source { file_id: self.current_file_id, ast }
78 }
79
80 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
81 Path::from_src(path, &self.hygiene)
82 }
83
84 fn resolve_path_as_macro(&self, db: &impl DefDatabase2, path: &Path) -> Option<MacroDefId> {
85 self.crate_def_map.resolve_path(db, self.module.module_id, path).0.get_macros()
86 }
87}
88
89struct Mark {
90 file_id: HirFileId,
91}
92
93impl Drop for Mark {
94 fn drop(&mut self) {
95 if !std::thread::panicking() {
96 panic!("dropped mark")
97 }
98 }
99}
100
101/// The body of an item (function, const etc.).
102#[derive(Debug, Eq, PartialEq)]
103pub struct Body {
104 exprs: Arena<ExprId, Expr>,
105 pats: Arena<PatId, Pat>,
106 /// The patterns for the function's parameters. While the parameter types are
107 /// part of the function signature, the patterns are not (they don't change
108 /// the external type of the function).
109 ///
110 /// If this `Body` is for the body of a constant, this will just be
111 /// empty.
112 params: Vec<PatId>,
113 /// The `ExprId` of the actual body expression.
114 body_expr: ExprId,
115}
116
117pub type ExprPtr = Either<AstPtr<ast::Expr>, AstPtr<ast::RecordField>>;
118pub type ExprSource = Source<ExprPtr>;
119
120pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
121pub type PatSource = Source<PatPtr>;
122
123/// An item body together with the mapping from syntax nodes to HIR expression
124/// IDs. This is needed to go from e.g. a position in a file to the HIR
125/// expression containing it; but for type inference etc., we want to operate on
126/// a structure that is agnostic to the actual positions of expressions in the
127/// file, so that we don't recompute types whenever some whitespace is typed.
128///
129/// One complication here is that, due to macro expansion, a single `Body` might
130/// be spread across several files. So, for each ExprId and PatId, we record
131/// both the HirFileId and the position inside the file. However, we only store
132/// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
133/// this properly for macros.
134#[derive(Default, Debug, Eq, PartialEq)]
135pub struct BodySourceMap {
136 expr_map: FxHashMap<ExprSource, ExprId>,
137 expr_map_back: ArenaMap<ExprId, ExprSource>,
138 pat_map: FxHashMap<PatSource, PatId>,
139 pat_map_back: ArenaMap<PatId, PatSource>,
140 field_map: FxHashMap<(ExprId, usize), AstPtr<ast::RecordField>>,
141}
142
143impl Body {
144 pub(crate) fn body_with_source_map_query(
145 db: &impl DefDatabase2,
146 def: DefWithBodyId,
147 ) -> (Arc<Body>, Arc<BodySourceMap>) {
148 let mut params = None;
149
150 let (file_id, module, body) = match def {
151 DefWithBodyId::FunctionId(f) => {
152 let src = f.source(db);
153 params = src.ast.param_list();
154 (src.file_id, f.module(db), src.ast.body().map(ast::Expr::from))
155 }
156 DefWithBodyId::ConstId(c) => {
157 let src = c.source(db);
158 (src.file_id, c.module(db), src.ast.body())
159 }
160 DefWithBodyId::StaticId(s) => {
161 let src = s.source(db);
162 (src.file_id, s.module(db), src.ast.body())
163 }
164 };
165 let expander = Expander::new(db, file_id, module);
166 let (body, source_map) = Body::new(db, expander, params, body);
167 (Arc::new(body), Arc::new(source_map))
168 }
169
170 pub(crate) fn body_query(db: &impl DefDatabase2, def: DefWithBodyId) -> Arc<Body> {
171 db.body_with_source_map(def).0
172 }
173
174 fn new(
175 db: &impl DefDatabase2,
176 expander: Expander,
177 params: Option<ast::ParamList>,
178 body: Option<ast::Expr>,
179 ) -> (Body, BodySourceMap) {
180 lower::lower(db, expander, params, body)
181 }
182
183 pub fn params(&self) -> &[PatId] {
184 &self.params
185 }
186
187 pub fn body_expr(&self) -> ExprId {
188 self.body_expr
189 }
190
191 pub fn exprs(&self) -> impl Iterator<Item = (ExprId, &Expr)> {
192 self.exprs.iter()
193 }
194
195 pub fn pats(&self) -> impl Iterator<Item = (PatId, &Pat)> {
196 self.pats.iter()
197 }
198}
199
200impl Index<ExprId> for Body {
201 type Output = Expr;
202
203 fn index(&self, expr: ExprId) -> &Expr {
204 &self.exprs[expr]
205 }
206}
207
208impl Index<PatId> for Body {
209 type Output = Pat;
210
211 fn index(&self, pat: PatId) -> &Pat {
212 &self.pats[pat]
213 }
214}
215
216impl BodySourceMap {
217 pub fn expr_syntax(&self, expr: ExprId) -> Option<ExprSource> {
218 self.expr_map_back.get(expr).copied()
219 }
220
221 pub fn node_expr(&self, node: Source<&ast::Expr>) -> Option<ExprId> {
222 let src = node.map(|it| Either::A(AstPtr::new(it)));
223 self.expr_map.get(&src).cloned()
224 }
225
226 pub fn pat_syntax(&self, pat: PatId) -> Option<PatSource> {
227 self.pat_map_back.get(pat).copied()
228 }
229
230 pub fn node_pat(&self, node: Source<&ast::Pat>) -> Option<PatId> {
231 let src = node.map(|it| Either::A(AstPtr::new(it)));
232 self.pat_map.get(&src).cloned()
233 }
234
235 pub fn field_syntax(&self, expr: ExprId, field: usize) -> AstPtr<ast::RecordField> {
236 self.field_map[&(expr, field)]
237 }
238}
diff --git a/crates/ra_hir_def/src/body/lower.rs b/crates/ra_hir_def/src/body/lower.rs
new file mode 100644
index 000000000..a5bb60e85
--- /dev/null
+++ b/crates/ra_hir_def/src/body/lower.rs
@@ -0,0 +1,595 @@
1//! FIXME: write short doc here
2
3use hir_expand::{
4 either::Either,
5 name::{self, AsName, Name},
6};
7use ra_arena::Arena;
8use ra_syntax::{
9 ast::{
10 self, ArgListOwner, ArrayExprKind, LiteralKind, LoopBodyOwner, NameOwner,
11 TypeAscriptionOwner,
12 },
13 AstNode, AstPtr,
14};
15
16use crate::{
17 body::{Body, BodySourceMap, Expander, PatPtr},
18 builtin_type::{BuiltinFloat, BuiltinInt},
19 db::DefDatabase2,
20 expr::{
21 ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp,
22 MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement,
23 },
24 path::GenericArgs,
25 path::Path,
26 type_ref::{Mutability, TypeRef},
27};
28
29pub(super) fn lower(
30 db: &impl DefDatabase2,
31 expander: Expander,
32 params: Option<ast::ParamList>,
33 body: Option<ast::Expr>,
34) -> (Body, BodySourceMap) {
35 ExprCollector {
36 expander,
37 db,
38 source_map: BodySourceMap::default(),
39 body: Body {
40 exprs: Arena::default(),
41 pats: Arena::default(),
42 params: Vec::new(),
43 body_expr: ExprId::dummy(),
44 },
45 }
46 .collect(params, body)
47}
48
49struct ExprCollector<DB> {
50 db: DB,
51 expander: Expander,
52
53 body: Body,
54 source_map: BodySourceMap,
55}
56
57impl<'a, DB> ExprCollector<&'a DB>
58where
59 DB: DefDatabase2,
60{
61 fn collect(
62 mut self,
63 param_list: Option<ast::ParamList>,
64 body: Option<ast::Expr>,
65 ) -> (Body, BodySourceMap) {
66 if let Some(param_list) = param_list {
67 if let Some(self_param) = param_list.self_param() {
68 let ptr = AstPtr::new(&self_param);
69 let param_pat = self.alloc_pat(
70 Pat::Bind {
71 name: name::SELF_PARAM,
72 mode: BindingAnnotation::Unannotated,
73 subpat: None,
74 },
75 Either::B(ptr),
76 );
77 self.body.params.push(param_pat);
78 }
79
80 for param in param_list.params() {
81 let pat = match param.pat() {
82 None => continue,
83 Some(pat) => pat,
84 };
85 let param_pat = self.collect_pat(pat);
86 self.body.params.push(param_pat);
87 }
88 };
89
90 self.body.body_expr = self.collect_expr_opt(body);
91 (self.body, self.source_map)
92 }
93
94 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
95 let ptr = Either::A(ptr);
96 let id = self.body.exprs.alloc(expr);
97 let src = self.expander.to_source(ptr);
98 self.source_map.expr_map.insert(src, id);
99 self.source_map.expr_map_back.insert(id, src);
100 id
101 }
102 // desugared exprs don't have ptr, that's wrong and should be fixed
103 // somehow.
104 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
105 self.body.exprs.alloc(expr)
106 }
107 fn alloc_expr_field_shorthand(&mut self, expr: Expr, ptr: AstPtr<ast::RecordField>) -> ExprId {
108 let ptr = Either::B(ptr);
109 let id = self.body.exprs.alloc(expr);
110 let src = self.expander.to_source(ptr);
111 self.source_map.expr_map.insert(src, id);
112 self.source_map.expr_map_back.insert(id, src);
113 id
114 }
115 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
116 let id = self.body.pats.alloc(pat);
117 let src = self.expander.to_source(ptr);
118 self.source_map.pat_map.insert(src, id);
119 self.source_map.pat_map_back.insert(id, src);
120 id
121 }
122
123 fn empty_block(&mut self) -> ExprId {
124 let block = Expr::Block { statements: Vec::new(), tail: None };
125 self.body.exprs.alloc(block)
126 }
127
128 fn missing_expr(&mut self) -> ExprId {
129 self.body.exprs.alloc(Expr::Missing)
130 }
131
132 fn missing_pat(&mut self) -> PatId {
133 self.body.pats.alloc(Pat::Missing)
134 }
135
136 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
137 let syntax_ptr = AstPtr::new(&expr);
138 match expr {
139 ast::Expr::IfExpr(e) => {
140 let then_branch = self.collect_block_opt(e.then_branch());
141
142 let else_branch = e.else_branch().map(|b| match b {
143 ast::ElseBranch::Block(it) => self.collect_block(it),
144 ast::ElseBranch::IfExpr(elif) => {
145 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
146 self.collect_expr(expr)
147 }
148 });
149
150 let condition = match e.condition() {
151 None => self.missing_expr(),
152 Some(condition) => match condition.pat() {
153 None => self.collect_expr_opt(condition.expr()),
154 // if let -- desugar to match
155 Some(pat) => {
156 let pat = self.collect_pat(pat);
157 let match_expr = self.collect_expr_opt(condition.expr());
158 let placeholder_pat = self.missing_pat();
159 let arms = vec![
160 MatchArm { pats: vec![pat], expr: then_branch, guard: None },
161 MatchArm {
162 pats: vec![placeholder_pat],
163 expr: else_branch.unwrap_or_else(|| self.empty_block()),
164 guard: None,
165 },
166 ];
167 return self
168 .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr);
169 }
170 },
171 };
172
173 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
174 }
175 ast::Expr::TryBlockExpr(e) => {
176 let body = self.collect_block_opt(e.body());
177 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
178 }
179 ast::Expr::BlockExpr(e) => self.collect_block(e),
180 ast::Expr::LoopExpr(e) => {
181 let body = self.collect_block_opt(e.loop_body());
182 self.alloc_expr(Expr::Loop { body }, syntax_ptr)
183 }
184 ast::Expr::WhileExpr(e) => {
185 let body = self.collect_block_opt(e.loop_body());
186
187 let condition = match e.condition() {
188 None => self.missing_expr(),
189 Some(condition) => match condition.pat() {
190 None => self.collect_expr_opt(condition.expr()),
191 // if let -- desugar to match
192 Some(pat) => {
193 let pat = self.collect_pat(pat);
194 let match_expr = self.collect_expr_opt(condition.expr());
195 let placeholder_pat = self.missing_pat();
196 let break_ = self.alloc_expr_desugared(Expr::Break { expr: None });
197 let arms = vec![
198 MatchArm { pats: vec![pat], expr: body, guard: None },
199 MatchArm { pats: vec![placeholder_pat], expr: break_, guard: None },
200 ];
201 let match_expr =
202 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
203 return self.alloc_expr(Expr::Loop { body: match_expr }, syntax_ptr);
204 }
205 },
206 };
207
208 self.alloc_expr(Expr::While { condition, body }, syntax_ptr)
209 }
210 ast::Expr::ForExpr(e) => {
211 let iterable = self.collect_expr_opt(e.iterable());
212 let pat = self.collect_pat_opt(e.pat());
213 let body = self.collect_block_opt(e.loop_body());
214 self.alloc_expr(Expr::For { iterable, pat, body }, syntax_ptr)
215 }
216 ast::Expr::CallExpr(e) => {
217 let callee = self.collect_expr_opt(e.expr());
218 let args = if let Some(arg_list) = e.arg_list() {
219 arg_list.args().map(|e| self.collect_expr(e)).collect()
220 } else {
221 Vec::new()
222 };
223 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
224 }
225 ast::Expr::MethodCallExpr(e) => {
226 let receiver = self.collect_expr_opt(e.expr());
227 let args = if let Some(arg_list) = e.arg_list() {
228 arg_list.args().map(|e| self.collect_expr(e)).collect()
229 } else {
230 Vec::new()
231 };
232 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
233 let generic_args = e.type_arg_list().and_then(GenericArgs::from_ast);
234 self.alloc_expr(
235 Expr::MethodCall { receiver, method_name, args, generic_args },
236 syntax_ptr,
237 )
238 }
239 ast::Expr::MatchExpr(e) => {
240 let expr = self.collect_expr_opt(e.expr());
241 let arms = if let Some(match_arm_list) = e.match_arm_list() {
242 match_arm_list
243 .arms()
244 .map(|arm| MatchArm {
245 pats: arm.pats().map(|p| self.collect_pat(p)).collect(),
246 expr: self.collect_expr_opt(arm.expr()),
247 guard: arm
248 .guard()
249 .and_then(|guard| guard.expr())
250 .map(|e| self.collect_expr(e)),
251 })
252 .collect()
253 } else {
254 Vec::new()
255 };
256 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
257 }
258 ast::Expr::PathExpr(e) => {
259 let path = e
260 .path()
261 .and_then(|path| self.expander.parse_path(path))
262 .map(Expr::Path)
263 .unwrap_or(Expr::Missing);
264 self.alloc_expr(path, syntax_ptr)
265 }
266 ast::Expr::ContinueExpr(_e) => {
267 // FIXME: labels
268 self.alloc_expr(Expr::Continue, syntax_ptr)
269 }
270 ast::Expr::BreakExpr(e) => {
271 let expr = e.expr().map(|e| self.collect_expr(e));
272 self.alloc_expr(Expr::Break { expr }, syntax_ptr)
273 }
274 ast::Expr::ParenExpr(e) => {
275 let inner = self.collect_expr_opt(e.expr());
276 // make the paren expr point to the inner expression as well
277 let src = self.expander.to_source(Either::A(syntax_ptr));
278 self.source_map.expr_map.insert(src, inner);
279 inner
280 }
281 ast::Expr::ReturnExpr(e) => {
282 let expr = e.expr().map(|e| self.collect_expr(e));
283 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
284 }
285 ast::Expr::RecordLit(e) => {
286 let path = e.path().and_then(|path| self.expander.parse_path(path));
287 let mut field_ptrs = Vec::new();
288 let record_lit = if let Some(nfl) = e.record_field_list() {
289 let fields = nfl
290 .fields()
291 .inspect(|field| field_ptrs.push(AstPtr::new(field)))
292 .map(|field| RecordLitField {
293 name: field
294 .name_ref()
295 .map(|nr| nr.as_name())
296 .unwrap_or_else(Name::missing),
297 expr: if let Some(e) = field.expr() {
298 self.collect_expr(e)
299 } else if let Some(nr) = field.name_ref() {
300 // field shorthand
301 self.alloc_expr_field_shorthand(
302 Expr::Path(Path::from_name_ref(&nr)),
303 AstPtr::new(&field),
304 )
305 } else {
306 self.missing_expr()
307 },
308 })
309 .collect();
310 let spread = nfl.spread().map(|s| self.collect_expr(s));
311 Expr::RecordLit { path, fields, spread }
312 } else {
313 Expr::RecordLit { path, fields: Vec::new(), spread: None }
314 };
315
316 let res = self.alloc_expr(record_lit, syntax_ptr);
317 for (i, ptr) in field_ptrs.into_iter().enumerate() {
318 self.source_map.field_map.insert((res, i), ptr);
319 }
320 res
321 }
322 ast::Expr::FieldExpr(e) => {
323 let expr = self.collect_expr_opt(e.expr());
324 let name = match e.field_access() {
325 Some(kind) => kind.as_name(),
326 _ => Name::missing(),
327 };
328 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
329 }
330 ast::Expr::AwaitExpr(e) => {
331 let expr = self.collect_expr_opt(e.expr());
332 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
333 }
334 ast::Expr::TryExpr(e) => {
335 let expr = self.collect_expr_opt(e.expr());
336 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
337 }
338 ast::Expr::CastExpr(e) => {
339 let expr = self.collect_expr_opt(e.expr());
340 let type_ref = TypeRef::from_ast_opt(e.type_ref());
341 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
342 }
343 ast::Expr::RefExpr(e) => {
344 let expr = self.collect_expr_opt(e.expr());
345 let mutability = Mutability::from_mutable(e.is_mut());
346 self.alloc_expr(Expr::Ref { expr, mutability }, syntax_ptr)
347 }
348 ast::Expr::PrefixExpr(e) => {
349 let expr = self.collect_expr_opt(e.expr());
350 if let Some(op) = e.op_kind() {
351 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
352 } else {
353 self.alloc_expr(Expr::Missing, syntax_ptr)
354 }
355 }
356 ast::Expr::LambdaExpr(e) => {
357 let mut args = Vec::new();
358 let mut arg_types = Vec::new();
359 if let Some(pl) = e.param_list() {
360 for param in pl.params() {
361 let pat = self.collect_pat_opt(param.pat());
362 let type_ref = param.ascribed_type().map(TypeRef::from_ast);
363 args.push(pat);
364 arg_types.push(type_ref);
365 }
366 }
367 let body = self.collect_expr_opt(e.body());
368 self.alloc_expr(Expr::Lambda { args, arg_types, body }, syntax_ptr)
369 }
370 ast::Expr::BinExpr(e) => {
371 let lhs = self.collect_expr_opt(e.lhs());
372 let rhs = self.collect_expr_opt(e.rhs());
373 let op = e.op_kind().map(BinaryOp::from);
374 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
375 }
376 ast::Expr::TupleExpr(e) => {
377 let exprs = e.exprs().map(|expr| self.collect_expr(expr)).collect();
378 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
379 }
380 ast::Expr::BoxExpr(e) => {
381 let expr = self.collect_expr_opt(e.expr());
382 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
383 }
384
385 ast::Expr::ArrayExpr(e) => {
386 let kind = e.kind();
387
388 match kind {
389 ArrayExprKind::ElementList(e) => {
390 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
391 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
392 }
393 ArrayExprKind::Repeat { initializer, repeat } => {
394 let initializer = self.collect_expr_opt(initializer);
395 let repeat = self.collect_expr_opt(repeat);
396 self.alloc_expr(
397 Expr::Array(Array::Repeat { initializer, repeat }),
398 syntax_ptr,
399 )
400 }
401 }
402 }
403
404 ast::Expr::Literal(e) => {
405 let lit = match e.kind() {
406 LiteralKind::IntNumber { suffix } => {
407 let known_name = suffix.and_then(|it| BuiltinInt::from_suffix(&it));
408
409 Literal::Int(Default::default(), known_name)
410 }
411 LiteralKind::FloatNumber { suffix } => {
412 let known_name = suffix.and_then(|it| BuiltinFloat::from_suffix(&it));
413
414 Literal::Float(Default::default(), known_name)
415 }
416 LiteralKind::ByteString => Literal::ByteString(Default::default()),
417 LiteralKind::String => Literal::String(Default::default()),
418 LiteralKind::Byte => Literal::Int(Default::default(), Some(BuiltinInt::U8)),
419 LiteralKind::Bool => Literal::Bool(Default::default()),
420 LiteralKind::Char => Literal::Char(Default::default()),
421 };
422 self.alloc_expr(Expr::Literal(lit), syntax_ptr)
423 }
424 ast::Expr::IndexExpr(e) => {
425 let base = self.collect_expr_opt(e.base());
426 let index = self.collect_expr_opt(e.index());
427 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
428 }
429
430 // FIXME implement HIR for these:
431 ast::Expr::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
432 ast::Expr::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
433 ast::Expr::MacroCall(e) => match self.expander.enter_expand(self.db, e) {
434 Some((mark, expansion)) => {
435 let id = self.collect_expr(expansion);
436 self.expander.exit(self.db, mark);
437 id
438 }
439 None => self.alloc_expr(Expr::Missing, syntax_ptr),
440 },
441 }
442 }
443
444 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
445 if let Some(expr) = expr {
446 self.collect_expr(expr)
447 } else {
448 self.missing_expr()
449 }
450 }
451
452 fn collect_block(&mut self, expr: ast::BlockExpr) -> ExprId {
453 let syntax_node_ptr = AstPtr::new(&expr.clone().into());
454 let block = match expr.block() {
455 Some(block) => block,
456 None => return self.alloc_expr(Expr::Missing, syntax_node_ptr),
457 };
458 let statements = block
459 .statements()
460 .map(|s| match s {
461 ast::Stmt::LetStmt(stmt) => {
462 let pat = self.collect_pat_opt(stmt.pat());
463 let type_ref = stmt.ascribed_type().map(TypeRef::from_ast);
464 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
465 Statement::Let { pat, type_ref, initializer }
466 }
467 ast::Stmt::ExprStmt(stmt) => Statement::Expr(self.collect_expr_opt(stmt.expr())),
468 })
469 .collect();
470 let tail = block.expr().map(|e| self.collect_expr(e));
471 self.alloc_expr(Expr::Block { statements, tail }, syntax_node_ptr)
472 }
473
474 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
475 if let Some(block) = expr {
476 self.collect_block(block)
477 } else {
478 self.missing_expr()
479 }
480 }
481
482 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
483 let pattern = match &pat {
484 ast::Pat::BindPat(bp) => {
485 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
486 let annotation = BindingAnnotation::new(bp.is_mutable(), bp.is_ref());
487 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
488 Pat::Bind { name, mode: annotation, subpat }
489 }
490 ast::Pat::TupleStructPat(p) => {
491 let path = p.path().and_then(|path| self.expander.parse_path(path));
492 let args = p.args().map(|p| self.collect_pat(p)).collect();
493 Pat::TupleStruct { path, args }
494 }
495 ast::Pat::RefPat(p) => {
496 let pat = self.collect_pat_opt(p.pat());
497 let mutability = Mutability::from_mutable(p.is_mut());
498 Pat::Ref { pat, mutability }
499 }
500 ast::Pat::PathPat(p) => {
501 let path = p.path().and_then(|path| self.expander.parse_path(path));
502 path.map(Pat::Path).unwrap_or(Pat::Missing)
503 }
504 ast::Pat::TuplePat(p) => {
505 let args = p.args().map(|p| self.collect_pat(p)).collect();
506 Pat::Tuple(args)
507 }
508 ast::Pat::PlaceholderPat(_) => Pat::Wild,
509 ast::Pat::RecordPat(p) => {
510 let path = p.path().and_then(|path| self.expander.parse_path(path));
511 let record_field_pat_list =
512 p.record_field_pat_list().expect("every struct should have a field list");
513 let mut fields: Vec<_> = record_field_pat_list
514 .bind_pats()
515 .filter_map(|bind_pat| {
516 let ast_pat =
517 ast::Pat::cast(bind_pat.syntax().clone()).expect("bind pat is a pat");
518 let pat = self.collect_pat(ast_pat);
519 let name = bind_pat.name()?.as_name();
520 Some(RecordFieldPat { name, pat })
521 })
522 .collect();
523 let iter = record_field_pat_list.record_field_pats().filter_map(|f| {
524 let ast_pat = f.pat()?;
525 let pat = self.collect_pat(ast_pat);
526 let name = f.name()?.as_name();
527 Some(RecordFieldPat { name, pat })
528 });
529 fields.extend(iter);
530
531 Pat::Record { path, args: fields }
532 }
533
534 // FIXME: implement
535 ast::Pat::DotDotPat(_) => Pat::Missing,
536 ast::Pat::BoxPat(_) => Pat::Missing,
537 ast::Pat::LiteralPat(_) => Pat::Missing,
538 ast::Pat::SlicePat(_) | ast::Pat::RangePat(_) => Pat::Missing,
539 };
540 let ptr = AstPtr::new(&pat);
541 self.alloc_pat(pattern, Either::A(ptr))
542 }
543
544 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
545 if let Some(pat) = pat {
546 self.collect_pat(pat)
547 } else {
548 self.missing_pat()
549 }
550 }
551}
552
553impl From<ast::BinOp> for BinaryOp {
554 fn from(ast_op: ast::BinOp) -> Self {
555 match ast_op {
556 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
557 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
558 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
559 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
560 ast::BinOp::LesserEqualTest => {
561 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
562 }
563 ast::BinOp::GreaterEqualTest => {
564 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
565 }
566 ast::BinOp::LesserTest => {
567 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
568 }
569 ast::BinOp::GreaterTest => {
570 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
571 }
572 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
573 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
574 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
575 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
576 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
577 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
578 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
579 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
580 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
581 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
582 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
583 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
584 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
585 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
586 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
587 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
588 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
589 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
590 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
591 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
592 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
593 }
594 }
595}
diff --git a/crates/ra_hir_def/src/body/scope.rs b/crates/ra_hir_def/src/body/scope.rs
new file mode 100644
index 000000000..09a39e721
--- /dev/null
+++ b/crates/ra_hir_def/src/body/scope.rs
@@ -0,0 +1,165 @@
1//! FIXME: write short doc here
2use std::sync::Arc;
3
4use hir_expand::name::Name;
5use ra_arena::{impl_arena_id, Arena, RawId};
6use rustc_hash::FxHashMap;
7
8use crate::{
9 body::Body,
10 db::DefDatabase2,
11 expr::{Expr, ExprId, Pat, PatId, Statement},
12 DefWithBodyId,
13};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct ScopeId(RawId);
17impl_arena_id!(ScopeId);
18
19#[derive(Debug, PartialEq, Eq)]
20pub struct ExprScopes {
21 scopes: Arena<ScopeId, ScopeData>,
22 scope_by_expr: FxHashMap<ExprId, ScopeId>,
23}
24
25#[derive(Debug, PartialEq, Eq)]
26pub struct ScopeEntry {
27 name: Name,
28 pat: PatId,
29}
30
31impl ScopeEntry {
32 pub fn name(&self) -> &Name {
33 &self.name
34 }
35
36 pub fn pat(&self) -> PatId {
37 self.pat
38 }
39}
40
41#[derive(Debug, PartialEq, Eq)]
42pub struct ScopeData {
43 parent: Option<ScopeId>,
44 entries: Vec<ScopeEntry>,
45}
46
47impl ExprScopes {
48 pub(crate) fn expr_scopes_query(db: &impl DefDatabase2, def: DefWithBodyId) -> Arc<ExprScopes> {
49 let body = db.body(def);
50 Arc::new(ExprScopes::new(&*body))
51 }
52
53 fn new(body: &Body) -> ExprScopes {
54 let mut scopes =
55 ExprScopes { scopes: Arena::default(), scope_by_expr: FxHashMap::default() };
56 let root = scopes.root_scope();
57 scopes.add_params_bindings(body, root, body.params());
58 compute_expr_scopes(body.body_expr(), body, &mut scopes, root);
59 scopes
60 }
61
62 pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
63 &self.scopes[scope].entries
64 }
65
66 pub fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
67 std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
68 }
69
70 pub fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
71 self.scope_by_expr.get(&expr).copied()
72 }
73
74 pub fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
75 &self.scope_by_expr
76 }
77
78 fn root_scope(&mut self) -> ScopeId {
79 self.scopes.alloc(ScopeData { parent: None, entries: vec![] })
80 }
81
82 fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
83 self.scopes.alloc(ScopeData { parent: Some(parent), entries: vec![] })
84 }
85
86 fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
87 match &body[pat] {
88 Pat::Bind { name, .. } => {
89 // bind can have a sub pattern, but it's actually not allowed
90 // to bind to things in there
91 let entry = ScopeEntry { name: name.clone(), pat };
92 self.scopes[scope].entries.push(entry)
93 }
94 p => p.walk_child_pats(|pat| self.add_bindings(body, scope, pat)),
95 }
96 }
97
98 fn add_params_bindings(&mut self, body: &Body, scope: ScopeId, params: &[PatId]) {
99 params.iter().for_each(|pat| self.add_bindings(body, scope, *pat));
100 }
101
102 fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
103 self.scope_by_expr.insert(node, scope);
104 }
105}
106
107fn compute_block_scopes(
108 statements: &[Statement],
109 tail: Option<ExprId>,
110 body: &Body,
111 scopes: &mut ExprScopes,
112 mut scope: ScopeId,
113) {
114 for stmt in statements {
115 match stmt {
116 Statement::Let { pat, initializer, .. } => {
117 if let Some(expr) = initializer {
118 scopes.set_scope(*expr, scope);
119 compute_expr_scopes(*expr, body, scopes, scope);
120 }
121 scope = scopes.new_scope(scope);
122 scopes.add_bindings(body, scope, *pat);
123 }
124 Statement::Expr(expr) => {
125 scopes.set_scope(*expr, scope);
126 compute_expr_scopes(*expr, body, scopes, scope);
127 }
128 }
129 }
130 if let Some(expr) = tail {
131 compute_expr_scopes(expr, body, scopes, scope);
132 }
133}
134
135fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
136 scopes.set_scope(expr, scope);
137 match &body[expr] {
138 Expr::Block { statements, tail } => {
139 compute_block_scopes(&statements, *tail, body, scopes, scope);
140 }
141 Expr::For { iterable, pat, body: body_expr } => {
142 compute_expr_scopes(*iterable, body, scopes, scope);
143 let scope = scopes.new_scope(scope);
144 scopes.add_bindings(body, scope, *pat);
145 compute_expr_scopes(*body_expr, body, scopes, scope);
146 }
147 Expr::Lambda { args, body: body_expr, .. } => {
148 let scope = scopes.new_scope(scope);
149 scopes.add_params_bindings(body, scope, &args);
150 compute_expr_scopes(*body_expr, body, scopes, scope);
151 }
152 Expr::Match { expr, arms } => {
153 compute_expr_scopes(*expr, body, scopes, scope);
154 for arm in arms {
155 let scope = scopes.new_scope(scope);
156 for pat in &arm.pats {
157 scopes.add_bindings(body, scope, *pat);
158 }
159 scopes.set_scope(arm.expr, scope);
160 compute_expr_scopes(arm.expr, body, scopes, scope);
161 }
162 }
163 e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
164 };
165}
diff --git a/crates/ra_hir_def/src/builtin_type.rs b/crates/ra_hir_def/src/builtin_type.rs
index 12929caa9..5e8157144 100644
--- a/crates/ra_hir_def/src/builtin_type.rs
+++ b/crates/ra_hir_def/src/builtin_type.rs
@@ -3,6 +3,8 @@
3//! A peculiarity of built-in types is that they are always available and are 3//! A peculiarity of built-in types is that they are always available and are
4//! not associated with any particular crate. 4//! not associated with any particular crate.
5 5
6use std::fmt;
7
6use hir_expand::name::{self, Name}; 8use hir_expand::name::{self, Name};
7 9
8#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] 10#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
@@ -28,12 +30,23 @@ pub enum FloatBitness {
28} 30}
29 31
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub struct BuiltinInt {
34 pub signedness: Signedness,
35 pub bitness: IntBitness,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub struct BuiltinFloat {
40 pub bitness: FloatBitness,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum BuiltinType { 44pub enum BuiltinType {
32 Char, 45 Char,
33 Bool, 46 Bool,
34 Str, 47 Str,
35 Int { signedness: Signedness, bitness: IntBitness }, 48 Int(BuiltinInt),
36 Float { bitness: FloatBitness }, 49 Float(BuiltinFloat),
37} 50}
38 51
39impl BuiltinType { 52impl BuiltinType {
@@ -43,21 +56,105 @@ impl BuiltinType {
43 (name::BOOL, BuiltinType::Bool), 56 (name::BOOL, BuiltinType::Bool),
44 (name::STR, BuiltinType::Str ), 57 (name::STR, BuiltinType::Str ),
45 58
46 (name::ISIZE, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::Xsize }), 59 (name::ISIZE, BuiltinType::Int(BuiltinInt::ISIZE)),
47 (name::I8, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X8 }), 60 (name::I8, BuiltinType::Int(BuiltinInt::I8)),
48 (name::I16, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X16 }), 61 (name::I16, BuiltinType::Int(BuiltinInt::I16)),
49 (name::I32, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X32 }), 62 (name::I32, BuiltinType::Int(BuiltinInt::I32)),
50 (name::I64, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X64 }), 63 (name::I64, BuiltinType::Int(BuiltinInt::I64)),
51 (name::I128, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X128 }), 64 (name::I128, BuiltinType::Int(BuiltinInt::I128)),
52 65
53 (name::USIZE, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize }), 66 (name::USIZE, BuiltinType::Int(BuiltinInt::USIZE)),
54 (name::U8, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X8 }), 67 (name::U8, BuiltinType::Int(BuiltinInt::U8)),
55 (name::U16, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X16 }), 68 (name::U16, BuiltinType::Int(BuiltinInt::U16)),
56 (name::U32, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X32 }), 69 (name::U32, BuiltinType::Int(BuiltinInt::U32)),
57 (name::U64, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X64 }), 70 (name::U64, BuiltinType::Int(BuiltinInt::U64)),
58 (name::U128, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X128 }), 71 (name::U128, BuiltinType::Int(BuiltinInt::U128)),
59 72
60 (name::F32, BuiltinType::Float { bitness: FloatBitness::X32 }), 73 (name::F32, BuiltinType::Float(BuiltinFloat::F32)),
61 (name::F64, BuiltinType::Float { bitness: FloatBitness::X64 }), 74 (name::F64, BuiltinType::Float(BuiltinFloat::F64)),
62 ]; 75 ];
63} 76}
77
78impl fmt::Display for BuiltinType {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 let type_name = match self {
81 BuiltinType::Char => "char",
82 BuiltinType::Bool => "bool",
83 BuiltinType::Str => "str",
84 BuiltinType::Int(BuiltinInt { signedness, bitness }) => match (signedness, bitness) {
85 (Signedness::Signed, IntBitness::Xsize) => "isize",
86 (Signedness::Signed, IntBitness::X8) => "i8",
87 (Signedness::Signed, IntBitness::X16) => "i16",
88 (Signedness::Signed, IntBitness::X32) => "i32",
89 (Signedness::Signed, IntBitness::X64) => "i64",
90 (Signedness::Signed, IntBitness::X128) => "i128",
91
92 (Signedness::Unsigned, IntBitness::Xsize) => "usize",
93 (Signedness::Unsigned, IntBitness::X8) => "u8",
94 (Signedness::Unsigned, IntBitness::X16) => "u16",
95 (Signedness::Unsigned, IntBitness::X32) => "u32",
96 (Signedness::Unsigned, IntBitness::X64) => "u64",
97 (Signedness::Unsigned, IntBitness::X128) => "u128",
98 },
99 BuiltinType::Float(BuiltinFloat { bitness }) => match bitness {
100 FloatBitness::X32 => "f32",
101 FloatBitness::X64 => "f64",
102 },
103 };
104 f.write_str(type_name)
105 }
106}
107
108#[rustfmt::skip]
109impl BuiltinInt {
110 pub const ISIZE: BuiltinInt = BuiltinInt { signedness: Signedness::Signed, bitness: IntBitness::Xsize };
111 pub const I8 : BuiltinInt = BuiltinInt { signedness: Signedness::Signed, bitness: IntBitness::X8 };
112 pub const I16 : BuiltinInt = BuiltinInt { signedness: Signedness::Signed, bitness: IntBitness::X16 };
113 pub const I32 : BuiltinInt = BuiltinInt { signedness: Signedness::Signed, bitness: IntBitness::X32 };
114 pub const I64 : BuiltinInt = BuiltinInt { signedness: Signedness::Signed, bitness: IntBitness::X64 };
115 pub const I128 : BuiltinInt = BuiltinInt { signedness: Signedness::Signed, bitness: IntBitness::X128 };
116
117 pub const USIZE: BuiltinInt = BuiltinInt { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize };
118 pub const U8 : BuiltinInt = BuiltinInt { signedness: Signedness::Unsigned, bitness: IntBitness::X8 };
119 pub const U16 : BuiltinInt = BuiltinInt { signedness: Signedness::Unsigned, bitness: IntBitness::X16 };
120 pub const U32 : BuiltinInt = BuiltinInt { signedness: Signedness::Unsigned, bitness: IntBitness::X32 };
121 pub const U64 : BuiltinInt = BuiltinInt { signedness: Signedness::Unsigned, bitness: IntBitness::X64 };
122 pub const U128 : BuiltinInt = BuiltinInt { signedness: Signedness::Unsigned, bitness: IntBitness::X128 };
123
124
125 pub fn from_suffix(suffix: &str) -> Option<BuiltinInt> {
126 let res = match suffix {
127 "isize" => Self::ISIZE,
128 "i8" => Self::I8,
129 "i16" => Self::I16,
130 "i32" => Self::I32,
131 "i64" => Self::I64,
132 "i128" => Self::I128,
133
134 "usize" => Self::USIZE,
135 "u8" => Self::U8,
136 "u16" => Self::U16,
137 "u32" => Self::U32,
138 "u64" => Self::U64,
139 "u128" => Self::U128,
140
141 _ => return None,
142 };
143 Some(res)
144 }
145}
146
147#[rustfmt::skip]
148impl BuiltinFloat {
149 pub const F32: BuiltinFloat = BuiltinFloat { bitness: FloatBitness::X32 };
150 pub const F64: BuiltinFloat = BuiltinFloat { bitness: FloatBitness::X64 };
151
152 pub fn from_suffix(suffix: &str) -> Option<BuiltinFloat> {
153 let res = match suffix {
154 "f32" => BuiltinFloat::F32,
155 "f64" => BuiltinFloat::F64,
156 _ => return None,
157 };
158 Some(res)
159 }
160}
diff --git a/crates/ra_hir_def/src/db.rs b/crates/ra_hir_def/src/db.rs
index 29cf71a59..40b5920d9 100644
--- a/crates/ra_hir_def/src/db.rs
+++ b/crates/ra_hir_def/src/db.rs
@@ -7,11 +7,12 @@ use ra_syntax::ast;
7 7
8use crate::{ 8use crate::{
9 adt::{EnumData, StructData}, 9 adt::{EnumData, StructData},
10 body::{scope::ExprScopes, Body, BodySourceMap},
10 nameres::{ 11 nameres::{
11 raw::{ImportSourceMap, RawItems}, 12 raw::{ImportSourceMap, RawItems},
12 CrateDefMap, 13 CrateDefMap,
13 }, 14 },
14 EnumId, StructOrUnionId, 15 DefWithBodyId, EnumId, StructOrUnionId,
15}; 16};
16 17
17#[salsa::query_group(InternDatabaseStorage)] 18#[salsa::query_group(InternDatabaseStorage)]
@@ -52,4 +53,13 @@ pub trait DefDatabase2: InternDatabase + AstDatabase {
52 53
53 #[salsa::invoke(EnumData::enum_data_query)] 54 #[salsa::invoke(EnumData::enum_data_query)]
54 fn enum_data(&self, e: EnumId) -> Arc<EnumData>; 55 fn enum_data(&self, e: EnumId) -> Arc<EnumData>;
56
57 #[salsa::invoke(Body::body_with_source_map_query)]
58 fn body_with_source_map(&self, def: DefWithBodyId) -> (Arc<Body>, Arc<BodySourceMap>);
59
60 #[salsa::invoke(Body::body_query)]
61 fn body(&self, def: DefWithBodyId) -> Arc<Body>;
62
63 #[salsa::invoke(ExprScopes::expr_scopes_query)]
64 fn expr_scopes(&self, def: DefWithBodyId) -> Arc<ExprScopes>;
55} 65}
diff --git a/crates/ra_hir_def/src/expr.rs b/crates/ra_hir_def/src/expr.rs
new file mode 100644
index 000000000..04c1d8f69
--- /dev/null
+++ b/crates/ra_hir_def/src/expr.rs
@@ -0,0 +1,421 @@
1//! This module describes hir-level representation of expressions.
2//!
3//! This representaion is:
4//!
5//! 1. Identity-based. Each expression has an `id`, so we can distinguish
6//! between different `1` in `1 + 1`.
7//! 2. Independent of syntax. Though syntactic provenance information can be
8//! attached separately via id-based side map.
9//! 3. Unresolved. Paths are stored as sequences of names, and not as defs the
10//! names refer to.
11//! 4. Desugared. There's no `if let`.
12//!
13//! See also a neighboring `body` module.
14
15use hir_expand::name::Name;
16use ra_arena::{impl_arena_id, RawId};
17
18use crate::{
19 builtin_type::{BuiltinFloat, BuiltinInt},
20 path::{GenericArgs, Path},
21 type_ref::{Mutability, TypeRef},
22};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub struct ExprId(RawId);
26impl_arena_id!(ExprId);
27
28impl ExprId {
29 pub fn dummy() -> ExprId {
30 ExprId((!0).into())
31 }
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct PatId(RawId);
36impl_arena_id!(PatId);
37
38#[derive(Debug, Clone, Eq, PartialEq)]
39pub enum Literal {
40 String(String),
41 ByteString(Vec<u8>),
42 Char(char),
43 Bool(bool),
44 Int(u64, Option<BuiltinInt>),
45 Float(u64, Option<BuiltinFloat>), // FIXME: f64 is not Eq
46}
47
48#[derive(Debug, Clone, Eq, PartialEq)]
49pub enum Expr {
50 /// This is produced if syntax tree does not have a required expression piece.
51 Missing,
52 Path(Path),
53 If {
54 condition: ExprId,
55 then_branch: ExprId,
56 else_branch: Option<ExprId>,
57 },
58 Block {
59 statements: Vec<Statement>,
60 tail: Option<ExprId>,
61 },
62 Loop {
63 body: ExprId,
64 },
65 While {
66 condition: ExprId,
67 body: ExprId,
68 },
69 For {
70 iterable: ExprId,
71 pat: PatId,
72 body: ExprId,
73 },
74 Call {
75 callee: ExprId,
76 args: Vec<ExprId>,
77 },
78 MethodCall {
79 receiver: ExprId,
80 method_name: Name,
81 args: Vec<ExprId>,
82 generic_args: Option<GenericArgs>,
83 },
84 Match {
85 expr: ExprId,
86 arms: Vec<MatchArm>,
87 },
88 Continue,
89 Break {
90 expr: Option<ExprId>,
91 },
92 Return {
93 expr: Option<ExprId>,
94 },
95 RecordLit {
96 path: Option<Path>,
97 fields: Vec<RecordLitField>,
98 spread: Option<ExprId>,
99 },
100 Field {
101 expr: ExprId,
102 name: Name,
103 },
104 Await {
105 expr: ExprId,
106 },
107 Try {
108 expr: ExprId,
109 },
110 TryBlock {
111 body: ExprId,
112 },
113 Cast {
114 expr: ExprId,
115 type_ref: TypeRef,
116 },
117 Ref {
118 expr: ExprId,
119 mutability: Mutability,
120 },
121 Box {
122 expr: ExprId,
123 },
124 UnaryOp {
125 expr: ExprId,
126 op: UnaryOp,
127 },
128 BinaryOp {
129 lhs: ExprId,
130 rhs: ExprId,
131 op: Option<BinaryOp>,
132 },
133 Index {
134 base: ExprId,
135 index: ExprId,
136 },
137 Lambda {
138 args: Vec<PatId>,
139 arg_types: Vec<Option<TypeRef>>,
140 body: ExprId,
141 },
142 Tuple {
143 exprs: Vec<ExprId>,
144 },
145 Array(Array),
146 Literal(Literal),
147}
148
149#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
150pub enum BinaryOp {
151 LogicOp(LogicOp),
152 ArithOp(ArithOp),
153 CmpOp(CmpOp),
154 Assignment { op: Option<ArithOp> },
155}
156
157#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
158pub enum LogicOp {
159 And,
160 Or,
161}
162
163#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
164pub enum CmpOp {
165 Eq { negated: bool },
166 Ord { ordering: Ordering, strict: bool },
167}
168
169#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
170pub enum Ordering {
171 Less,
172 Greater,
173}
174
175#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
176pub enum ArithOp {
177 Add,
178 Mul,
179 Sub,
180 Div,
181 Rem,
182 Shl,
183 Shr,
184 BitXor,
185 BitOr,
186 BitAnd,
187}
188
189pub use ra_syntax::ast::PrefixOp as UnaryOp;
190#[derive(Debug, Clone, Eq, PartialEq)]
191pub enum Array {
192 ElementList(Vec<ExprId>),
193 Repeat { initializer: ExprId, repeat: ExprId },
194}
195
196#[derive(Debug, Clone, Eq, PartialEq)]
197pub struct MatchArm {
198 pub pats: Vec<PatId>,
199 pub guard: Option<ExprId>,
200 pub expr: ExprId,
201}
202
203#[derive(Debug, Clone, Eq, PartialEq)]
204pub struct RecordLitField {
205 pub name: Name,
206 pub expr: ExprId,
207}
208
209#[derive(Debug, Clone, Eq, PartialEq)]
210pub enum Statement {
211 Let { pat: PatId, type_ref: Option<TypeRef>, initializer: Option<ExprId> },
212 Expr(ExprId),
213}
214
215impl Expr {
216 pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
217 match self {
218 Expr::Missing => {}
219 Expr::Path(_) => {}
220 Expr::If { condition, then_branch, else_branch } => {
221 f(*condition);
222 f(*then_branch);
223 if let Some(else_branch) = else_branch {
224 f(*else_branch);
225 }
226 }
227 Expr::Block { statements, tail } => {
228 for stmt in statements {
229 match stmt {
230 Statement::Let { initializer, .. } => {
231 if let Some(expr) = initializer {
232 f(*expr);
233 }
234 }
235 Statement::Expr(e) => f(*e),
236 }
237 }
238 if let Some(expr) = tail {
239 f(*expr);
240 }
241 }
242 Expr::TryBlock { body } => f(*body),
243 Expr::Loop { body } => f(*body),
244 Expr::While { condition, body } => {
245 f(*condition);
246 f(*body);
247 }
248 Expr::For { iterable, body, .. } => {
249 f(*iterable);
250 f(*body);
251 }
252 Expr::Call { callee, args } => {
253 f(*callee);
254 for arg in args {
255 f(*arg);
256 }
257 }
258 Expr::MethodCall { receiver, args, .. } => {
259 f(*receiver);
260 for arg in args {
261 f(*arg);
262 }
263 }
264 Expr::Match { expr, arms } => {
265 f(*expr);
266 for arm in arms {
267 f(arm.expr);
268 }
269 }
270 Expr::Continue => {}
271 Expr::Break { expr } | Expr::Return { expr } => {
272 if let Some(expr) = expr {
273 f(*expr);
274 }
275 }
276 Expr::RecordLit { fields, spread, .. } => {
277 for field in fields {
278 f(field.expr);
279 }
280 if let Some(expr) = spread {
281 f(*expr);
282 }
283 }
284 Expr::Lambda { body, .. } => {
285 f(*body);
286 }
287 Expr::BinaryOp { lhs, rhs, .. } => {
288 f(*lhs);
289 f(*rhs);
290 }
291 Expr::Index { base, index } => {
292 f(*base);
293 f(*index);
294 }
295 Expr::Field { expr, .. }
296 | Expr::Await { expr }
297 | Expr::Try { expr }
298 | Expr::Cast { expr, .. }
299 | Expr::Ref { expr, .. }
300 | Expr::UnaryOp { expr, .. }
301 | Expr::Box { expr } => {
302 f(*expr);
303 }
304 Expr::Tuple { exprs } => {
305 for expr in exprs {
306 f(*expr);
307 }
308 }
309 Expr::Array(a) => match a {
310 Array::ElementList(exprs) => {
311 for expr in exprs {
312 f(*expr);
313 }
314 }
315 Array::Repeat { initializer, repeat } => {
316 f(*initializer);
317 f(*repeat)
318 }
319 },
320 Expr::Literal(_) => {}
321 }
322 }
323}
324
325/// Explicit binding annotations given in the HIR for a binding. Note
326/// that this is not the final binding *mode* that we infer after type
327/// inference.
328#[derive(Clone, PartialEq, Eq, Debug, Copy)]
329pub enum BindingAnnotation {
330 /// No binding annotation given: this means that the final binding mode
331 /// will depend on whether we have skipped through a `&` reference
332 /// when matching. For example, the `x` in `Some(x)` will have binding
333 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
334 /// ultimately be inferred to be by-reference.
335 Unannotated,
336
337 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
338 Mutable,
339
340 /// Annotated as `ref`, like `ref x`
341 Ref,
342
343 /// Annotated as `ref mut x`.
344 RefMut,
345}
346
347impl BindingAnnotation {
348 pub fn new(is_mutable: bool, is_ref: bool) -> Self {
349 match (is_mutable, is_ref) {
350 (true, true) => BindingAnnotation::RefMut,
351 (false, true) => BindingAnnotation::Ref,
352 (true, false) => BindingAnnotation::Mutable,
353 (false, false) => BindingAnnotation::Unannotated,
354 }
355 }
356}
357
358#[derive(Debug, Clone, Eq, PartialEq)]
359pub struct RecordFieldPat {
360 pub name: Name,
361 pub pat: PatId,
362}
363
364/// Close relative to rustc's hir::PatKind
365#[derive(Debug, Clone, Eq, PartialEq)]
366pub enum Pat {
367 Missing,
368 Wild,
369 Tuple(Vec<PatId>),
370 Record {
371 path: Option<Path>,
372 args: Vec<RecordFieldPat>,
373 // FIXME: 'ellipsis' option
374 },
375 Range {
376 start: ExprId,
377 end: ExprId,
378 },
379 Slice {
380 prefix: Vec<PatId>,
381 rest: Option<PatId>,
382 suffix: Vec<PatId>,
383 },
384 Path(Path),
385 Lit(ExprId),
386 Bind {
387 mode: BindingAnnotation,
388 name: Name,
389 subpat: Option<PatId>,
390 },
391 TupleStruct {
392 path: Option<Path>,
393 args: Vec<PatId>,
394 },
395 Ref {
396 pat: PatId,
397 mutability: Mutability,
398 },
399}
400
401impl Pat {
402 pub fn walk_child_pats(&self, mut f: impl FnMut(PatId)) {
403 match self {
404 Pat::Range { .. } | Pat::Lit(..) | Pat::Path(..) | Pat::Wild | Pat::Missing => {}
405 Pat::Bind { subpat, .. } => {
406 subpat.iter().copied().for_each(f);
407 }
408 Pat::Tuple(args) | Pat::TupleStruct { args, .. } => {
409 args.iter().copied().for_each(f);
410 }
411 Pat::Ref { pat, .. } => f(*pat),
412 Pat::Slice { prefix, rest, suffix } => {
413 let total_iter = prefix.iter().chain(rest.iter()).chain(suffix.iter());
414 total_iter.copied().for_each(f);
415 }
416 Pat::Record { args, .. } => {
417 args.iter().map(|f| f.pat).for_each(f);
418 }
419 }
420 }
421}
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs
index 239317efe..3fab7965c 100644
--- a/crates/ra_hir_def/src/lib.rs
+++ b/crates/ra_hir_def/src/lib.rs
@@ -14,6 +14,8 @@ pub mod type_ref;
14pub mod builtin_type; 14pub mod builtin_type;
15pub mod adt; 15pub mod adt;
16pub mod diagnostics; 16pub mod diagnostics;
17pub mod expr;
18pub mod body;
17 19
18#[cfg(test)] 20#[cfg(test)]
19mod test_db; 21mod test_db;
@@ -372,3 +374,13 @@ impl_froms!(
372 TypeAliasId, 374 TypeAliasId,
373 BuiltinType 375 BuiltinType
374); 376);
377
378/// The defs which have a body.
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
380pub enum DefWithBodyId {
381 FunctionId(FunctionId),
382 StaticId(StaticId),
383 ConstId(ConstId),
384}
385
386impl_froms!(DefWithBodyId: FunctionId, ConstId, StaticId);
diff --git a/crates/ra_hir_def/src/nameres/collector.rs b/crates/ra_hir_def/src/nameres/collector.rs
index 7e6083961..37d0f3093 100644
--- a/crates/ra_hir_def/src/nameres/collector.rs
+++ b/crates/ra_hir_def/src/nameres/collector.rs
@@ -1,8 +1,9 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2 2
3use hir_expand::{ 3use hir_expand::{
4 builtin_macro::find_builtin_macro,
4 name::{self, AsName, Name}, 5 name::{self, AsName, Name},
5 HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind, 6 HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroDefKind, MacroFileKind,
6}; 7};
7use ra_cfg::CfgOptions; 8use ra_cfg::CfgOptions;
8use ra_db::{CrateId, FileId}; 9use ra_db::{CrateId, FileId};
@@ -36,11 +37,12 @@ pub(super) fn collect_defs(db: &impl DefDatabase2, mut def_map: CrateDefMap) ->
36 ); 37 );
37 38
38 // look for the prelude 39 // look for the prelude
39 if def_map.prelude.is_none() { 40 // If the dependency defines a prelude, we overwrite an already defined
40 let map = db.crate_def_map(dep.crate_id); 41 // prelude. This is necessary to import the "std" prelude if a crate
41 if map.prelude.is_some() { 42 // depends on both "core" and "std".
42 def_map.prelude = map.prelude; 43 let dep_def_map = db.crate_def_map(dep.crate_id);
43 } 44 if dep_def_map.prelude.is_some() {
45 def_map.prelude = dep_def_map.prelude;
44 } 46 }
45 } 47 }
46 48
@@ -691,10 +693,30 @@ where
691 fn collect_macro(&mut self, mac: &raw::MacroData) { 693 fn collect_macro(&mut self, mac: &raw::MacroData) {
692 let ast_id = AstId::new(self.file_id, mac.ast_id); 694 let ast_id = AstId::new(self.file_id, mac.ast_id);
693 695
696 // Case 0: builtin macros
697 if mac.builtin {
698 if let Some(name) = &mac.name {
699 let krate = self.def_collector.def_map.krate;
700 if let Some(macro_id) = find_builtin_macro(name, krate, ast_id) {
701 self.def_collector.define_macro(
702 self.module_id,
703 name.clone(),
704 macro_id,
705 mac.export,
706 );
707 return;
708 }
709 }
710 }
711
694 // Case 1: macro rules, define a macro in crate-global mutable scope 712 // Case 1: macro rules, define a macro in crate-global mutable scope
695 if is_macro_rules(&mac.path) { 713 if is_macro_rules(&mac.path) {
696 if let Some(name) = &mac.name { 714 if let Some(name) = &mac.name {
697 let macro_id = MacroDefId { ast_id, krate: self.def_collector.def_map.krate }; 715 let macro_id = MacroDefId {
716 ast_id,
717 krate: self.def_collector.def_map.krate,
718 kind: MacroDefKind::Declarative,
719 };
698 self.def_collector.define_macro(self.module_id, name.clone(), macro_id, mac.export); 720 self.def_collector.define_macro(self.module_id, name.clone(), macro_id, mac.export);
699 } 721 }
700 return; 722 return;
diff --git a/crates/ra_hir_def/src/nameres/raw.rs b/crates/ra_hir_def/src/nameres/raw.rs
index 369376f30..f52002bc0 100644
--- a/crates/ra_hir_def/src/nameres/raw.rs
+++ b/crates/ra_hir_def/src/nameres/raw.rs
@@ -200,6 +200,7 @@ pub(super) struct MacroData {
200 pub(super) path: Path, 200 pub(super) path: Path,
201 pub(super) name: Option<Name>, 201 pub(super) name: Option<Name>,
202 pub(super) export: bool, 202 pub(super) export: bool,
203 pub(super) builtin: bool,
203} 204}
204 205
205struct RawItemsCollector { 206struct RawItemsCollector {
@@ -367,7 +368,11 @@ impl RawItemsCollector {
367 // FIXME: cfg_attr 368 // FIXME: cfg_attr
368 let export = m.attrs().filter_map(|x| x.simple_name()).any(|name| name == "macro_export"); 369 let export = m.attrs().filter_map(|x| x.simple_name()).any(|name| name == "macro_export");
369 370
370 let m = self.raw_items.macros.alloc(MacroData { ast_id, path, name, export }); 371 // FIXME: cfg_attr
372 let builtin =
373 m.attrs().filter_map(|x| x.simple_name()).any(|name| name == "rustc_builtin_macro");
374
375 let m = self.raw_items.macros.alloc(MacroData { ast_id, path, name, export, builtin });
371 self.push_item(current_module, attrs, RawItemKind::Macro(m)); 376 self.push_item(current_module, attrs, RawItemKind::Macro(m));
372 } 377 }
373 378
diff --git a/crates/ra_hir_def/src/nameres/tests.rs b/crates/ra_hir_def/src/nameres/tests.rs
index 52bd0aa91..256f7d4be 100644
--- a/crates/ra_hir_def/src/nameres/tests.rs
+++ b/crates/ra_hir_def/src/nameres/tests.rs
@@ -464,6 +464,37 @@ fn values_dont_shadow_extern_crates() {
464} 464}
465 465
466#[test] 466#[test]
467fn std_prelude_takes_precedence_above_core_prelude() {
468 let map = def_map(
469 r#"
470 //- /main.rs crate:main deps:core,std
471 use {Foo, Bar};
472
473 //- /std.rs crate:std deps:core
474 #[prelude_import]
475 pub use self::prelude::*;
476 mod prelude {
477 pub struct Foo;
478 pub use core::prelude::Bar;
479 }
480
481 //- /core.rs crate:core
482 #[prelude_import]
483 pub use self::prelude::*;
484 mod prelude {
485 pub struct Bar;
486 }
487 "#,
488 );
489
490 assert_snapshot!(map, @r###"
491 ⋮crate
492 ⋮Bar: t v
493 ⋮Foo: t v
494 "###);
495}
496
497#[test]
467fn cfg_not_test() { 498fn cfg_not_test() {
468 let map = def_map( 499 let map = def_map(
469 r#" 500 r#"