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, LabelId, MatchGuard, 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 label: Option<(LabelId, Name)>,
44 entries: Vec<ScopeEntry>,
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))
53 fn new(body: &Body) -> ExprScopes {
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);
62 pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
63 &self.scopes[scope].entries
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
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()
76 pub fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
77 std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
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))
85 pub fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
86 self.scope_by_expr.get(&expr).copied()
89 pub fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
93 fn root_scope(&mut self) -> ScopeId {
94 self.scopes.alloc(ScopeData { parent: None, block: None, label: None, entries: vec![] })
97 fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
98 self.scopes.alloc(ScopeData {
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![] })
114 label: Option<(LabelId, Name)>,
116 self.scopes.alloc(ScopeData {
117 parent: Some(parent),
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);
131 pattern.walk_child_pats(|pat| self.add_bindings(body, scope, pat));
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));
138 fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
139 self.scope_by_expr.insert(node, scope);
143 fn compute_block_scopes(
144 statements: &[Statement],
145 tail: Option<ExprId>,
147 scopes: &mut ExprScopes,
150 for stmt in statements {
152 Statement::Let { pat, initializer, else_branch, .. } => {
153 if let Some(expr) = initializer {
154 scopes.set_scope(*expr, scope);
155 compute_expr_scopes(*expr, body, scopes, scope);
157 if let Some(expr) = else_branch {
158 scopes.set_scope(*expr, scope);
159 compute_expr_scopes(*expr, body, scopes, scope);
161 scope = scopes.new_scope(scope);
162 scopes.add_bindings(body, scope, *pat);
164 Statement::Expr { expr, .. } => {
165 scopes.set_scope(*expr, scope);
166 compute_expr_scopes(*expr, body, scopes, scope);
170 if let Some(expr) = tail {
171 compute_expr_scopes(expr, body, scopes, scope);
175 fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
177 |label: &Option<_>| label.map(|label| (label, body.labels[label].name.clone()));
179 scopes.set_scope(expr, scope);
181 Expr::Block { statements, tail, id, label } => {
182 let scope = scopes.new_block_scope(scope, *id, make_label(label));
183 // Overwrite the old scope for the block expr, so that every block scope can be found
184 // via the block itself (important for blocks that only contain items, no expressions).
185 scopes.set_scope(expr, scope);
186 compute_block_scopes(statements, *tail, body, scopes, scope);
188 Expr::For { iterable, pat, body: body_expr, label } => {
189 compute_expr_scopes(*iterable, body, scopes, scope);
190 let scope = scopes.new_labeled_scope(scope, make_label(label));
191 scopes.add_bindings(body, scope, *pat);
192 compute_expr_scopes(*body_expr, body, scopes, scope);
194 Expr::While { condition, body: body_expr, label } => {
195 let scope = scopes.new_labeled_scope(scope, make_label(label));
196 compute_expr_scopes(*condition, body, scopes, scope);
197 compute_expr_scopes(*body_expr, body, scopes, scope);
199 Expr::Loop { body: body_expr, label } => {
200 let scope = scopes.new_labeled_scope(scope, make_label(label));
201 compute_expr_scopes(*body_expr, body, scopes, scope);
203 Expr::Lambda { args, body: body_expr, .. } => {
204 let scope = scopes.new_scope(scope);
205 scopes.add_params_bindings(body, scope, args);
206 compute_expr_scopes(*body_expr, body, scopes, scope);
208 Expr::Match { expr, arms } => {
209 compute_expr_scopes(*expr, body, scopes, scope);
211 let mut scope = scopes.new_scope(scope);
212 scopes.add_bindings(body, scope, arm.pat);
214 Some(MatchGuard::If { expr: guard }) => {
215 scopes.set_scope(guard, scope);
216 compute_expr_scopes(guard, body, scopes, scope);
218 Some(MatchGuard::IfLet { pat, expr: guard }) => {
219 scopes.set_scope(guard, scope);
220 compute_expr_scopes(guard, body, scopes, scope);
221 scope = scopes.new_scope(scope);
222 scopes.add_bindings(body, scope, pat);
226 scopes.set_scope(arm.expr, scope);
227 compute_expr_scopes(arm.expr, body, scopes, scope);
230 e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
236 use base_db::{fixture::WithFixture, FileId, SourceDatabase};
237 use hir_expand::{name::AsName, InFile};
238 use syntax::{algo::find_node_at_offset, ast, AstNode};
239 use test_utils::{assert_eq_text, extract_offset};
241 use crate::{db::DefDatabase, test_db::TestDB, FunctionId, ModuleDefId};
243 fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
244 let krate = db.test_crate();
245 let crate_def_map = db.crate_def_map(krate);
247 let module = crate_def_map.modules_for_file(file_id).next().unwrap();
248 let (_, def) = crate_def_map[module].scope.entries().next().unwrap();
249 match def.take_values().unwrap() {
250 ModuleDefId::FunctionId(it) => it,
255 fn do_check(ra_fixture: &str, expected: &[&str]) {
256 let (offset, code) = extract_offset(ra_fixture);
258 let mut buf = String::new();
259 let off: usize = offset.into();
260 buf.push_str(&code[..off]);
261 buf.push_str("$0marker");
262 buf.push_str(&code[off..]);
266 let (db, position) = TestDB::with_position(&code);
267 let file_id = position.file_id;
268 let offset = position.offset;
270 let file_syntax = db.parse(file_id).syntax_node();
271 let marker: ast::PathExpr = find_node_at_offset(&file_syntax, offset).unwrap();
272 let function = find_function(&db, file_id);
274 let scopes = db.expr_scopes(function.into());
275 let (_body, source_map) = db.body_with_source_map(function.into());
277 let expr_id = source_map
278 .node_expr(InFile { file_id: file_id.into(), value: &marker.into() })
280 let scope = scopes.scope_for(expr_id);
284 .flat_map(|scope| scopes.entries(scope))
285 .map(|it| it.name().to_string())
288 let expected = expected.join("\n");
289 assert_eq_text!(&expected, &actual);
293 fn test_lambda_scope() {
297 let f = |bar, baz: i32| {
301 &["bar", "baz", "foo"],
306 fn test_call_scope() {
317 fn test_method_call_scope() {
328 fn test_loop_scope() {
357 fn test_shadow_variable() {
368 fn test_bindings_after_at() {
373 opt @ Some(unit) => {
385 fn macro_inner_item() {
405 fn broken_inner_item() {
417 fn do_check_local_name(ra_fixture: &str, expected_offset: u32) {
418 let (db, position) = TestDB::with_position(ra_fixture);
419 let file_id = position.file_id;
420 let offset = position.offset;
422 let file = db.parse(file_id).ok().unwrap();
423 let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
424 .expect("failed to find a name at the target offset");
425 let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), offset).unwrap();
427 let function = find_function(&db, file_id);
429 let scopes = db.expr_scopes(function.into());
430 let (_body, source_map) = db.body_with_source_map(function.into());
433 let expr_ast = name_ref.syntax().ancestors().find_map(ast::Expr::cast).unwrap();
435 source_map.node_expr(InFile { file_id: file_id.into(), value: &expr_ast }).unwrap();
436 scopes.scope_for(expr_id).unwrap()
439 let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap();
440 let pat_src = source_map.pat_syntax(resolved.pat()).unwrap();
442 let local_name = pat_src.value.either(
443 |it| it.syntax_node_ptr().to_node(file.syntax()),
444 |it| it.syntax_node_ptr().to_node(file.syntax()),
446 assert_eq!(local_name.text_range(), expected_name.syntax().text_range());
450 fn test_resolve_local_name() {
453 fn foo(x: i32, y: u32) {
467 fn test_resolve_local_name_declaration() {
479 fn test_resolve_local_name_shadow() {
492 fn ref_patterns_contribute_bindings() {
496 if let Some(&from) = bar() {
506 fn while_let_desugaring() {
507 cov_mark::check!(infer_resolve_while_let);
511 let foo: Option<f32> = None;
512 while let Option::Some(spam) = foo {