aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/expr
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src/expr')
-rw-r--r--crates/ra_hir/src/expr/lower.rs647
-rw-r--r--crates/ra_hir/src/expr/scope.rs354
2 files changed, 0 insertions, 1001 deletions
diff --git a/crates/ra_hir/src/expr/lower.rs b/crates/ra_hir/src/expr/lower.rs
deleted file mode 100644
index 6463dd65e..000000000
--- a/crates/ra_hir/src/expr/lower.rs
+++ /dev/null
@@ -1,647 +0,0 @@
1//! FIXME: write short doc here
2
3use hir_def::{path::GenericArgs, type_ref::TypeRef};
4use hir_expand::{
5 hygiene::Hygiene,
6 name::{self, AsName, Name},
7};
8use ra_arena::Arena;
9use ra_syntax::{
10 ast::{
11 self, ArgListOwner, ArrayExprKind, LiteralKind, LoopBodyOwner, NameOwner,
12 TypeAscriptionOwner,
13 },
14 AstNode, AstPtr,
15};
16use test_utils::tested_by;
17
18use crate::{
19 db::HirDatabase,
20 ty::primitive::{FloatTy, IntTy, UncertainFloatTy, UncertainIntTy},
21 AstId, DefWithBody, Either, HirFileId, MacroCallLoc, MacroFileKind, Mutability, Path, Resolver,
22 Source,
23};
24
25use super::{
26 ArithOp, Array, BinaryOp, BindingAnnotation, Body, BodySourceMap, CmpOp, Expr, ExprId, Literal,
27 LogicOp, MatchArm, Ordering, Pat, PatId, PatPtr, RecordFieldPat, RecordLitField, Statement,
28};
29
30pub(super) fn lower(
31 db: &impl HirDatabase,
32 resolver: Resolver,
33 file_id: HirFileId,
34 owner: DefWithBody,
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 owner,
46 exprs: Arena::default(),
47 pats: Arena::default(),
48 params: Vec::new(),
49 body_expr: ExprId((!0).into()),
50 },
51 }
52 .collect(params, body)
53}
54
55struct ExprCollector<DB> {
56 db: DB,
57 resolver: Resolver,
58 // Expr collector expands macros along the way. original points to the file
59 // we started with, current points to the current macro expansion. source
60 // maps don't support macros yet, so we only record info into source map if
61 // current == original (see #1196)
62 original_file_id: HirFileId,
63 current_file_id: HirFileId,
64
65 body: Body,
66 source_map: BodySourceMap,
67}
68
69impl<'a, DB> ExprCollector<&'a DB>
70where
71 DB: HirDatabase,
72{
73 fn collect(
74 mut self,
75 param_list: Option<ast::ParamList>,
76 body: Option<ast::Expr>,
77 ) -> (Body, BodySourceMap) {
78 if let Some(param_list) = param_list {
79 if let Some(self_param) = param_list.self_param() {
80 let ptr = AstPtr::new(&self_param);
81 let param_pat = self.alloc_pat(
82 Pat::Bind {
83 name: name::SELF_PARAM,
84 mode: BindingAnnotation::Unannotated,
85 subpat: None,
86 },
87 Either::B(ptr),
88 );
89 self.body.params.push(param_pat);
90 }
91
92 for param in param_list.params() {
93 let pat = match param.pat() {
94 None => continue,
95 Some(pat) => pat,
96 };
97 let param_pat = self.collect_pat(pat);
98 self.body.params.push(param_pat);
99 }
100 };
101
102 self.body.body_expr = self.collect_expr_opt(body);
103 (self.body, self.source_map)
104 }
105
106 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
107 let ptr = Either::A(ptr);
108 let id = self.body.exprs.alloc(expr);
109 if self.current_file_id == self.original_file_id {
110 self.source_map.expr_map.insert(ptr, id);
111 }
112 self.source_map
113 .expr_map_back
114 .insert(id, Source { file_id: self.current_file_id, ast: ptr });
115 id
116 }
117 // desugared exprs don't have ptr, that's wrong and should be fixed
118 // somehow.
119 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
120 self.body.exprs.alloc(expr)
121 }
122 fn alloc_expr_field_shorthand(&mut self, expr: Expr, ptr: AstPtr<ast::RecordField>) -> ExprId {
123 let ptr = Either::B(ptr);
124 let id = self.body.exprs.alloc(expr);
125 if self.current_file_id == self.original_file_id {
126 self.source_map.expr_map.insert(ptr, id);
127 }
128 self.source_map
129 .expr_map_back
130 .insert(id, Source { file_id: self.current_file_id, ast: ptr });
131 id
132 }
133 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
134 let id = self.body.pats.alloc(pat);
135 if self.current_file_id == self.original_file_id {
136 self.source_map.pat_map.insert(ptr, id);
137 }
138 self.source_map.pat_map_back.insert(id, Source { file_id: self.current_file_id, ast: ptr });
139 id
140 }
141
142 fn empty_block(&mut self) -> ExprId {
143 let block = Expr::Block { statements: Vec::new(), tail: None };
144 self.body.exprs.alloc(block)
145 }
146
147 fn missing_expr(&mut self) -> ExprId {
148 self.body.exprs.alloc(Expr::Missing)
149 }
150
151 fn missing_pat(&mut self) -> PatId {
152 self.body.pats.alloc(Pat::Missing)
153 }
154
155 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
156 let syntax_ptr = AstPtr::new(&expr);
157 match expr {
158 ast::Expr::IfExpr(e) => {
159 let then_branch = self.collect_block_opt(e.then_branch());
160
161 let else_branch = e.else_branch().map(|b| match b {
162 ast::ElseBranch::Block(it) => self.collect_block(it),
163 ast::ElseBranch::IfExpr(elif) => {
164 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
165 self.collect_expr(expr)
166 }
167 });
168
169 let condition = match e.condition() {
170 None => self.missing_expr(),
171 Some(condition) => match condition.pat() {
172 None => self.collect_expr_opt(condition.expr()),
173 // if let -- desugar to match
174 Some(pat) => {
175 let pat = self.collect_pat(pat);
176 let match_expr = self.collect_expr_opt(condition.expr());
177 let placeholder_pat = self.missing_pat();
178 let arms = vec![
179 MatchArm { pats: vec![pat], expr: then_branch, guard: None },
180 MatchArm {
181 pats: vec![placeholder_pat],
182 expr: else_branch.unwrap_or_else(|| self.empty_block()),
183 guard: None,
184 },
185 ];
186 return self
187 .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr);
188 }
189 },
190 };
191
192 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
193 }
194 ast::Expr::TryBlockExpr(e) => {
195 let body = self.collect_block_opt(e.body());
196 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
197 }
198 ast::Expr::BlockExpr(e) => self.collect_block(e),
199 ast::Expr::LoopExpr(e) => {
200 let body = self.collect_block_opt(e.loop_body());
201 self.alloc_expr(Expr::Loop { body }, syntax_ptr)
202 }
203 ast::Expr::WhileExpr(e) => {
204 let body = self.collect_block_opt(e.loop_body());
205
206 let condition = match e.condition() {
207 None => self.missing_expr(),
208 Some(condition) => match condition.pat() {
209 None => self.collect_expr_opt(condition.expr()),
210 // if let -- desugar to match
211 Some(pat) => {
212 tested_by!(infer_while_let);
213 let pat = self.collect_pat(pat);
214 let match_expr = self.collect_expr_opt(condition.expr());
215 let placeholder_pat = self.missing_pat();
216 let break_ = self.alloc_expr_desugared(Expr::Break { expr: None });
217 let arms = vec![
218 MatchArm { pats: vec![pat], expr: body, guard: None },
219 MatchArm { pats: vec![placeholder_pat], expr: break_, guard: None },
220 ];
221 let match_expr =
222 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
223 return self.alloc_expr(Expr::Loop { body: match_expr }, syntax_ptr);
224 }
225 },
226 };
227
228 self.alloc_expr(Expr::While { condition, body }, syntax_ptr)
229 }
230 ast::Expr::ForExpr(e) => {
231 let iterable = self.collect_expr_opt(e.iterable());
232 let pat = self.collect_pat_opt(e.pat());
233 let body = self.collect_block_opt(e.loop_body());
234 self.alloc_expr(Expr::For { iterable, pat, body }, syntax_ptr)
235 }
236 ast::Expr::CallExpr(e) => {
237 let callee = self.collect_expr_opt(e.expr());
238 let args = if let Some(arg_list) = e.arg_list() {
239 arg_list.args().map(|e| self.collect_expr(e)).collect()
240 } else {
241 Vec::new()
242 };
243 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
244 }
245 ast::Expr::MethodCallExpr(e) => {
246 let receiver = self.collect_expr_opt(e.expr());
247 let args = if let Some(arg_list) = e.arg_list() {
248 arg_list.args().map(|e| self.collect_expr(e)).collect()
249 } else {
250 Vec::new()
251 };
252 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
253 let generic_args = e.type_arg_list().and_then(GenericArgs::from_ast);
254 self.alloc_expr(
255 Expr::MethodCall { receiver, method_name, args, generic_args },
256 syntax_ptr,
257 )
258 }
259 ast::Expr::MatchExpr(e) => {
260 let expr = self.collect_expr_opt(e.expr());
261 let arms = if let Some(match_arm_list) = e.match_arm_list() {
262 match_arm_list
263 .arms()
264 .map(|arm| MatchArm {
265 pats: arm.pats().map(|p| self.collect_pat(p)).collect(),
266 expr: self.collect_expr_opt(arm.expr()),
267 guard: arm
268 .guard()
269 .and_then(|guard| guard.expr())
270 .map(|e| self.collect_expr(e)),
271 })
272 .collect()
273 } else {
274 Vec::new()
275 };
276 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
277 }
278 ast::Expr::PathExpr(e) => {
279 let path = e
280 .path()
281 .and_then(|path| self.parse_path(path))
282 .map(Expr::Path)
283 .unwrap_or(Expr::Missing);
284 self.alloc_expr(path, syntax_ptr)
285 }
286 ast::Expr::ContinueExpr(_e) => {
287 // FIXME: labels
288 self.alloc_expr(Expr::Continue, syntax_ptr)
289 }
290 ast::Expr::BreakExpr(e) => {
291 let expr = e.expr().map(|e| self.collect_expr(e));
292 self.alloc_expr(Expr::Break { expr }, syntax_ptr)
293 }
294 ast::Expr::ParenExpr(e) => {
295 let inner = self.collect_expr_opt(e.expr());
296 // make the paren expr point to the inner expression as well
297 self.source_map.expr_map.insert(Either::A(syntax_ptr), inner);
298 inner
299 }
300 ast::Expr::ReturnExpr(e) => {
301 let expr = e.expr().map(|e| self.collect_expr(e));
302 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
303 }
304 ast::Expr::RecordLit(e) => {
305 let path = e.path().and_then(|path| self.parse_path(path));
306 let mut field_ptrs = Vec::new();
307 let record_lit = if let Some(nfl) = e.record_field_list() {
308 let fields = nfl
309 .fields()
310 .inspect(|field| field_ptrs.push(AstPtr::new(field)))
311 .map(|field| RecordLitField {
312 name: field
313 .name_ref()
314 .map(|nr| nr.as_name())
315 .unwrap_or_else(Name::missing),
316 expr: if let Some(e) = field.expr() {
317 self.collect_expr(e)
318 } else if let Some(nr) = field.name_ref() {
319 // field shorthand
320 self.alloc_expr_field_shorthand(
321 Expr::Path(Path::from_name_ref(&nr)),
322 AstPtr::new(&field),
323 )
324 } else {
325 self.missing_expr()
326 },
327 })
328 .collect();
329 let spread = nfl.spread().map(|s| self.collect_expr(s));
330 Expr::RecordLit { path, fields, spread }
331 } else {
332 Expr::RecordLit { path, fields: Vec::new(), spread: None }
333 };
334
335 let res = self.alloc_expr(record_lit, syntax_ptr);
336 for (i, ptr) in field_ptrs.into_iter().enumerate() {
337 self.source_map.field_map.insert((res, i), ptr);
338 }
339 res
340 }
341 ast::Expr::FieldExpr(e) => {
342 let expr = self.collect_expr_opt(e.expr());
343 let name = match e.field_access() {
344 Some(kind) => kind.as_name(),
345 _ => Name::missing(),
346 };
347 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
348 }
349 ast::Expr::AwaitExpr(e) => {
350 let expr = self.collect_expr_opt(e.expr());
351 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
352 }
353 ast::Expr::TryExpr(e) => {
354 let expr = self.collect_expr_opt(e.expr());
355 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
356 }
357 ast::Expr::CastExpr(e) => {
358 let expr = self.collect_expr_opt(e.expr());
359 let type_ref = TypeRef::from_ast_opt(e.type_ref());
360 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
361 }
362 ast::Expr::RefExpr(e) => {
363 let expr = self.collect_expr_opt(e.expr());
364 let mutability = Mutability::from_mutable(e.is_mut());
365 self.alloc_expr(Expr::Ref { expr, mutability }, syntax_ptr)
366 }
367 ast::Expr::PrefixExpr(e) => {
368 let expr = self.collect_expr_opt(e.expr());
369 if let Some(op) = e.op_kind() {
370 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
371 } else {
372 self.alloc_expr(Expr::Missing, syntax_ptr)
373 }
374 }
375 ast::Expr::LambdaExpr(e) => {
376 let mut args = Vec::new();
377 let mut arg_types = Vec::new();
378 if let Some(pl) = e.param_list() {
379 for param in pl.params() {
380 let pat = self.collect_pat_opt(param.pat());
381 let type_ref = param.ascribed_type().map(TypeRef::from_ast);
382 args.push(pat);
383 arg_types.push(type_ref);
384 }
385 }
386 let body = self.collect_expr_opt(e.body());
387 self.alloc_expr(Expr::Lambda { args, arg_types, body }, syntax_ptr)
388 }
389 ast::Expr::BinExpr(e) => {
390 let lhs = self.collect_expr_opt(e.lhs());
391 let rhs = self.collect_expr_opt(e.rhs());
392 let op = e.op_kind().map(BinaryOp::from);
393 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
394 }
395 ast::Expr::TupleExpr(e) => {
396 let exprs = e.exprs().map(|expr| self.collect_expr(expr)).collect();
397 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
398 }
399 ast::Expr::BoxExpr(e) => {
400 let expr = self.collect_expr_opt(e.expr());
401 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
402 }
403
404 ast::Expr::ArrayExpr(e) => {
405 let kind = e.kind();
406
407 match kind {
408 ArrayExprKind::ElementList(e) => {
409 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
410 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
411 }
412 ArrayExprKind::Repeat { initializer, repeat } => {
413 let initializer = self.collect_expr_opt(initializer);
414 let repeat = self.collect_expr_opt(repeat);
415 self.alloc_expr(
416 Expr::Array(Array::Repeat { initializer, repeat }),
417 syntax_ptr,
418 )
419 }
420 }
421 }
422
423 ast::Expr::Literal(e) => {
424 let lit = match e.kind() {
425 LiteralKind::IntNumber { suffix } => {
426 let known_name = suffix
427 .and_then(|it| IntTy::from_suffix(&it).map(UncertainIntTy::Known));
428
429 Literal::Int(
430 Default::default(),
431 known_name.unwrap_or(UncertainIntTy::Unknown),
432 )
433 }
434 LiteralKind::FloatNumber { suffix } => {
435 let known_name = suffix
436 .and_then(|it| FloatTy::from_suffix(&it).map(UncertainFloatTy::Known));
437
438 Literal::Float(
439 Default::default(),
440 known_name.unwrap_or(UncertainFloatTy::Unknown),
441 )
442 }
443 LiteralKind::ByteString => Literal::ByteString(Default::default()),
444 LiteralKind::String => Literal::String(Default::default()),
445 LiteralKind::Byte => {
446 Literal::Int(Default::default(), UncertainIntTy::Known(IntTy::u8()))
447 }
448 LiteralKind::Bool => Literal::Bool(Default::default()),
449 LiteralKind::Char => Literal::Char(Default::default()),
450 };
451 self.alloc_expr(Expr::Literal(lit), syntax_ptr)
452 }
453 ast::Expr::IndexExpr(e) => {
454 let base = self.collect_expr_opt(e.base());
455 let index = self.collect_expr_opt(e.index());
456 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
457 }
458
459 // FIXME implement HIR for these:
460 ast::Expr::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
461 ast::Expr::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
462 ast::Expr::MacroCall(e) => {
463 let ast_id = AstId::new(
464 self.current_file_id,
465 self.db.ast_id_map(self.current_file_id).ast_id(&e),
466 );
467
468 if let Some(path) = e.path().and_then(|path| self.parse_path(path)) {
469 if let Some(def) = self.resolver.resolve_path_as_macro(self.db, &path) {
470 let call_id = self.db.intern_macro(MacroCallLoc { def: def.id, ast_id });
471 let file_id = call_id.as_file(MacroFileKind::Expr);
472 if let Some(node) = self.db.parse_or_expand(file_id) {
473 if let Some(expr) = ast::Expr::cast(node) {
474 log::debug!("macro expansion {:#?}", expr.syntax());
475 let old_file_id =
476 std::mem::replace(&mut self.current_file_id, file_id);
477 let id = self.collect_expr(expr);
478 self.current_file_id = old_file_id;
479 return id;
480 }
481 }
482 }
483 }
484 // FIXME: Instead of just dropping the error from expansion
485 // report it
486 self.alloc_expr(Expr::Missing, syntax_ptr)
487 }
488 }
489 }
490
491 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
492 if let Some(expr) = expr {
493 self.collect_expr(expr)
494 } else {
495 self.missing_expr()
496 }
497 }
498
499 fn collect_block(&mut self, expr: ast::BlockExpr) -> ExprId {
500 let syntax_node_ptr = AstPtr::new(&expr.clone().into());
501 let block = match expr.block() {
502 Some(block) => block,
503 None => return self.alloc_expr(Expr::Missing, syntax_node_ptr),
504 };
505 let statements = block
506 .statements()
507 .map(|s| match s {
508 ast::Stmt::LetStmt(stmt) => {
509 let pat = self.collect_pat_opt(stmt.pat());
510 let type_ref = stmt.ascribed_type().map(TypeRef::from_ast);
511 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
512 Statement::Let { pat, type_ref, initializer }
513 }
514 ast::Stmt::ExprStmt(stmt) => Statement::Expr(self.collect_expr_opt(stmt.expr())),
515 })
516 .collect();
517 let tail = block.expr().map(|e| self.collect_expr(e));
518 self.alloc_expr(Expr::Block { statements, tail }, syntax_node_ptr)
519 }
520
521 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
522 if let Some(block) = expr {
523 self.collect_block(block)
524 } else {
525 self.missing_expr()
526 }
527 }
528
529 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
530 let pattern = match &pat {
531 ast::Pat::BindPat(bp) => {
532 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
533 let annotation = BindingAnnotation::new(bp.is_mutable(), bp.is_ref());
534 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
535 Pat::Bind { name, mode: annotation, subpat }
536 }
537 ast::Pat::TupleStructPat(p) => {
538 let path = p.path().and_then(|path| self.parse_path(path));
539 let args = p.args().map(|p| self.collect_pat(p)).collect();
540 Pat::TupleStruct { path, args }
541 }
542 ast::Pat::RefPat(p) => {
543 let pat = self.collect_pat_opt(p.pat());
544 let mutability = Mutability::from_mutable(p.is_mut());
545 Pat::Ref { pat, mutability }
546 }
547 ast::Pat::PathPat(p) => {
548 let path = p.path().and_then(|path| self.parse_path(path));
549 path.map(Pat::Path).unwrap_or(Pat::Missing)
550 }
551 ast::Pat::TuplePat(p) => {
552 let args = p.args().map(|p| self.collect_pat(p)).collect();
553 Pat::Tuple(args)
554 }
555 ast::Pat::PlaceholderPat(_) => Pat::Wild,
556 ast::Pat::RecordPat(p) => {
557 let path = p.path().and_then(|path| self.parse_path(path));
558 let record_field_pat_list =
559 p.record_field_pat_list().expect("every struct should have a field list");
560 let mut fields: Vec<_> = record_field_pat_list
561 .bind_pats()
562 .filter_map(|bind_pat| {
563 let ast_pat =
564 ast::Pat::cast(bind_pat.syntax().clone()).expect("bind pat is a pat");
565 let pat = self.collect_pat(ast_pat);
566 let name = bind_pat.name()?.as_name();
567 Some(RecordFieldPat { name, pat })
568 })
569 .collect();
570 let iter = record_field_pat_list.record_field_pats().filter_map(|f| {
571 let ast_pat = f.pat()?;
572 let pat = self.collect_pat(ast_pat);
573 let name = f.name()?.as_name();
574 Some(RecordFieldPat { name, pat })
575 });
576 fields.extend(iter);
577
578 Pat::Record { path, args: fields }
579 }
580
581 // FIXME: implement
582 ast::Pat::DotDotPat(_) => Pat::Missing,
583 ast::Pat::BoxPat(_) => Pat::Missing,
584 ast::Pat::LiteralPat(_) => Pat::Missing,
585 ast::Pat::SlicePat(_) | ast::Pat::RangePat(_) => Pat::Missing,
586 };
587 let ptr = AstPtr::new(&pat);
588 self.alloc_pat(pattern, Either::A(ptr))
589 }
590
591 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
592 if let Some(pat) = pat {
593 self.collect_pat(pat)
594 } else {
595 self.missing_pat()
596 }
597 }
598
599 fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
600 let hygiene = Hygiene::new(self.db, self.current_file_id);
601 Path::from_src(path, &hygiene)
602 }
603}
604
605impl From<ast::BinOp> for BinaryOp {
606 fn from(ast_op: ast::BinOp) -> Self {
607 match ast_op {
608 ast::BinOp::BooleanOr => BinaryOp::LogicOp(LogicOp::Or),
609 ast::BinOp::BooleanAnd => BinaryOp::LogicOp(LogicOp::And),
610 ast::BinOp::EqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: false }),
611 ast::BinOp::NegatedEqualityTest => BinaryOp::CmpOp(CmpOp::Eq { negated: true }),
612 ast::BinOp::LesserEqualTest => {
613 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: false })
614 }
615 ast::BinOp::GreaterEqualTest => {
616 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: false })
617 }
618 ast::BinOp::LesserTest => {
619 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Less, strict: true })
620 }
621 ast::BinOp::GreaterTest => {
622 BinaryOp::CmpOp(CmpOp::Ord { ordering: Ordering::Greater, strict: true })
623 }
624 ast::BinOp::Addition => BinaryOp::ArithOp(ArithOp::Add),
625 ast::BinOp::Multiplication => BinaryOp::ArithOp(ArithOp::Mul),
626 ast::BinOp::Subtraction => BinaryOp::ArithOp(ArithOp::Sub),
627 ast::BinOp::Division => BinaryOp::ArithOp(ArithOp::Div),
628 ast::BinOp::Remainder => BinaryOp::ArithOp(ArithOp::Rem),
629 ast::BinOp::LeftShift => BinaryOp::ArithOp(ArithOp::Shl),
630 ast::BinOp::RightShift => BinaryOp::ArithOp(ArithOp::Shr),
631 ast::BinOp::BitwiseXor => BinaryOp::ArithOp(ArithOp::BitXor),
632 ast::BinOp::BitwiseOr => BinaryOp::ArithOp(ArithOp::BitOr),
633 ast::BinOp::BitwiseAnd => BinaryOp::ArithOp(ArithOp::BitAnd),
634 ast::BinOp::Assignment => BinaryOp::Assignment { op: None },
635 ast::BinOp::AddAssign => BinaryOp::Assignment { op: Some(ArithOp::Add) },
636 ast::BinOp::DivAssign => BinaryOp::Assignment { op: Some(ArithOp::Div) },
637 ast::BinOp::MulAssign => BinaryOp::Assignment { op: Some(ArithOp::Mul) },
638 ast::BinOp::RemAssign => BinaryOp::Assignment { op: Some(ArithOp::Rem) },
639 ast::BinOp::ShlAssign => BinaryOp::Assignment { op: Some(ArithOp::Shl) },
640 ast::BinOp::ShrAssign => BinaryOp::Assignment { op: Some(ArithOp::Shr) },
641 ast::BinOp::SubAssign => BinaryOp::Assignment { op: Some(ArithOp::Sub) },
642 ast::BinOp::BitOrAssign => BinaryOp::Assignment { op: Some(ArithOp::BitOr) },
643 ast::BinOp::BitAndAssign => BinaryOp::Assignment { op: Some(ArithOp::BitAnd) },
644 ast::BinOp::BitXorAssign => BinaryOp::Assignment { op: Some(ArithOp::BitXor) },
645 }
646 }
647}
diff --git a/crates/ra_hir/src/expr/scope.rs b/crates/ra_hir/src/expr/scope.rs
deleted file mode 100644
index 5a1eade2c..000000000
--- a/crates/ra_hir/src/expr/scope.rs
+++ /dev/null
@@ -1,354 +0,0 @@
1//! FIXME: write short doc here
2
3use std::sync::Arc;
4
5use ra_arena::{impl_arena_id, Arena, RawId};
6use rustc_hash::FxHashMap;
7
8use crate::{
9 db::HirDatabase,
10 expr::{Body, Expr, ExprId, Pat, PatId, Statement},
11 DefWithBody, Name,
12};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct ScopeId(RawId);
16impl_arena_id!(ScopeId);
17
18#[derive(Debug, PartialEq, Eq)]
19pub struct ExprScopes {
20 body: Arc<Body>,
21 scopes: Arena<ScopeId, ScopeData>,
22 scope_by_expr: FxHashMap<ExprId, ScopeId>,
23}
24
25#[derive(Debug, PartialEq, Eq)]
26pub(crate) struct ScopeEntry {
27 name: Name,
28 pat: PatId,
29}
30
31impl ScopeEntry {
32 pub(crate) fn name(&self) -> &Name {
33 &self.name
34 }
35
36 pub(crate) fn pat(&self) -> PatId {
37 self.pat
38 }
39}
40
41#[derive(Debug, PartialEq, Eq)]
42pub(crate) struct ScopeData {
43 parent: Option<ScopeId>,
44 entries: Vec<ScopeEntry>,
45}
46
47impl ExprScopes {
48 pub(crate) fn expr_scopes_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<ExprScopes> {
49 let body = db.body_hir(def);
50 let res = ExprScopes::new(body);
51 Arc::new(res)
52 }
53
54 fn new(body: Arc<Body>) -> ExprScopes {
55 let mut scopes = ExprScopes {
56 body: body.clone(),
57 scopes: Arena::default(),
58 scope_by_expr: FxHashMap::default(),
59 };
60 let root = scopes.root_scope();
61 scopes.add_params_bindings(root, body.params());
62 compute_expr_scopes(body.body_expr(), &body, &mut scopes, root);
63 scopes
64 }
65
66 pub(crate) fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
67 &self.scopes[scope].entries
68 }
69
70 pub(crate) fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
71 std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
72 }
73
74 pub(crate) fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
75 self.scope_by_expr.get(&expr).copied()
76 }
77
78 pub(crate) fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
79 &self.scope_by_expr
80 }
81
82 fn root_scope(&mut self) -> ScopeId {
83 self.scopes.alloc(ScopeData { parent: None, entries: vec![] })
84 }
85
86 fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
87 self.scopes.alloc(ScopeData { parent: Some(parent), entries: vec![] })
88 }
89
90 fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
91 match &body[pat] {
92 Pat::Bind { name, .. } => {
93 // bind can have a sub pattern, but it's actually not allowed
94 // to bind to things in there
95 let entry = ScopeEntry { name: name.clone(), pat };
96 self.scopes[scope].entries.push(entry)
97 }
98 p => p.walk_child_pats(|pat| self.add_bindings(body, scope, pat)),
99 }
100 }
101
102 fn add_params_bindings(&mut self, scope: ScopeId, params: &[PatId]) {
103 let body = Arc::clone(&self.body);
104 params.iter().for_each(|pat| self.add_bindings(&body, scope, *pat));
105 }
106
107 fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
108 self.scope_by_expr.insert(node, scope);
109 }
110}
111
112fn compute_block_scopes(
113 statements: &[Statement],
114 tail: Option<ExprId>,
115 body: &Body,
116 scopes: &mut ExprScopes,
117 mut scope: ScopeId,
118) {
119 for stmt in statements {
120 match stmt {
121 Statement::Let { pat, initializer, .. } => {
122 if let Some(expr) = initializer {
123 scopes.set_scope(*expr, scope);
124 compute_expr_scopes(*expr, body, scopes, scope);
125 }
126 scope = scopes.new_scope(scope);
127 scopes.add_bindings(body, scope, *pat);
128 }
129 Statement::Expr(expr) => {
130 scopes.set_scope(*expr, scope);
131 compute_expr_scopes(*expr, body, scopes, scope);
132 }
133 }
134 }
135 if let Some(expr) = tail {
136 compute_expr_scopes(expr, body, scopes, scope);
137 }
138}
139
140fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
141 scopes.set_scope(expr, scope);
142 match &body[expr] {
143 Expr::Block { statements, tail } => {
144 compute_block_scopes(&statements, *tail, body, scopes, scope);
145 }
146 Expr::For { iterable, pat, body: body_expr } => {
147 compute_expr_scopes(*iterable, body, scopes, scope);
148 let scope = scopes.new_scope(scope);
149 scopes.add_bindings(body, scope, *pat);
150 compute_expr_scopes(*body_expr, body, scopes, scope);
151 }
152 Expr::Lambda { args, body: body_expr, .. } => {
153 let scope = scopes.new_scope(scope);
154 scopes.add_params_bindings(scope, &args);
155 compute_expr_scopes(*body_expr, body, scopes, scope);
156 }
157 Expr::Match { expr, arms } => {
158 compute_expr_scopes(*expr, body, scopes, scope);
159 for arm in arms {
160 let scope = scopes.new_scope(scope);
161 for pat in &arm.pats {
162 scopes.add_bindings(body, scope, *pat);
163 }
164 scopes.set_scope(arm.expr, scope);
165 compute_expr_scopes(arm.expr, body, scopes, scope);
166 }
167 }
168 e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
169 };
170}
171
172#[cfg(test)]
173mod tests {
174 use ra_db::{fixture::WithFixture, SourceDatabase};
175 use ra_syntax::{algo::find_node_at_offset, ast, AstNode};
176 use test_utils::{assert_eq_text, extract_offset};
177
178 use crate::{source_binder::SourceAnalyzer, test_db::TestDB};
179
180 fn do_check(code: &str, expected: &[&str]) {
181 let (off, code) = extract_offset(code);
182 let code = {
183 let mut buf = String::new();
184 let off = u32::from(off) as usize;
185 buf.push_str(&code[..off]);
186 buf.push_str("marker");
187 buf.push_str(&code[off..]);
188 buf
189 };
190
191 let (db, file_id) = TestDB::with_single_file(&code);
192 let file = db.parse(file_id).ok().unwrap();
193 let marker: ast::PathExpr = find_node_at_offset(file.syntax(), off).unwrap();
194 let analyzer = SourceAnalyzer::new(&db, file_id, marker.syntax(), None);
195
196 let scopes = analyzer.scopes();
197 let expr_id = analyzer.body_source_map().node_expr(&marker.into()).unwrap();
198 let scope = scopes.scope_for(expr_id);
199
200 let actual = scopes
201 .scope_chain(scope)
202 .flat_map(|scope| scopes.entries(scope))
203 .map(|it| it.name().to_string())
204 .collect::<Vec<_>>()
205 .join("\n");
206 let expected = expected.join("\n");
207 assert_eq_text!(&expected, &actual);
208 }
209
210 #[test]
211 fn test_lambda_scope() {
212 do_check(
213 r"
214 fn quux(foo: i32) {
215 let f = |bar, baz: i32| {
216 <|>
217 };
218 }",
219 &["bar", "baz", "foo"],
220 );
221 }
222
223 #[test]
224 fn test_call_scope() {
225 do_check(
226 r"
227 fn quux() {
228 f(|x| <|> );
229 }",
230 &["x"],
231 );
232 }
233
234 #[test]
235 fn test_method_call_scope() {
236 do_check(
237 r"
238 fn quux() {
239 z.f(|x| <|> );
240 }",
241 &["x"],
242 );
243 }
244
245 #[test]
246 fn test_loop_scope() {
247 do_check(
248 r"
249 fn quux() {
250 loop {
251 let x = ();
252 <|>
253 };
254 }",
255 &["x"],
256 );
257 }
258
259 #[test]
260 fn test_match() {
261 do_check(
262 r"
263 fn quux() {
264 match () {
265 Some(x) => {
266 <|>
267 }
268 };
269 }",
270 &["x"],
271 );
272 }
273
274 #[test]
275 fn test_shadow_variable() {
276 do_check(
277 r"
278 fn foo(x: String) {
279 let x : &str = &x<|>;
280 }",
281 &["x"],
282 );
283 }
284
285 fn do_check_local_name(code: &str, expected_offset: u32) {
286 let (off, code) = extract_offset(code);
287
288 let (db, file_id) = TestDB::with_single_file(&code);
289 let file = db.parse(file_id).ok().unwrap();
290 let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
291 .expect("failed to find a name at the target offset");
292 let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap();
293 let analyzer = SourceAnalyzer::new(&db, file_id, name_ref.syntax(), None);
294
295 let local_name_entry = analyzer.resolve_local_name(&name_ref).unwrap();
296 let local_name =
297 local_name_entry.ptr().either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
298 assert_eq!(local_name.range(), expected_name.syntax().text_range());
299 }
300
301 #[test]
302 fn test_resolve_local_name() {
303 do_check_local_name(
304 r#"
305 fn foo(x: i32, y: u32) {
306 {
307 let z = x * 2;
308 }
309 {
310 let t = x<|> * 3;
311 }
312 }"#,
313 21,
314 );
315 }
316
317 #[test]
318 fn test_resolve_local_name_declaration() {
319 do_check_local_name(
320 r#"
321 fn foo(x: String) {
322 let x : &str = &x<|>;
323 }"#,
324 21,
325 );
326 }
327
328 #[test]
329 fn test_resolve_local_name_shadow() {
330 do_check_local_name(
331 r"
332 fn foo(x: String) {
333 let x : &str = &x;
334 x<|>
335 }
336 ",
337 53,
338 );
339 }
340
341 #[test]
342 fn ref_patterns_contribute_bindings() {
343 do_check_local_name(
344 r"
345 fn foo() {
346 if let Some(&from) = bar() {
347 from<|>;
348 }
349 }
350 ",
351 53,
352 );
353 }
354}