]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body/scope.rs
Track labels in scopes
[rust.git] / crates / hir_def / src / body / scope.rs
1 //! Name resolution for expressions.
2 use std::sync::Arc;
3
4 use hir_expand::name::Name;
5 use la_arena::{Arena, Idx};
6 use rustc_hash::FxHashMap;
7
8 use crate::{
9     body::Body,
10     db::DefDatabase,
11     expr::{Expr, ExprId, LabelId, Pat, PatId, Statement},
12     BlockId, DefWithBodyId,
13 };
14
15 pub type ScopeId = Idx<ScopeData>;
16
17 #[derive(Debug, PartialEq, Eq)]
18 pub struct ExprScopes {
19     scopes: Arena<ScopeData>,
20     scope_by_expr: FxHashMap<ExprId, ScopeId>,
21 }
22
23 #[derive(Debug, PartialEq, Eq)]
24 pub struct ScopeEntry {
25     name: Name,
26     pat: PatId,
27 }
28
29 impl ScopeEntry {
30     pub fn name(&self) -> &Name {
31         &self.name
32     }
33
34     pub fn pat(&self) -> PatId {
35         self.pat
36     }
37 }
38
39 #[derive(Debug, PartialEq, Eq)]
40 pub struct ScopeData {
41     parent: Option<ScopeId>,
42     block: Option<BlockId>,
43     label: Option<(LabelId, Name)>,
44     entries: Vec<ScopeEntry>,
45 }
46
47 impl ExprScopes {
48     pub(crate) fn expr_scopes_query(db: &dyn DefDatabase, 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     /// If `scope` refers to a block expression scope, returns the corresponding `BlockId`.
67     pub fn block(&self, scope: ScopeId) -> Option<BlockId> {
68         self.scopes[scope].block
69     }
70
71     /// If `scope` refers to a labeled expression scope, returns the corresponding `Label`.
72     pub fn label(&self, scope: ScopeId) -> Option<(LabelId, Name)> {
73         self.scopes[scope].label.clone()
74     }
75
76     pub fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
77         std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
78     }
79
80     pub fn resolve_name_in_scope(&self, scope: ScopeId, name: &Name) -> Option<&ScopeEntry> {
81         self.scope_chain(Some(scope))
82             .find_map(|scope| self.entries(scope).iter().find(|it| it.name == *name))
83     }
84
85     pub fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
86         self.scope_by_expr.get(&expr).copied()
87     }
88
89     pub fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
90         &self.scope_by_expr
91     }
92
93     fn root_scope(&mut self) -> ScopeId {
94         self.scopes.alloc(ScopeData { parent: None, block: None, label: None, entries: vec![] })
95     }
96
97     fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
98         self.scopes.alloc(ScopeData {
99             parent: Some(parent),
100             block: None,
101             label: None,
102             entries: vec![],
103         })
104     }
105
106     fn new_labeled_scope(&mut self, parent: ScopeId, label: Option<(LabelId, Name)>) -> ScopeId {
107         self.scopes.alloc(ScopeData { parent: Some(parent), block: None, label, entries: vec![] })
108     }
109
110     fn new_block_scope(
111         &mut self,
112         parent: ScopeId,
113         block: BlockId,
114         label: Option<(LabelId, Name)>,
115     ) -> ScopeId {
116         self.scopes.alloc(ScopeData {
117             parent: Some(parent),
118             block: Some(block),
119             label,
120             entries: vec![],
121         })
122     }
123
124     fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
125         let pattern = &body[pat];
126         if let Pat::Bind { name, .. } = pattern {
127             let entry = ScopeEntry { name: name.clone(), pat };
128             self.scopes[scope].entries.push(entry);
129         }
130
131         pattern.walk_child_pats(|pat| self.add_bindings(body, scope, pat));
132     }
133
134     fn add_params_bindings(&mut self, body: &Body, scope: ScopeId, params: &[PatId]) {
135         params.iter().for_each(|pat| self.add_bindings(body, scope, *pat));
136     }
137
138     fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
139         self.scope_by_expr.insert(node, scope);
140     }
141 }
142
143 fn compute_block_scopes(
144     statements: &[Statement],
145     tail: Option<ExprId>,
146     body: &Body,
147     scopes: &mut ExprScopes,
148     mut scope: ScopeId,
149 ) {
150     for stmt in statements {
151         match stmt {
152             Statement::Let { pat, initializer, .. } => {
153                 if let Some(expr) = initializer {
154                     scopes.set_scope(*expr, scope);
155                     compute_expr_scopes(*expr, body, scopes, scope);
156                 }
157                 scope = scopes.new_scope(scope);
158                 scopes.add_bindings(body, scope, *pat);
159             }
160             Statement::Expr(expr) => {
161                 scopes.set_scope(*expr, scope);
162                 compute_expr_scopes(*expr, body, scopes, scope);
163             }
164         }
165     }
166     if let Some(expr) = tail {
167         compute_expr_scopes(expr, body, scopes, scope);
168     }
169 }
170
171 fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
172     let make_label =
173         |label: &Option<_>| label.map(|label| (label, body.labels[label].name.clone()));
174
175     scopes.set_scope(expr, scope);
176     match &body[expr] {
177         Expr::Block { statements, tail, id, label } => {
178             let scope = scopes.new_block_scope(scope, *id, make_label(label));
179             // Overwrite the old scope for the block expr, so that every block scope can be found
180             // via the block itself (important for blocks that only contain items, no expressions).
181             scopes.set_scope(expr, scope);
182             compute_block_scopes(statements, *tail, body, scopes, scope);
183         }
184         Expr::For { iterable, pat, body: body_expr, label } => {
185             compute_expr_scopes(*iterable, body, scopes, scope);
186             let scope = scopes.new_labeled_scope(scope, make_label(label));
187             scopes.add_bindings(body, scope, *pat);
188             compute_expr_scopes(*body_expr, body, scopes, scope);
189         }
190         Expr::While { condition, body: body_expr, label } => {
191             compute_expr_scopes(*condition, body, scopes, scope);
192             let scope = scopes.new_labeled_scope(scope, make_label(label));
193             compute_expr_scopes(*body_expr, body, scopes, scope);
194         }
195         Expr::Loop { body: body_expr, label } => {
196             let scope = scopes.new_labeled_scope(scope, make_label(label));
197             compute_expr_scopes(*body_expr, body, scopes, scope);
198         }
199         Expr::Lambda { args, body: body_expr, .. } => {
200             let scope = scopes.new_scope(scope);
201             scopes.add_params_bindings(body, scope, &args);
202             compute_expr_scopes(*body_expr, body, scopes, scope);
203         }
204         Expr::Match { expr, arms } => {
205             compute_expr_scopes(*expr, body, scopes, scope);
206             for arm in arms {
207                 let scope = scopes.new_scope(scope);
208                 scopes.add_bindings(body, scope, arm.pat);
209                 if let Some(guard) = arm.guard {
210                     scopes.set_scope(guard, scope);
211                     compute_expr_scopes(guard, body, scopes, scope);
212                 }
213                 scopes.set_scope(arm.expr, scope);
214                 compute_expr_scopes(arm.expr, body, scopes, scope);
215             }
216         }
217         e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
218     };
219 }
220
221 #[cfg(test)]
222 mod tests {
223     use base_db::{fixture::WithFixture, FileId, SourceDatabase};
224     use hir_expand::{name::AsName, InFile};
225     use syntax::{algo::find_node_at_offset, ast, AstNode};
226     use test_utils::{assert_eq_text, extract_offset};
227
228     use crate::{db::DefDatabase, test_db::TestDB, FunctionId, ModuleDefId};
229
230     fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
231         let krate = db.test_crate();
232         let crate_def_map = db.crate_def_map(krate);
233
234         let module = crate_def_map.modules_for_file(file_id).next().unwrap();
235         let (_, def) = crate_def_map[module].scope.entries().next().unwrap();
236         match def.take_values().unwrap() {
237             ModuleDefId::FunctionId(it) => it,
238             _ => panic!(),
239         }
240     }
241
242     fn do_check(ra_fixture: &str, expected: &[&str]) {
243         let (offset, code) = extract_offset(ra_fixture);
244         let code = {
245             let mut buf = String::new();
246             let off: usize = offset.into();
247             buf.push_str(&code[..off]);
248             buf.push_str("$0marker");
249             buf.push_str(&code[off..]);
250             buf
251         };
252
253         let (db, position) = TestDB::with_position(&code);
254         let file_id = position.file_id;
255         let offset = position.offset;
256
257         let file_syntax = db.parse(file_id).syntax_node();
258         let marker: ast::PathExpr = find_node_at_offset(&file_syntax, offset).unwrap();
259         let function = find_function(&db, file_id);
260
261         let scopes = db.expr_scopes(function.into());
262         let (_body, source_map) = db.body_with_source_map(function.into());
263
264         let expr_id = source_map
265             .node_expr(InFile { file_id: file_id.into(), value: &marker.into() })
266             .unwrap();
267         let scope = scopes.scope_for(expr_id);
268
269         let actual = scopes
270             .scope_chain(scope)
271             .flat_map(|scope| scopes.entries(scope))
272             .map(|it| it.name().to_string())
273             .collect::<Vec<_>>()
274             .join("\n");
275         let expected = expected.join("\n");
276         assert_eq_text!(&expected, &actual);
277     }
278
279     #[test]
280     fn test_lambda_scope() {
281         do_check(
282             r"
283             fn quux(foo: i32) {
284                 let f = |bar, baz: i32| {
285                     $0
286                 };
287             }",
288             &["bar", "baz", "foo"],
289         );
290     }
291
292     #[test]
293     fn test_call_scope() {
294         do_check(
295             r"
296             fn quux() {
297                 f(|x| $0 );
298             }",
299             &["x"],
300         );
301     }
302
303     #[test]
304     fn test_method_call_scope() {
305         do_check(
306             r"
307             fn quux() {
308                 z.f(|x| $0 );
309             }",
310             &["x"],
311         );
312     }
313
314     #[test]
315     fn test_loop_scope() {
316         do_check(
317             r"
318             fn quux() {
319                 loop {
320                     let x = ();
321                     $0
322                 };
323             }",
324             &["x"],
325         );
326     }
327
328     #[test]
329     fn test_match() {
330         do_check(
331             r"
332             fn quux() {
333                 match () {
334                     Some(x) => {
335                         $0
336                     }
337                 };
338             }",
339             &["x"],
340         );
341     }
342
343     #[test]
344     fn test_shadow_variable() {
345         do_check(
346             r"
347             fn foo(x: String) {
348                 let x : &str = &x$0;
349             }",
350             &["x"],
351         );
352     }
353
354     #[test]
355     fn test_bindings_after_at() {
356         do_check(
357             r"
358 fn foo() {
359     match Some(()) {
360         opt @ Some(unit) => {
361             $0
362         }
363         _ => {}
364     }
365 }
366 ",
367             &["opt", "unit"],
368         );
369     }
370
371     #[test]
372     fn macro_inner_item() {
373         do_check(
374             r"
375             macro_rules! mac {
376                 () => {{
377                     fn inner() {}
378                     inner();
379                 }};
380             }
381
382             fn foo() {
383                 mac!();
384                 $0
385             }
386         ",
387             &[],
388         );
389     }
390
391     #[test]
392     fn broken_inner_item() {
393         do_check(
394             r"
395             fn foo() {
396                 trait {}
397                 $0
398             }
399         ",
400             &[],
401         );
402     }
403
404     fn do_check_local_name(ra_fixture: &str, expected_offset: u32) {
405         let (db, position) = TestDB::with_position(ra_fixture);
406         let file_id = position.file_id;
407         let offset = position.offset;
408
409         let file = db.parse(file_id).ok().unwrap();
410         let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
411             .expect("failed to find a name at the target offset");
412         let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), offset).unwrap();
413
414         let function = find_function(&db, file_id);
415
416         let scopes = db.expr_scopes(function.into());
417         let (_body, source_map) = db.body_with_source_map(function.into());
418
419         let expr_scope = {
420             let expr_ast = name_ref.syntax().ancestors().find_map(ast::Expr::cast).unwrap();
421             let expr_id =
422                 source_map.node_expr(InFile { file_id: file_id.into(), value: &expr_ast }).unwrap();
423             scopes.scope_for(expr_id).unwrap()
424         };
425
426         let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap();
427         let pat_src = source_map.pat_syntax(resolved.pat()).unwrap();
428
429         let local_name = pat_src.value.either(
430             |it| it.syntax_node_ptr().to_node(file.syntax()),
431             |it| it.syntax_node_ptr().to_node(file.syntax()),
432         );
433         assert_eq!(local_name.text_range(), expected_name.syntax().text_range());
434     }
435
436     #[test]
437     fn test_resolve_local_name() {
438         do_check_local_name(
439             r#"
440 fn foo(x: i32, y: u32) {
441     {
442         let z = x * 2;
443     }
444     {
445         let t = x$0 * 3;
446     }
447 }
448 "#,
449             7,
450         );
451     }
452
453     #[test]
454     fn test_resolve_local_name_declaration() {
455         do_check_local_name(
456             r#"
457 fn foo(x: String) {
458     let x : &str = &x$0;
459 }
460 "#,
461             7,
462         );
463     }
464
465     #[test]
466     fn test_resolve_local_name_shadow() {
467         do_check_local_name(
468             r"
469 fn foo(x: String) {
470     let x : &str = &x;
471     x$0
472 }
473 ",
474             28,
475         );
476     }
477
478     #[test]
479     fn ref_patterns_contribute_bindings() {
480         do_check_local_name(
481             r"
482 fn foo() {
483     if let Some(&from) = bar() {
484         from$0;
485     }
486 }
487 ",
488             28,
489         );
490     }
491
492     #[test]
493     fn while_let_desugaring() {
494         cov_mark::check!(infer_resolve_while_let);
495         do_check_local_name(
496             r#"
497 fn test() {
498     let foo: Option<f32> = None;
499     while let Option::Some(spam) = foo {
500         spam$0
501     }
502 }
503 "#,
504             75,
505         );
506     }
507 }