1 //! Name resolution for expressions.
4 use arena::{Arena, Idx};
5 use hir_expand::name::Name;
6 use rustc_hash::FxHashMap;
11 expr::{Expr, ExprId, Pat, PatId, Statement},
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 entries: Vec<ScopeEntry>,
46 pub(crate) fn expr_scopes_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<ExprScopes> {
47 let body = db.body(def);
48 Arc::new(ExprScopes::new(&*body))
51 fn new(body: &Body) -> ExprScopes {
53 ExprScopes { scopes: Arena::default(), scope_by_expr: FxHashMap::default() };
54 let root = scopes.root_scope();
55 scopes.add_params_bindings(body, root, &body.params);
56 compute_expr_scopes(body.body_expr, body, &mut scopes, root);
60 pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
61 &self.scopes[scope].entries
64 pub fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
65 std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
68 pub fn resolve_name_in_scope(&self, scope: ScopeId, name: &Name) -> Option<&ScopeEntry> {
69 self.scope_chain(Some(scope))
70 .find_map(|scope| self.entries(scope).iter().find(|it| it.name == *name))
73 pub fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
74 self.scope_by_expr.get(&expr).copied()
77 pub fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
81 fn root_scope(&mut self) -> ScopeId {
82 self.scopes.alloc(ScopeData { parent: None, entries: vec![] })
85 fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
86 self.scopes.alloc(ScopeData { parent: Some(parent), entries: vec![] })
89 fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
90 let pattern = &body[pat];
91 if let Pat::Bind { name, .. } = pattern {
92 let entry = ScopeEntry { name: name.clone(), pat };
93 self.scopes[scope].entries.push(entry);
96 pattern.walk_child_pats(|pat| self.add_bindings(body, scope, pat));
99 fn add_params_bindings(&mut self, body: &Body, scope: ScopeId, params: &[PatId]) {
100 params.iter().for_each(|pat| self.add_bindings(body, scope, *pat));
103 fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
104 self.scope_by_expr.insert(node, scope);
108 fn compute_block_scopes(
109 statements: &[Statement],
110 tail: Option<ExprId>,
112 scopes: &mut ExprScopes,
115 for stmt in statements {
117 Statement::Let { pat, initializer, .. } => {
118 if let Some(expr) = initializer {
119 scopes.set_scope(*expr, scope);
120 compute_expr_scopes(*expr, body, scopes, scope);
122 scope = scopes.new_scope(scope);
123 scopes.add_bindings(body, scope, *pat);
125 Statement::Expr(expr) => {
126 scopes.set_scope(*expr, scope);
127 compute_expr_scopes(*expr, body, scopes, scope);
131 if let Some(expr) = tail {
132 compute_expr_scopes(expr, body, scopes, scope);
136 fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
137 scopes.set_scope(expr, scope);
139 Expr::Block { statements, tail, .. } => {
140 compute_block_scopes(&statements, *tail, body, scopes, scope);
142 Expr::For { iterable, pat, body: body_expr, .. } => {
143 compute_expr_scopes(*iterable, body, scopes, scope);
144 let scope = scopes.new_scope(scope);
145 scopes.add_bindings(body, scope, *pat);
146 compute_expr_scopes(*body_expr, body, scopes, scope);
148 Expr::Lambda { args, body: body_expr, .. } => {
149 let scope = scopes.new_scope(scope);
150 scopes.add_params_bindings(body, scope, &args);
151 compute_expr_scopes(*body_expr, body, scopes, scope);
153 Expr::Match { expr, arms } => {
154 compute_expr_scopes(*expr, body, scopes, scope);
156 let scope = scopes.new_scope(scope);
157 scopes.add_bindings(body, scope, arm.pat);
158 if let Some(guard) = arm.guard {
159 scopes.set_scope(guard, scope);
160 compute_expr_scopes(guard, body, scopes, scope);
162 scopes.set_scope(arm.expr, scope);
163 compute_expr_scopes(arm.expr, body, scopes, scope);
166 e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
172 use base_db::{fixture::WithFixture, FileId, SourceDatabase};
173 use hir_expand::{name::AsName, InFile};
174 use syntax::{algo::find_node_at_offset, ast, AstNode};
175 use test_utils::{assert_eq_text, extract_offset, mark};
177 use crate::{db::DefDatabase, test_db::TestDB, FunctionId, ModuleDefId};
179 fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
180 let krate = db.test_crate();
181 let crate_def_map = db.crate_def_map(krate);
183 let module = crate_def_map.modules_for_file(file_id).next().unwrap();
184 let (_, def) = crate_def_map[module].scope.entries().next().unwrap();
185 match def.take_values().unwrap() {
186 ModuleDefId::FunctionId(it) => it,
191 fn do_check(ra_fixture: &str, expected: &[&str]) {
192 let (offset, code) = extract_offset(ra_fixture);
194 let mut buf = String::new();
195 let off: usize = offset.into();
196 buf.push_str(&code[..off]);
197 buf.push_str("<|>marker");
198 buf.push_str(&code[off..]);
202 let (db, position) = TestDB::with_position(&code);
203 let file_id = position.file_id;
204 let offset = position.offset;
206 let file_syntax = db.parse(file_id).syntax_node();
207 let marker: ast::PathExpr = find_node_at_offset(&file_syntax, offset).unwrap();
208 let function = find_function(&db, file_id);
210 let scopes = db.expr_scopes(function.into());
211 let (_body, source_map) = db.body_with_source_map(function.into());
213 let expr_id = source_map
214 .node_expr(InFile { file_id: file_id.into(), value: &marker.into() })
216 let scope = scopes.scope_for(expr_id);
220 .flat_map(|scope| scopes.entries(scope))
221 .map(|it| it.name().to_string())
224 let expected = expected.join("\n");
225 assert_eq_text!(&expected, &actual);
229 fn test_lambda_scope() {
233 let f = |bar, baz: i32| {
237 &["bar", "baz", "foo"],
242 fn test_call_scope() {
253 fn test_method_call_scope() {
264 fn test_loop_scope() {
293 fn test_shadow_variable() {
297 let x : &str = &x<|>;
304 fn test_bindings_after_at() {
309 opt @ Some(unit) => {
321 fn macro_inner_item() {
341 fn broken_inner_item() {
353 fn do_check_local_name(ra_fixture: &str, expected_offset: u32) {
354 let (db, position) = TestDB::with_position(ra_fixture);
355 let file_id = position.file_id;
356 let offset = position.offset;
358 let file = db.parse(file_id).ok().unwrap();
359 let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
360 .expect("failed to find a name at the target offset");
361 let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), offset).unwrap();
363 let function = find_function(&db, file_id);
365 let scopes = db.expr_scopes(function.into());
366 let (_body, source_map) = db.body_with_source_map(function.into());
369 let expr_ast = name_ref.syntax().ancestors().find_map(ast::Expr::cast).unwrap();
371 source_map.node_expr(InFile { file_id: file_id.into(), value: &expr_ast }).unwrap();
372 scopes.scope_for(expr_id).unwrap()
375 let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap();
376 let pat_src = source_map.pat_syntax(resolved.pat()).unwrap();
378 let local_name = pat_src.value.either(
379 |it| it.syntax_node_ptr().to_node(file.syntax()),
380 |it| it.syntax_node_ptr().to_node(file.syntax()),
382 assert_eq!(local_name.text_range(), expected_name.syntax().text_range());
386 fn test_resolve_local_name() {
389 fn foo(x: i32, y: u32) {
403 fn test_resolve_local_name_declaration() {
407 let x : &str = &x<|>;
415 fn test_resolve_local_name_shadow() {
428 fn ref_patterns_contribute_bindings() {
432 if let Some(&from) = bar() {
442 fn while_let_desugaring() {
443 mark::check!(infer_resolve_while_let);
447 let foo: Option<f32> = None;
448 while let Option::Some(spam) = foo {