aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_def/src
diff options
context:
space:
mode:
authorSeivan Heidari <[email protected]>2019-11-12 18:04:54 +0000
committerSeivan Heidari <[email protected]>2019-11-12 18:04:54 +0000
commit0525778a3ad590492b51cc11085d815f9bb8f92b (patch)
tree56096932b19861ab86c9564717f88cf7cd86d023 /crates/ra_hir_def/src
parent11755f3eff87cd8ee0af7961377e0ae3ffea5050 (diff)
parent3322d65addd9ec61b8c5bc055803f6549946da8b (diff)
Merge branch 'master' of https://github.com/rust-analyzer/rust-analyzer into feature/themes
Diffstat (limited to 'crates/ra_hir_def/src')
-rw-r--r--crates/ra_hir_def/src/body.rs144
-rw-r--r--crates/ra_hir_def/src/body/lower.rs631
-rw-r--r--crates/ra_hir_def/src/builtin_type.rs105
-rw-r--r--crates/ra_hir_def/src/expr.rs421
-rw-r--r--crates/ra_hir_def/src/lib.rs2
5 files changed, 1283 insertions, 20 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..ac8f8261b
--- /dev/null
+++ b/crates/ra_hir_def/src/body.rs
@@ -0,0 +1,144 @@
1//! FIXME: write short doc here
2mod lower;
3
4use std::{ops::Index, sync::Arc};
5
6use hir_expand::{either::Either, HirFileId, MacroDefId, Source};
7use ra_arena::{map::ArenaMap, Arena};
8use ra_syntax::{ast, AstPtr};
9use rustc_hash::FxHashMap;
10
11use crate::{
12 db::DefDatabase2,
13 expr::{Expr, ExprId, Pat, PatId},
14 nameres::CrateDefMap,
15 path::Path,
16 ModuleId,
17};
18
19pub struct MacroResolver {
20 crate_def_map: Arc<CrateDefMap>,
21 module: ModuleId,
22}
23
24impl MacroResolver {
25 pub fn new(db: &impl DefDatabase2, module: ModuleId) -> MacroResolver {
26 MacroResolver { crate_def_map: db.crate_def_map(module.krate), module }
27 }
28
29 pub(crate) fn resolve_path_as_macro(
30 &self,
31 db: &impl DefDatabase2,
32 path: &Path,
33 ) -> Option<MacroDefId> {
34 self.crate_def_map.resolve_path(db, self.module.module_id, path).0.get_macros()
35 }
36}
37
38/// The body of an item (function, const etc.).
39#[derive(Debug, Eq, PartialEq)]
40pub struct Body {
41 exprs: Arena<ExprId, Expr>,
42 pats: Arena<PatId, Pat>,
43 /// The patterns for the function's parameters. While the parameter types are
44 /// part of the function signature, the patterns are not (they don't change
45 /// the external type of the function).
46 ///
47 /// If this `Body` is for the body of a constant, this will just be
48 /// empty.
49 params: Vec<PatId>,
50 /// The `ExprId` of the actual body expression.
51 body_expr: ExprId,
52}
53
54pub type ExprPtr = Either<AstPtr<ast::Expr>, AstPtr<ast::RecordField>>;
55pub type ExprSource = Source<ExprPtr>;
56
57pub type PatPtr = Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>;
58pub type PatSource = Source<PatPtr>;
59
60/// An item body together with the mapping from syntax nodes to HIR expression
61/// IDs. This is needed to go from e.g. a position in a file to the HIR
62/// expression containing it; but for type inference etc., we want to operate on
63/// a structure that is agnostic to the actual positions of expressions in the
64/// file, so that we don't recompute types whenever some whitespace is typed.
65///
66/// One complication here is that, due to macro expansion, a single `Body` might
67/// be spread across several files. So, for each ExprId and PatId, we record
68/// both the HirFileId and the position inside the file. However, we only store
69/// AST -> ExprId mapping for non-macro files, as it is not clear how to handle
70/// this properly for macros.
71#[derive(Default, Debug, Eq, PartialEq)]
72pub struct BodySourceMap {
73 expr_map: FxHashMap<ExprPtr, ExprId>,
74 expr_map_back: ArenaMap<ExprId, ExprSource>,
75 pat_map: FxHashMap<PatPtr, PatId>,
76 pat_map_back: ArenaMap<PatId, PatSource>,
77 field_map: FxHashMap<(ExprId, usize), AstPtr<ast::RecordField>>,
78}
79
80impl Body {
81 pub fn new(
82 db: &impl DefDatabase2,
83 resolver: MacroResolver,
84 file_id: HirFileId,
85 params: Option<ast::ParamList>,
86 body: Option<ast::Expr>,
87 ) -> (Body, BodySourceMap) {
88 lower::lower(db, resolver, file_id, params, body)
89 }
90
91 pub fn params(&self) -> &[PatId] {
92 &self.params
93 }
94
95 pub fn body_expr(&self) -> ExprId {
96 self.body_expr
97 }
98
99 pub fn exprs(&self) -> impl Iterator<Item = (ExprId, &Expr)> {
100 self.exprs.iter()
101 }
102
103 pub fn pats(&self) -> impl Iterator<Item = (PatId, &Pat)> {
104 self.pats.iter()
105 }
106}
107
108impl Index<ExprId> for Body {
109 type Output = Expr;
110
111 fn index(&self, expr: ExprId) -> &Expr {
112 &self.exprs[expr]
113 }
114}
115
116impl Index<PatId> for Body {
117 type Output = Pat;
118
119 fn index(&self, pat: PatId) -> &Pat {
120 &self.pats[pat]
121 }
122}
123
124impl BodySourceMap {
125 pub fn expr_syntax(&self, expr: ExprId) -> Option<ExprSource> {
126 self.expr_map_back.get(expr).copied()
127 }
128
129 pub fn node_expr(&self, node: &ast::Expr) -> Option<ExprId> {
130 self.expr_map.get(&Either::A(AstPtr::new(node))).cloned()
131 }
132
133 pub fn pat_syntax(&self, pat: PatId) -> Option<PatSource> {
134 self.pat_map_back.get(pat).copied()
135 }
136
137 pub fn node_pat(&self, node: &ast::Pat) -> Option<PatId> {
138 self.pat_map.get(&Either::A(AstPtr::new(node))).cloned()
139 }
140
141 pub fn field_syntax(&self, expr: ExprId, field: usize) -> AstPtr<ast::RecordField> {
142 self.field_map[&(expr, field)]
143 }
144}
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..2aa863c9e
--- /dev/null
+++ b/crates/ra_hir_def/src/body/lower.rs
@@ -0,0 +1,631 @@
1//! FIXME: write short doc here
2
3use hir_expand::{
4 either::Either,
5 hygiene::Hygiene,
6 name::{self, AsName, Name},
7 AstId, HirFileId, MacroCallLoc, MacroFileKind, Source,
8};
9use ra_arena::Arena;
10use ra_syntax::{
11 ast::{
12 self, ArgListOwner, ArrayExprKind, LiteralKind, LoopBodyOwner, NameOwner,
13 TypeAscriptionOwner,
14 },
15 AstNode, AstPtr,
16};
17
18use crate::{
19 body::{Body, BodySourceMap, MacroResolver, PatPtr},
20 builtin_type::{BuiltinFloat, BuiltinInt},
21 db::DefDatabase2,
22 expr::{
23 ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp,
24 MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement,
25 },
26 path::GenericArgs,
27 path::Path,
28 type_ref::{Mutability, TypeRef},
29};
30
31pub(super) fn lower(
32 db: &impl DefDatabase2,
33 resolver: MacroResolver,
34 file_id: HirFileId,
35 params: Option<ast::ParamList>,
36 body: Option<ast::Expr>,
37) -> (Body, BodySourceMap) {
38 ExprCollector {
39 resolver,
40 db,
41 original_file_id: file_id,
42 current_file_id: file_id,
43 source_map: BodySourceMap::default(),
44 body: Body {
45 exprs: Arena::default(),
46 pats: Arena::default(),
47 params: Vec::new(),
48 body_expr: ExprId::dummy(),
49 },
50 }
51 .collect(params, body)
52}
53
54struct ExprCollector<DB> {
55 db: DB,
56 resolver: MacroResolver,
57 original_file_id: HirFileId,
58 current_file_id: HirFileId,
59
60 body: Body,
61 source_map: BodySourceMap,
62}
63
64impl<'a, DB> ExprCollector<&'a DB>
65where
66 DB: DefDatabase2,
67{
68 fn collect(
69 mut self,
70 param_list: Option<ast::ParamList>,
71 body: Option<ast::Expr>,
72 ) -> (Body, BodySourceMap) {
73 if let Some(param_list) = param_list {
74 if let Some(self_param) = param_list.self_param() {
75 let ptr = AstPtr::new(&self_param);
76 let param_pat = self.alloc_pat(
77 Pat::Bind {
78 name: name::SELF_PARAM,
79 mode: BindingAnnotation::Unannotated,
80 subpat: None,
81 },
82 Either::B(ptr),
83 );
84 self.body.params.push(param_pat);
85 }
86
87 for param in param_list.params() {
88 let pat = match param.pat() {
89 None => continue,
90 Some(pat) => pat,
91 };
92 let param_pat = self.collect_pat(pat);
93 self.body.params.push(param_pat);
94 }
95 };
96
97 self.body.body_expr = self.collect_expr_opt(body);
98 (self.body, self.source_map)
99 }
100
101 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
102 let ptr = Either::A(ptr);
103 let id = self.body.exprs.alloc(expr);
104 if self.current_file_id == self.original_file_id {
105 self.source_map.expr_map.insert(ptr, id);
106 }
107 self.source_map
108 .expr_map_back
109 .insert(id, Source { file_id: self.current_file_id, ast: ptr });
110 id
111 }
112 // desugared exprs don't have ptr, that's wrong and should be fixed
113 // somehow.
114 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
115 self.body.exprs.alloc(expr)
116 }
117 fn alloc_expr_field_shorthand(&mut self, expr: Expr, ptr: AstPtr<ast::RecordField>) -> ExprId {
118 let ptr = Either::B(ptr);
119 let id = self.body.exprs.alloc(expr);
120 if self.current_file_id == self.original_file_id {
121 self.source_map.expr_map.insert(ptr, id);
122 }
123 self.source_map
124 .expr_map_back
125 .insert(id, Source { file_id: self.current_file_id, ast: ptr });
126 id
127 }
128 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
129 let id = self.body.pats.alloc(pat);
130 if self.current_file_id == self.original_file_id {
131 self.source_map.pat_map.insert(ptr, id);
132 }
133 self.source_map.pat_map_back.insert(id, Source { file_id: self.current_file_id, ast: ptr });
134 id
135 }
136
137 fn empty_block(&mut self) -> ExprId {
138 let block = Expr::Block { statements: Vec::new(), tail: None };
139 self.body.exprs.alloc(block)
140 }
141
142 fn missing_expr(&mut self) -> ExprId {
143 self.body.exprs.alloc(Expr::Missing)
144 }
145
146 fn missing_pat(&mut self) -> PatId {
147 self.body.pats.alloc(Pat::Missing)
148 }
149
150 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
151 let syntax_ptr = AstPtr::new(&expr);
152 match expr {
153 ast::Expr::IfExpr(e) => {
154 let then_branch = self.collect_block_opt(e.then_branch());
155
156 let else_branch = e.else_branch().map(|b| match b {
157 ast::ElseBranch::Block(it) => self.collect_block(it),
158 ast::ElseBranch::IfExpr(elif) => {
159 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
160 self.collect_expr(expr)
161 }
162 });
163
164 let condition = match e.condition() {
165 None => self.missing_expr(),
166 Some(condition) => match condition.pat() {
167 None => self.collect_expr_opt(condition.expr()),
168 // if let -- desugar to match
169 Some(pat) => {
170 let pat = self.collect_pat(pat);
171 let match_expr = self.collect_expr_opt(condition.expr());
172 let placeholder_pat = self.missing_pat();
173 let arms = vec![
174 MatchArm { pats: vec![pat], expr: then_branch, guard: None },
175 MatchArm {
176 pats: vec![placeholder_pat],
177 expr: else_branch.unwrap_or_else(|| self.empty_block()),
178 guard: None,
179 },
180 ];
181 return self
182 .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr);
183 }
184 },
185 };
186
187 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
188 }
189 ast::Expr::TryBlockExpr(e) => {
190 let body = self.collect_block_opt(e.body());
191 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
192 }
193 ast::Expr::BlockExpr(e) => self.collect_block(e),
194 ast::Expr::LoopExpr(e) => {
195 let body = self.collect_block_opt(e.loop_body());
196 self.alloc_expr(Expr::Loop { body }, syntax_ptr)
197 }
198 ast::Expr::WhileExpr(e) => {
199 let body = self.collect_block_opt(e.loop_body());
200
201 let condition = match e.condition() {
202 None => self.missing_expr(),
203 Some(condition) => match condition.pat() {
204 None => self.collect_expr_opt(condition.expr()),
205 // if let -- desugar to match
206 Some(pat) => {
207 let pat = self.collect_pat(pat);
208 let match_expr = self.collect_expr_opt(condition.expr());
209 let placeholder_pat = self.missing_pat();
210 let break_ = self.alloc_expr_desugared(Expr::Break { expr: None });
211 let arms = vec![
212 MatchArm { pats: vec![pat], expr: body, guard: None },
213 MatchArm { pats: vec![placeholder_pat], expr: break_, guard: None },
214 ];
215 let match_expr =
216 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
217 return self.alloc_expr(Expr::Loop { body: match_expr }, syntax_ptr);
218 }
219 },
220 };
221
222 self.alloc_expr(Expr::While { condition, body }, syntax_ptr)
223 }
224 ast::Expr::ForExpr(e) => {
225 let iterable = self.collect_expr_opt(e.iterable());
226 let pat = self.collect_pat_opt(e.pat());
227 let body = self.collect_block_opt(e.loop_body());
228 self.alloc_expr(Expr::For { iterable, pat, body }, syntax_ptr)
229 }
230 ast::Expr::CallExpr(e) => {
231 let callee = self.collect_expr_opt(e.expr());
232 let args = if let Some(arg_list) = e.arg_list() {
233 arg_list.args().map(|e| self.collect_expr(e)).collect()
234 } else {
235 Vec::new()
236 };
237 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
238 }
239 ast::Expr::MethodCallExpr(e) => {
240 let receiver = self.collect_expr_opt(e.expr());
241 let args = if let Some(arg_list) = e.arg_list() {
242 arg_list.args().map(|e| self.collect_expr(e)).collect()
243 } else {
244 Vec::new()
245 };
246 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
247 let generic_args = e.type_arg_list().and_then(GenericArgs::from_ast);
248 self.alloc_expr(
249 Expr::MethodCall { receiver, method_name, args, generic_args },
250 syntax_ptr,
251 )
252 }
253 ast::Expr::MatchExpr(e) => {
254 let expr = self.collect_expr_opt(e.expr());
255 let arms = if let Some(match_arm_list) = e.match_arm_list() {
256 match_arm_list
257 .arms()
258 .map(|arm| MatchArm {
259 pats: arm.pats().map(|p| self.collect_pat(p)).collect(),
260 expr: self.collect_expr_opt(arm.expr()),
261 guard: arm
262 .guard()
263 .and_then(|guard| guard.expr())
264 .map(|e| self.collect_expr(e)),
265 })
266 .collect()
267 } else {
268 Vec::new()
269 };
270 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
271 }
272 ast::Expr::PathExpr(e) => {
273 let path = e
274 .path()
275 .and_then(|path| self.parse_path(path))
276 .map(Expr::Path)
277 .unwrap_or(Expr::Missing);
278 self.alloc_expr(path, syntax_ptr)
279 }
280 ast::Expr::ContinueExpr(_e) => {
281 // FIXME: labels
282 self.alloc_expr(Expr::Continue, syntax_ptr)
283 }
284 ast::Expr::BreakExpr(e) => {
285 let expr = e.expr().map(|e| self.collect_expr(e));
286 self.alloc_expr(Expr::Break { expr }, syntax_ptr)
287 }
288 ast::Expr::ParenExpr(e) => {
289 let inner = self.collect_expr_opt(e.expr());
290 // make the paren expr point to the inner expression as well
291 self.source_map.expr_map.insert(Either::A(syntax_ptr), inner);
292 inner
293 }
294 ast::Expr::ReturnExpr(e) => {
295 let expr = e.expr().map(|e| self.collect_expr(e));
296 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
297 }
298 ast::Expr::RecordLit(e) => {
299 let path = e.path().and_then(|path| self.parse_path(path));
300 let mut field_ptrs = Vec::new();
301 let record_lit = if let Some(nfl) = e.record_field_list() {
302 let fields = nfl
303 .fields()
304 .inspect(|field| field_ptrs.push(AstPtr::new(field)))
305 .map(|field| RecordLitField {
306 name: field
307 .name_ref()
308 .map(|nr| nr.as_name())
309 .unwrap_or_else(Name::missing),
310 expr: if let Some(e) = field.expr() {
311 self.collect_expr(e)
312 } else if let Some(nr) = field.name_ref() {
313 // field shorthand
314 self.alloc_expr_field_shorthand(
315 Expr::Path(Path::from_name_ref(&nr)),
316 AstPtr::new(&field),
317 )
318 } else {
319 self.missing_expr()
320 },
321 })
322 .collect();
323 let spread = nfl.spread().map(|s| self.collect_expr(s));
324 Expr::RecordLit { path, fields, spread }
325 } else {
326 Expr::RecordLit { path, fields: Vec::new(), spread: None }
327 };
328
329 let res = self.alloc_expr(record_lit, syntax_ptr);
330 for (i, ptr) in field_ptrs.into_iter().enumerate() {
331 self.source_map.field_map.insert((res, i), ptr);
332 }
333 res
334 }
335 ast::Expr::FieldExpr(e) => {
336 let expr = self.collect_expr_opt(e.expr());
337 let name = match e.field_access() {
338 Some(kind) => kind.as_name(),
339 _ => Name::missing(),
340 };
341 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
342 }
343 ast::Expr::AwaitExpr(e) => {
344 let expr = self.collect_expr_opt(e.expr());
345 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
346 }
347 ast::Expr::TryExpr(e) => {
348 let expr = self.collect_expr_opt(e.expr());
349 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
350 }
351 ast::Expr::CastExpr(e) => {
352 let expr = self.collect_expr_opt(e.expr());
353 let type_ref = TypeRef::from_ast_opt(e.type_ref());
354 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
355 }
356 ast::Expr::RefExpr(e) => {
357 let expr = self.collect_expr_opt(e.expr());
358 let mutability = Mutability::from_mutable(e.is_mut());
359 self.alloc_expr(Expr::Ref { expr, mutability }, syntax_ptr)
360 }
361 ast::Expr::PrefixExpr(e) => {
362 let expr = self.collect_expr_opt(e.expr());
363 if let Some(op) = e.op_kind() {
364 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
365 } else {
366 self.alloc_expr(Expr::Missing, syntax_ptr)
367 }
368 }
369 ast::Expr::LambdaExpr(e) => {
370 let mut args = Vec::new();
371 let mut arg_types = Vec::new();
372 if let Some(pl) = e.param_list() {
373 for param in pl.params() {
374 let pat = self.collect_pat_opt(param.pat());
375 let type_ref = param.ascribed_type().map(TypeRef::from_ast);
376 args.push(pat);
377 arg_types.push(type_ref);
378 }
379 }
380 let body = self.collect_expr_opt(e.body());
381 self.alloc_expr(Expr::Lambda { args, arg_types, body }, syntax_ptr)
382 }
383 ast::Expr::BinExpr(e) => {
384 let lhs = self.collect_expr_opt(e.lhs());
385 let rhs = self.collect_expr_opt(e.rhs());
386 let op = e.op_kind().map(BinaryOp::from);
387 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
388 }
389 ast::Expr::TupleExpr(e) => {
390 let exprs = e.exprs().map(|expr| self.collect_expr(expr)).collect();
391 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
392 }
393 ast::Expr::BoxExpr(e) => {
394 let expr = self.collect_expr_opt(e.expr());
395 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
396 }
397
398 ast::Expr::ArrayExpr(e) => {
399 let kind = e.kind();
400
401 match kind {
402 ArrayExprKind::ElementList(e) => {
403 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
404 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
405 }
406 ArrayExprKind::Repeat { initializer, repeat } => {
407 let initializer = self.collect_expr_opt(initializer);
408 let repeat = self.collect_expr_opt(repeat);
409 self.alloc_expr(
410 Expr::Array(Array::Repeat { initializer, repeat }),
411 syntax_ptr,
412 )
413 }
414 }
415 }
416
417 ast::Expr::Literal(e) => {
418 let lit = match e.kind() {
419 LiteralKind::IntNumber { suffix } => {
420 let known_name = suffix.and_then(|it| BuiltinInt::from_suffix(&it));
421
422 Literal::Int(Default::default(), known_name)
423 }
424 LiteralKind::FloatNumber { suffix } => {
425 let known_name = suffix.and_then(|it| BuiltinFloat::from_suffix(&it));
426
427 Literal::Float(Default::default(), known_name)
428 }
429 LiteralKind::ByteString => Literal::ByteString(Default::default()),
430 LiteralKind::String => Literal::String(Default::default()),
431 LiteralKind::Byte => Literal::Int(Default::default(), Some(BuiltinInt::U8)),
432 LiteralKind::Bool => Literal::Bool(Default::default()),
433 LiteralKind::Char => Literal::Char(Default::default()),
434 };
435 self.alloc_expr(Expr::Literal(lit), syntax_ptr)
436 }
437 ast::Expr::IndexExpr(e) => {
438 let base = self.collect_expr_opt(e.base());
439 let index = self.collect_expr_opt(e.index());
440 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
441 }
442
443 // FIXME implement HIR for these:
444 ast::Expr::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
445 ast::Expr::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
446 ast::Expr::MacroCall(e) => {
447 let ast_id = AstId::new(
448 self.current_file_id,
449 self.db.ast_id_map(self.current_file_id).ast_id(&e),
450 );
451
452 if let Some(path) = e.path().and_then(|path| self.parse_path(path)) {
453 if let Some(def) = self.resolver.resolve_path_as_macro(self.db, &path) {
454 let call_id = self.db.intern_macro(MacroCallLoc { def, ast_id });
455 let file_id = call_id.as_file(MacroFileKind::Expr);
456 if let Some(node) = self.db.parse_or_expand(file_id) {
457 if let Some(expr) = ast::Expr::cast(node) {
458 log::debug!("macro expansion {:#?}", expr.syntax());
459 let old_file_id =
460 std::mem::replace(&mut self.current_file_id, file_id);
461 let id = self.collect_expr(expr);
462 self.current_file_id = old_file_id;
463 return id;
464 }
465 }
466 }
467 }
468 // FIXME: Instead of just dropping the error from expansion
469 // report it
470 self.alloc_expr(Expr::Missing, syntax_ptr)
471 }
472 }
473 }
474
475 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
476 if let Some(expr) = expr {
477 self.collect_expr(expr)
478 } else {
479 self.missing_expr()
480 }
481 }
482
483 fn collect_block(&mut self, expr: ast::BlockExpr) -> ExprId {
484 let syntax_node_ptr = AstPtr::new(&expr.clone().into());
485 let block = match expr.block() {
486 Some(block) => block,
487 None => return self.alloc_expr(Expr::Missing, syntax_node_ptr),
488 };
489 let statements = block
490 .statements()
491 .map(|s| match s {
492 ast::Stmt::LetStmt(stmt) => {
493 let pat = self.collect_pat_opt(stmt.pat());
494 let type_ref = stmt.ascribed_type().map(TypeRef::from_ast);
495 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
496 Statement::Let { pat, type_ref, initializer }
497 }
498 ast::Stmt::ExprStmt(stmt) => Statement::Expr(self.collect_expr_opt(stmt.expr())),
499 })
500 .collect();
501 let tail = block.expr().map(|e| self.collect_expr(e));
502 self.alloc_expr(Expr::Block { statements, tail }, syntax_node_ptr)
503 }
504
505 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
506 if let Some(block) = expr {
507 self.collect_block(block)
508 } else {
509 self.missing_expr()
510 }
511 }
512
513 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
514 let pattern = match &pat {
515 ast::Pat::BindPat(bp) => {
516 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
517 let annotation = BindingAnnotation::new(bp.is_mutable(), bp.is_ref());
518 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
519 Pat::Bind { name, mode: annotation, subpat }
520 }
521 ast::Pat::TupleStructPat(p) => {
522 let path = p.path().and_then(|path| self.parse_path(path));
523 let args = p.args().map(|p| self.collect_pat(p)).collect();
524 Pat::TupleStruct { path, args }
525 }
526 ast::Pat::RefPat(p) => {
527 let pat = self.collect_pat_opt(p.pat());
528 let mutability = Mutability::from_mutable(p.is_mut());
529 Pat::Ref { pat, mutability }
530 }
531 ast::Pat::PathPat(p) => {
532 let path = p.path().and_then(|path| self.parse_path(path));
533 path.map(Pat::Path).unwrap_or(Pat::Missing)
534 }
535 ast::Pat::TuplePat(p) => {
536 let args = p.args().map(|p| self.collect_pat(p)).collect();
537 Pat::Tuple(args)
538 }
539 ast::Pat::PlaceholderPat(_) => Pat::Wild,
540 ast::Pat::RecordPat(p) => {
541 let path = p.path().and_then(|path| self.parse_path(path));
542 let record_field_pat_list =
543 p.record_field_pat_list().expect("every struct should have a field list");
544 let mut fields: Vec<_> = record_field_pat_list
545 .bind_pats()
546 .filter_map(|bind_pat| {
547 let ast_pat =
548 ast::Pat::cast(bind_pat.syntax().clone()).expect("bind pat is a pat");
549 let pat = self.collect_pat(ast_pat);
550 let name = bind_pat.name()?.as_name();
551 Some(RecordFieldPat { name, pat })
552 })
553 .collect();
554 let iter = record_field_pat_list.record_field_pats().filter_map(|f| {
555 let ast_pat = f.pat()?;
556 let pat = self.collect_pat(ast_pat);
557 let name = f.name()?.as_name();
558 Some(RecordFieldPat { name, pat })
559 });
560 fields.extend(iter);
561
562 Pat::Record { path, args: fields }
563 }
564
565 // FIXME: implement
566 ast::Pat::DotDotPat(_) => Pat::Missing,
567 ast::Pat::BoxPat(_) => Pat::Missing,
568 ast::Pat::LiteralPat(_) => Pat::Missing,
569 ast::Pat::SlicePat(_) | ast::Pat::RangePat(_) => Pat::Missing,
570 };
571 let ptr = AstPtr::new(&pat);
572 self.alloc_pat(pattern, Either::A(ptr))
573 }
574
575 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
576 if let Some(pat) = pat {
577 self.collect_pat(pat)
578 } else {
579 self.missing_pat()
580 }
581 }
582
583 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
584 let hygiene = Hygiene::new(self.db, self.current_file_id);
585 Path::from_src(path, &hygiene)
586 }
587}
588
589impl From<ast::BinOp> for BinaryOp {
590 fn from(ast_op: ast::BinOp) -> Self {
591 match ast_op {
592 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
593 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
594 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
595 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
596 ast::BinOp::LesserEqualTest => {
597 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
598 }
599 ast::BinOp::GreaterEqualTest => {
600 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
601 }
602 ast::BinOp::LesserTest => {
603 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
604 }
605 ast::BinOp::GreaterTest => {
606 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
607 }
608 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
609 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
610 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
611 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
612 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
613 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
614 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
615 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
616 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
617 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
618 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
619 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
620 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
621 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
622 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
623 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
624 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
625 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
626 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
627 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
628 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
629 }
630 }
631}
diff --git a/crates/ra_hir_def/src/builtin_type.rs b/crates/ra_hir_def/src/builtin_type.rs
index 2ec0c83fe..5e8157144 100644
--- a/crates/ra_hir_def/src/builtin_type.rs
+++ b/crates/ra_hir_def/src/builtin_type.rs
@@ -30,12 +30,23 @@ pub enum FloatBitness {
30} 30}
31 31
32#[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)]
33pub enum BuiltinType { 44pub enum BuiltinType {
34 Char, 45 Char,
35 Bool, 46 Bool,
36 Str, 47 Str,
37 Int { signedness: Signedness, bitness: IntBitness }, 48 Int(BuiltinInt),
38 Float { bitness: FloatBitness }, 49 Float(BuiltinFloat),
39} 50}
40 51
41impl BuiltinType { 52impl BuiltinType {
@@ -45,22 +56,22 @@ impl BuiltinType {
45 (name::BOOL, BuiltinType::Bool), 56 (name::BOOL, BuiltinType::Bool),
46 (name::STR, BuiltinType::Str ), 57 (name::STR, BuiltinType::Str ),
47 58
48 (name::ISIZE, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::Xsize }), 59 (name::ISIZE, BuiltinType::Int(BuiltinInt::ISIZE)),
49 (name::I8, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X8 }), 60 (name::I8, BuiltinType::Int(BuiltinInt::I8)),
50 (name::I16, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X16 }), 61 (name::I16, BuiltinType::Int(BuiltinInt::I16)),
51 (name::I32, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X32 }), 62 (name::I32, BuiltinType::Int(BuiltinInt::I32)),
52 (name::I64, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X64 }), 63 (name::I64, BuiltinType::Int(BuiltinInt::I64)),
53 (name::I128, BuiltinType::Int { signedness: Signedness::Signed, bitness: IntBitness::X128 }), 64 (name::I128, BuiltinType::Int(BuiltinInt::I128)),
54 65
55 (name::USIZE, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize }), 66 (name::USIZE, BuiltinType::Int(BuiltinInt::USIZE)),
56 (name::U8, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X8 }), 67 (name::U8, BuiltinType::Int(BuiltinInt::U8)),
57 (name::U16, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X16 }), 68 (name::U16, BuiltinType::Int(BuiltinInt::U16)),
58 (name::U32, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X32 }), 69 (name::U32, BuiltinType::Int(BuiltinInt::U32)),
59 (name::U64, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X64 }), 70 (name::U64, BuiltinType::Int(BuiltinInt::U64)),
60 (name::U128, BuiltinType::Int { signedness: Signedness::Unsigned, bitness: IntBitness::X128 }), 71 (name::U128, BuiltinType::Int(BuiltinInt::U128)),
61 72
62 (name::F32, BuiltinType::Float { bitness: FloatBitness::X32 }), 73 (name::F32, BuiltinType::Float(BuiltinFloat::F32)),
63 (name::F64, BuiltinType::Float { bitness: FloatBitness::X64 }), 74 (name::F64, BuiltinType::Float(BuiltinFloat::F64)),
64 ]; 75 ];
65} 76}
66 77
@@ -70,7 +81,7 @@ impl fmt::Display for BuiltinType {
70 BuiltinType::Char => "char", 81 BuiltinType::Char => "char",
71 BuiltinType::Bool => "bool", 82 BuiltinType::Bool => "bool",
72 BuiltinType::Str => "str", 83 BuiltinType::Str => "str",
73 BuiltinType::Int { signedness, bitness } => match (signedness, bitness) { 84 BuiltinType::Int(BuiltinInt { signedness, bitness }) => match (signedness, bitness) {
74 (Signedness::Signed, IntBitness::Xsize) => "isize", 85 (Signedness::Signed, IntBitness::Xsize) => "isize",
75 (Signedness::Signed, IntBitness::X8) => "i8", 86 (Signedness::Signed, IntBitness::X8) => "i8",
76 (Signedness::Signed, IntBitness::X16) => "i16", 87 (Signedness::Signed, IntBitness::X16) => "i16",
@@ -85,7 +96,7 @@ impl fmt::Display for BuiltinType {
85 (Signedness::Unsigned, IntBitness::X64) => "u64", 96 (Signedness::Unsigned, IntBitness::X64) => "u64",
86 (Signedness::Unsigned, IntBitness::X128) => "u128", 97 (Signedness::Unsigned, IntBitness::X128) => "u128",
87 }, 98 },
88 BuiltinType::Float { bitness } => match bitness { 99 BuiltinType::Float(BuiltinFloat { bitness }) => match bitness {
89 FloatBitness::X32 => "f32", 100 FloatBitness::X32 => "f32",
90 FloatBitness::X64 => "f64", 101 FloatBitness::X64 => "f64",
91 }, 102 },
@@ -93,3 +104,57 @@ impl fmt::Display for BuiltinType {
93 f.write_str(type_name) 104 f.write_str(type_name)
94 } 105 }
95} 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/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..4a758bb83 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;