1 //! Name resolution for expressions.
4 use hir_expand::name::Name;
5 use la_arena::{Arena, Idx};
6 use rustc_hash::FxHashMap;
11 expr::{Expr, ExprId, Pat, PatId, Statement},
12 BlockId, DefWithBodyId,
15 pub type ScopeId = Idx<ScopeData>;
17 #[derive(Debug, PartialEq, Eq)]
18 pub struct ExprScopes {
19 scopes: Arena<ScopeData>,
20 scope_by_expr: FxHashMap<ExprId, ScopeId>,
23 #[derive(Debug, PartialEq, Eq)]
24 pub struct ScopeEntry {
30 pub fn name(&self) -> &Name {
34 pub fn pat(&self) -> PatId {
39 #[derive(Debug, PartialEq, Eq)]
40 pub struct ScopeData {
41 parent: Option<ScopeId>,
42 block: Option<BlockId>,
43 entries: Vec<ScopeEntry>,
47 pub(crate) fn expr_scopes_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<ExprScopes> {
48 let body = db.body(def);
49 Arc::new(ExprScopes::new(&*body))
52 fn new(body: &Body) -> ExprScopes {
54 ExprScopes { scopes: Arena::default(), scope_by_expr: FxHashMap::default() };
55 let root = scopes.root_scope();
56 scopes.add_params_bindings(body, root, &body.params);
57 compute_expr_scopes(body.body_expr, body, &mut scopes, root);
61 pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
62 &self.scopes[scope].entries
65 /// If `scope` refers to a block expression scope, returns the corresponding `BlockId`.
66 pub fn block(&self, scope: ScopeId) -> Option<BlockId> {
67 self.scopes[scope].block
70 pub fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
71 std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
74 pub fn resolve_name_in_scope(&self, scope: ScopeId, name: &Name) -> Option<&ScopeEntry> {
75 self.scope_chain(Some(scope))
76 .find_map(|scope| self.entries(scope).iter().find(|it| it.name == *name))
79 pub fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
80 self.scope_by_expr.get(&expr).copied()
83 pub fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
87 fn root_scope(&mut self) -> ScopeId {
88 self.scopes.alloc(ScopeData { parent: None, block: None, entries: vec![] })
91 fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
92 self.scopes.alloc(ScopeData { parent: Some(parent), block: None, entries: vec![] })
95 fn new_block_scope(&mut self, parent: ScopeId, block: BlockId) -> ScopeId {
96 self.scopes.alloc(ScopeData { parent: Some(parent), block: Some(block), entries: vec![] })
99 fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
100 let pattern = &body[pat];
101 if let Pat::Bind { name, .. } = pattern {
102 let entry = ScopeEntry { name: name.clone(), pat };
103 self.scopes[scope].entries.push(entry);
106 pattern.walk_child_pats(|pat| self.add_bindings(body, scope, pat));
109 fn add_params_bindings(&mut self, body: &Body, scope: ScopeId, params: &[PatId]) {
110 params.iter().for_each(|pat| self.add_bindings(body, scope, *pat));
113 fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
114 self.scope_by_expr.insert(node, scope);
118 fn compute_block_scopes(
119 statements: &[Statement],
120 tail: Option<ExprId>,
122 scopes: &mut ExprScopes,
125 for stmt in statements {
127 Statement::Let { pat, initializer, .. } => {
128 if let Some(expr) = initializer {
129 scopes.set_scope(*expr, scope);
130 compute_expr_scopes(*expr, body, scopes, scope);
132 scope = scopes.new_scope(scope);
133 scopes.add_bindings(body, scope, *pat);
135 Statement::Expr(expr) => {
136 scopes.set_scope(*expr, scope);
137 compute_expr_scopes(*expr, body, scopes, scope);
141 if let Some(expr) = tail {
142 compute_expr_scopes(expr, body, scopes, scope);
146 fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
147 scopes.set_scope(expr, scope);
149 Expr::Block { statements, tail, id, .. } => {
150 let scope = scopes.new_block_scope(scope, *id);
151 // Overwrite the old scope for the block expr, so that every block scope can be found
152 // via the block itself (important for blocks that only contain items, no expressions).
153 scopes.set_scope(expr, scope);
154 compute_block_scopes(&statements, *tail, body, scopes, scope);
156 Expr::For { iterable, pat, body: body_expr, .. } => {
157 compute_expr_scopes(*iterable, body, scopes, scope);
158 let scope = scopes.new_scope(scope);
159 scopes.add_bindings(body, scope, *pat);
160 compute_expr_scopes(*body_expr, body, scopes, scope);
162 Expr::Lambda { args, body: body_expr, .. } => {
163 let scope = scopes.new_scope(scope);
164 scopes.add_params_bindings(body, scope, &args);
165 compute_expr_scopes(*body_expr, body, scopes, scope);
167 Expr::Match { expr, arms } => {
168 compute_expr_scopes(*expr, body, scopes, scope);
170 let scope = scopes.new_scope(scope);
171 scopes.add_bindings(body, scope, arm.pat);
172 if let Some(guard) = arm.guard {
173 scopes.set_scope(guard, scope);
174 compute_expr_scopes(guard, body, scopes, scope);
176 scopes.set_scope(arm.expr, scope);
177 compute_expr_scopes(arm.expr, body, scopes, scope);
180 e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
186 use base_db::{fixture::WithFixture, FileId, SourceDatabase};
187 use hir_expand::{name::AsName, InFile};
188 use syntax::{algo::find_node_at_offset, ast, AstNode};
189 use test_utils::{assert_eq_text, extract_offset, mark};
191 use crate::{db::DefDatabase, test_db::TestDB, FunctionId, ModuleDefId};
193 fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
194 let krate = db.test_crate();
195 let crate_def_map = db.crate_def_map(krate);
197 let module = crate_def_map.modules_for_file(file_id).next().unwrap();
198 let (_, def) = crate_def_map[module].scope.entries().next().unwrap();
199 match def.take_values().unwrap() {
200 ModuleDefId::FunctionId(it) => it,
205 fn do_check(ra_fixture: &str, expected: &[&str]) {
206 let (offset, code) = extract_offset(ra_fixture);
208 let mut buf = String::new();
209 let off: usize = offset.into();
210 buf.push_str(&code[..off]);
211 buf.push_str("$0marker");
212 buf.push_str(&code[off..]);
216 let (db, position) = TestDB::with_position(&code);
217 let file_id = position.file_id;
218 let offset = position.offset;
220 let file_syntax = db.parse(file_id).syntax_node();
221 let marker: ast::PathExpr = find_node_at_offset(&file_syntax, offset).unwrap();
222 let function = find_function(&db, file_id);
224 let scopes = db.expr_scopes(function.into());
225 let (_body, source_map) = db.body_with_source_map(function.into());
227 let expr_id = source_map
228 .node_expr(InFile { file_id: file_id.into(), value: &marker.into() })
230 let scope = scopes.scope_for(expr_id);
234 .flat_map(|scope| scopes.entries(scope))
235 .map(|it| it.name().to_string())
238 let expected = expected.join("\n");
239 assert_eq_text!(&expected, &actual);
243 fn test_lambda_scope() {
247 let f = |bar, baz: i32| {
251 &["bar", "baz", "foo"],
256 fn test_call_scope() {
267 fn test_method_call_scope() {
278 fn test_loop_scope() {
307 fn test_shadow_variable() {
318 fn test_bindings_after_at() {
323 opt @ Some(unit) => {
335 fn macro_inner_item() {
355 fn broken_inner_item() {
367 fn do_check_local_name(ra_fixture: &str, expected_offset: u32) {
368 let (db, position) = TestDB::with_position(ra_fixture);
369 let file_id = position.file_id;
370 let offset = position.offset;
372 let file = db.parse(file_id).ok().unwrap();
373 let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
374 .expect("failed to find a name at the target offset");
375 let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), offset).unwrap();
377 let function = find_function(&db, file_id);
379 let scopes = db.expr_scopes(function.into());
380 let (_body, source_map) = db.body_with_source_map(function.into());
383 let expr_ast = name_ref.syntax().ancestors().find_map(ast::Expr::cast).unwrap();
385 source_map.node_expr(InFile { file_id: file_id.into(), value: &expr_ast }).unwrap();
386 scopes.scope_for(expr_id).unwrap()
389 let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap();
390 let pat_src = source_map.pat_syntax(resolved.pat()).unwrap();
392 let local_name = pat_src.value.either(
393 |it| it.syntax_node_ptr().to_node(file.syntax()),
394 |it| it.syntax_node_ptr().to_node(file.syntax()),
396 assert_eq!(local_name.text_range(), expected_name.syntax().text_range());
400 fn test_resolve_local_name() {
403 fn foo(x: i32, y: u32) {
417 fn test_resolve_local_name_declaration() {
429 fn test_resolve_local_name_shadow() {
442 fn ref_patterns_contribute_bindings() {
446 if let Some(&from) = bar() {
456 fn while_let_desugaring() {
457 mark::check!(infer_resolve_while_let);
461 let foo: Option<f32> = None;
462 while let Option::Some(spam) = foo {