rust/crates/hir-def/src/body/scope.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

603 lines
17 KiB
Rust
Raw Normal View History

2019-11-24 12:00:50 -06:00
//! Name resolution for expressions.
2019-11-14 02:56:13 -06:00
use hir_expand::name::Name;
2023-09-22 01:08:00 -05:00
use la_arena::{Arena, ArenaMap, Idx, IdxRange, RawIdx};
2023-05-02 09:12:22 -05:00
use triomphe::Arc;
2019-11-14 02:56:13 -06:00
use crate::{
body::Body,
2019-11-23 05:44:43 -06:00
db::DefDatabase,
hir::{Binding, BindingId, Expr, ExprId, LabelId, Pat, PatId, Statement},
2021-02-09 10:11:44 -06:00
BlockId, DefWithBodyId,
2019-11-14 02:56:13 -06:00
};
2020-03-19 10:00:11 -05:00
pub type ScopeId = Idx<ScopeData>;
2019-11-14 02:56:13 -06:00
#[derive(Debug, PartialEq, Eq)]
pub struct ExprScopes {
2020-03-19 10:00:11 -05:00
scopes: Arena<ScopeData>,
scope_entries: Arena<ScopeEntry>,
2023-09-22 01:08:00 -05:00
scope_by_expr: ArenaMap<ExprId, ScopeId>,
2019-11-14 02:56:13 -06:00
}
#[derive(Debug, PartialEq, Eq)]
pub struct ScopeEntry {
name: Name,
2023-02-18 14:32:55 -06:00
binding: BindingId,
2019-11-14 02:56:13 -06:00
}
impl ScopeEntry {
pub fn name(&self) -> &Name {
&self.name
}
2023-02-18 14:32:55 -06:00
pub fn binding(&self) -> BindingId {
self.binding
2019-11-14 02:56:13 -06:00
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct ScopeData {
parent: Option<ScopeId>,
2021-02-09 10:11:44 -06:00
block: Option<BlockId>,
2021-03-20 18:59:45 -05:00
label: Option<(LabelId, Name)>,
entries: IdxRange<ScopeEntry>,
2019-11-14 02:56:13 -06:00
}
impl ExprScopes {
pub(crate) fn expr_scopes_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<ExprScopes> {
2019-11-14 08:37:22 -06:00
let body = db.body(def);
let mut scopes = ExprScopes::new(&body);
scopes.shrink_to_fit();
Arc::new(scopes)
2019-11-14 02:56:13 -06:00
}
pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
&self.scope_entries[self.scopes[scope].entries.clone()]
2019-11-14 02:56:13 -06:00
}
2021-02-09 10:11:44 -06:00
/// If `scope` refers to a block expression scope, returns the corresponding `BlockId`.
pub fn block(&self, scope: ScopeId) -> Option<BlockId> {
self.scopes[scope].block
}
2021-03-20 18:59:45 -05:00
/// If `scope` refers to a labeled expression scope, returns the corresponding `Label`.
pub fn label(&self, scope: ScopeId) -> Option<(LabelId, Name)> {
self.scopes[scope].label.clone()
}
/// Returns the scopes in ascending order.
2019-11-14 02:56:13 -06:00
pub fn scope_chain(&self, scope: Option<ScopeId>) -> impl Iterator<Item = ScopeId> + '_ {
std::iter::successors(scope, move |&scope| self.scopes[scope].parent)
}
2019-11-15 05:47:26 -06:00
pub fn resolve_name_in_scope(&self, scope: ScopeId, name: &Name) -> Option<&ScopeEntry> {
self.scope_chain(Some(scope))
.find_map(|scope| self.entries(scope).iter().find(|it| it.name == *name))
}
2019-11-14 02:56:13 -06:00
pub fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
2023-09-22 01:08:00 -05:00
self.scope_by_expr.get(expr).copied()
2019-11-14 02:56:13 -06:00
}
2023-09-22 01:08:00 -05:00
pub fn scope_by_expr(&self) -> &ArenaMap<ExprId, ScopeId> {
2019-11-14 02:56:13 -06:00
&self.scope_by_expr
}
}
fn empty_entries(idx: usize) -> IdxRange<ScopeEntry> {
IdxRange::new(Idx::from_raw(RawIdx::from(idx as u32))..Idx::from_raw(RawIdx::from(idx as u32)))
}
impl ExprScopes {
fn new(body: &Body) -> ExprScopes {
let mut scopes = ExprScopes {
scopes: Arena::default(),
scope_entries: Arena::default(),
2023-09-22 01:08:00 -05:00
scope_by_expr: ArenaMap::with_capacity(body.exprs.len()),
};
let mut root = scopes.root_scope();
scopes.add_params_bindings(body, root, &body.params);
compute_expr_scopes(body.body_expr, body, &mut scopes, &mut root);
scopes
}
2019-11-14 02:56:13 -06:00
fn root_scope(&mut self) -> ScopeId {
self.scopes.alloc(ScopeData {
parent: None,
block: None,
label: None,
entries: empty_entries(self.scope_entries.len()),
})
2019-11-14 02:56:13 -06:00
}
fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
2021-03-20 18:59:45 -05:00
self.scopes.alloc(ScopeData {
parent: Some(parent),
block: None,
label: None,
entries: empty_entries(self.scope_entries.len()),
2021-03-20 18:59:45 -05:00
})
2021-02-09 10:11:44 -06:00
}
2021-03-20 18:59:45 -05:00
fn new_labeled_scope(&mut self, parent: ScopeId, label: Option<(LabelId, Name)>) -> ScopeId {
self.scopes.alloc(ScopeData {
parent: Some(parent),
block: None,
label,
entries: empty_entries(self.scope_entries.len()),
})
2021-03-20 18:59:45 -05:00
}
fn new_block_scope(
&mut self,
parent: ScopeId,
block: Option<BlockId>,
2021-03-20 18:59:45 -05:00
label: Option<(LabelId, Name)>,
) -> ScopeId {
self.scopes.alloc(ScopeData {
parent: Some(parent),
block,
label,
entries: empty_entries(self.scope_entries.len()),
})
2019-11-14 02:56:13 -06:00
}
2023-02-18 14:32:55 -06:00
fn add_bindings(&mut self, body: &Body, scope: ScopeId, binding: BindingId) {
let Binding { name, .. } = &body.bindings[binding];
let entry = self.scope_entries.alloc(ScopeEntry { name: name.clone(), binding });
self.scopes[scope].entries =
IdxRange::new_inclusive(self.scopes[scope].entries.start()..=entry);
2023-02-18 14:32:55 -06:00
}
fn add_pat_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
2020-06-21 08:18:10 -05:00
let pattern = &body[pat];
2023-02-18 14:32:55 -06:00
if let Pat::Bind { id, .. } = pattern {
self.add_bindings(body, scope, *id);
2019-11-14 02:56:13 -06:00
}
2020-06-21 08:18:10 -05:00
2023-02-18 14:32:55 -06:00
pattern.walk_child_pats(|pat| self.add_pat_bindings(body, scope, pat));
2019-11-14 02:56:13 -06:00
}
fn add_params_bindings(&mut self, body: &Body, scope: ScopeId, params: &[PatId]) {
2023-02-18 14:32:55 -06:00
params.iter().for_each(|pat| self.add_pat_bindings(body, scope, *pat));
2019-11-14 02:56:13 -06:00
}
fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
self.scope_by_expr.insert(node, scope);
}
fn shrink_to_fit(&mut self) {
let ExprScopes { scopes, scope_entries, scope_by_expr } = self;
scopes.shrink_to_fit();
scope_entries.shrink_to_fit();
scope_by_expr.shrink_to_fit();
}
2019-11-14 02:56:13 -06:00
}
fn compute_block_scopes(
statements: &[Statement],
tail: Option<ExprId>,
body: &Body,
scopes: &mut ExprScopes,
scope: &mut ScopeId,
2019-11-14 02:56:13 -06:00
) {
for stmt in statements {
match stmt {
2021-10-07 10:05:50 -05:00
Statement::Let { pat, initializer, else_branch, .. } => {
2019-11-14 02:56:13 -06:00
if let Some(expr) = initializer {
compute_expr_scopes(*expr, body, scopes, scope);
2019-11-14 02:56:13 -06:00
}
2021-10-07 10:05:50 -05:00
if let Some(expr) = else_branch {
compute_expr_scopes(*expr, body, scopes, scope);
2021-10-07 10:05:50 -05:00
}
*scope = scopes.new_scope(*scope);
2023-02-18 14:32:55 -06:00
scopes.add_pat_bindings(body, *scope, *pat);
2019-11-14 02:56:13 -06:00
}
Statement::Expr { expr, .. } => {
compute_expr_scopes(*expr, body, scopes, scope);
2019-11-14 02:56:13 -06:00
}
Statement::Item => (),
2019-11-14 02:56:13 -06:00
}
}
if let Some(expr) = tail {
compute_expr_scopes(expr, body, scopes, scope);
2019-11-14 02:56:13 -06:00
}
}
2022-01-22 21:39:26 -06:00
fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: &mut ScopeId) {
2021-03-20 18:59:45 -05:00
let make_label =
2021-10-04 22:10:25 -05:00
|label: &Option<LabelId>| label.map(|label| (label, body.labels[label].name.clone()));
2021-03-20 18:59:45 -05:00
2022-01-22 21:39:26 -06:00
scopes.set_scope(expr, *scope);
2019-11-14 02:56:13 -06:00
match &body[expr] {
2021-03-20 18:59:45 -05:00
Expr::Block { statements, tail, id, label } => {
let mut scope = scopes.new_block_scope(*scope, *id, make_label(label));
2021-02-09 10:11:44 -06:00
// Overwrite the old scope for the block expr, so that every block scope can be found
// via the block itself (important for blocks that only contain items, no expressions).
scopes.set_scope(expr, scope);
compute_block_scopes(statements, *tail, body, scopes, &mut scope);
}
2023-05-12 09:47:15 -05:00
Expr::Const(_) => {
// FIXME: This is broken.
}
Expr::Unsafe { id, statements, tail } | Expr::Async { id, statements, tail } => {
let mut scope = scopes.new_block_scope(*scope, *id, None);
// Overwrite the old scope for the block expr, so that every block scope can be found
// via the block itself (important for blocks that only contain items, no expressions).
2021-02-09 10:11:44 -06:00
scopes.set_scope(expr, scope);
compute_block_scopes(statements, *tail, body, scopes, &mut scope);
2019-11-14 02:56:13 -06:00
}
2021-03-20 18:59:45 -05:00
Expr::Loop { body: body_expr, label } => {
2022-01-22 21:39:26 -06:00
let mut scope = scopes.new_labeled_scope(*scope, make_label(label));
compute_expr_scopes(*body_expr, body, scopes, &mut scope);
2021-03-20 18:59:45 -05:00
}
Expr::Closure { args, body: body_expr, .. } => {
2022-01-22 21:39:26 -06:00
let mut scope = scopes.new_scope(*scope);
2021-06-12 22:54:16 -05:00
scopes.add_params_bindings(body, scope, args);
2022-01-22 21:39:26 -06:00
compute_expr_scopes(*body_expr, body, scopes, &mut scope);
2019-11-14 02:56:13 -06:00
}
Expr::Match { expr, arms } => {
compute_expr_scopes(*expr, body, scopes, scope);
for arm in arms.iter() {
2022-01-22 21:39:26 -06:00
let mut scope = scopes.new_scope(*scope);
2023-02-18 14:32:55 -06:00
scopes.add_pat_bindings(body, scope, arm.pat);
2022-01-22 21:39:26 -06:00
if let Some(guard) = arm.guard {
scope = scopes.new_scope(scope);
compute_expr_scopes(guard, body, scopes, &mut scope);
}
compute_expr_scopes(arm.expr, body, scopes, &mut scope);
2019-11-14 02:56:13 -06:00
}
}
2022-01-22 21:39:26 -06:00
&Expr::If { condition, then_branch, else_branch } => {
let mut then_branch_scope = scopes.new_scope(*scope);
compute_expr_scopes(condition, body, scopes, &mut then_branch_scope);
compute_expr_scopes(then_branch, body, scopes, &mut then_branch_scope);
if let Some(else_branch) = else_branch {
compute_expr_scopes(else_branch, body, scopes, scope);
}
}
&Expr::Let { pat, expr } => {
compute_expr_scopes(expr, body, scopes, scope);
*scope = scopes.new_scope(*scope);
2023-02-18 14:32:55 -06:00
scopes.add_pat_bindings(body, *scope, pat);
2022-01-22 21:39:26 -06:00
}
2019-11-14 02:56:13 -06:00
e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
};
}
2019-11-15 05:47:26 -06:00
#[cfg(test)]
mod tests {
use base_db::{FileId, SourceDatabase};
use hir_expand::{name::AsName, InFile};
2020-08-12 11:26:51 -05:00
use syntax::{algo::find_node_at_offset, ast, AstNode};
use test_fixture::WithFixture;
2021-03-08 14:19:44 -06:00
use test_utils::{assert_eq_text, extract_offset};
2019-11-15 05:47:26 -06:00
2019-11-23 05:44:43 -06:00
use crate::{db::DefDatabase, test_db::TestDB, FunctionId, ModuleDefId};
2019-11-15 05:47:26 -06:00
fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
let krate = db.test_crate();
let crate_def_map = db.crate_def_map(krate);
let module = crate_def_map.modules_for_file(file_id).next().unwrap();
2019-12-22 08:37:07 -06:00
let (_, def) = crate_def_map[module].scope.entries().next().unwrap();
match def.take_values().unwrap() {
2019-11-15 05:47:26 -06:00
ModuleDefId::FunctionId(it) => it,
_ => panic!(),
}
}
2020-06-21 08:18:10 -05:00
fn do_check(ra_fixture: &str, expected: &[&str]) {
let (offset, code) = extract_offset(ra_fixture);
2019-11-15 05:47:26 -06:00
let code = {
let mut buf = String::new();
let off: usize = offset.into();
2019-11-15 05:47:26 -06:00
buf.push_str(&code[..off]);
2021-01-06 14:15:48 -06:00
buf.push_str("$0marker");
2019-11-15 05:47:26 -06:00
buf.push_str(&code[off..]);
buf
};
let (db, position) = TestDB::with_position(&code);
let file_id = position.file_id;
let offset = position.offset;
2019-11-15 05:47:26 -06:00
let file_syntax = db.parse(file_id).syntax_node();
let marker: ast::PathExpr = find_node_at_offset(&file_syntax, offset).unwrap();
2019-11-15 05:47:26 -06:00
let function = find_function(&db, file_id);
let scopes = db.expr_scopes(function.into());
let (_body, source_map) = db.body_with_source_map(function.into());
2019-11-20 00:40:36 -06:00
let expr_id = source_map
2019-11-28 03:50:26 -06:00
.node_expr(InFile { file_id: file_id.into(), value: &marker.into() })
2019-11-20 00:40:36 -06:00
.unwrap();
2019-11-15 05:47:26 -06:00
let scope = scopes.scope_for(expr_id);
let actual = scopes
.scope_chain(scope)
.flat_map(|scope| scopes.entries(scope))
.map(|it| it.name().to_smol_str())
2019-11-15 05:47:26 -06:00
.collect::<Vec<_>>()
.join("\n");
let expected = expected.join("\n");
assert_eq_text!(&expected, &actual);
}
#[test]
fn test_lambda_scope() {
do_check(
r"
fn quux(foo: i32) {
let f = |bar, baz: i32| {
2021-01-06 14:15:48 -06:00
$0
2019-11-15 05:47:26 -06:00
};
}",
&["bar", "baz", "foo"],
);
}
#[test]
fn test_call_scope() {
do_check(
r"
fn quux() {
2021-01-06 14:15:48 -06:00
f(|x| $0 );
2019-11-15 05:47:26 -06:00
}",
&["x"],
);
}
#[test]
fn test_method_call_scope() {
do_check(
r"
fn quux() {
2021-01-06 14:15:48 -06:00
z.f(|x| $0 );
2019-11-15 05:47:26 -06:00
}",
&["x"],
);
}
#[test]
fn test_loop_scope() {
do_check(
r"
fn quux() {
loop {
let x = ();
2021-01-06 14:15:48 -06:00
$0
2019-11-15 05:47:26 -06:00
};
}",
&["x"],
);
}
#[test]
fn test_match() {
do_check(
r"
fn quux() {
match () {
Some(x) => {
2021-01-06 14:15:48 -06:00
$0
2019-11-15 05:47:26 -06:00
}
};
}",
&["x"],
);
}
#[test]
fn test_shadow_variable() {
do_check(
r"
fn foo(x: String) {
2021-01-06 14:15:48 -06:00
let x : &str = &x$0;
2019-11-15 05:47:26 -06:00
}",
&["x"],
);
}
2020-06-21 08:18:10 -05:00
#[test]
fn test_bindings_after_at() {
do_check(
r"
fn foo() {
match Some(()) {
opt @ Some(unit) => {
2021-01-06 14:15:48 -06:00
$0
}
_ => {}
}
}
",
2020-06-21 08:18:10 -05:00
&["opt", "unit"],
);
}
#[test]
fn macro_inner_item() {
do_check(
r"
macro_rules! mac {
() => {{
fn inner() {}
inner();
}};
}
fn foo() {
mac!();
2021-01-06 14:15:48 -06:00
$0
}
",
&[],
);
}
#[test]
fn broken_inner_item() {
do_check(
r"
fn foo() {
trait {}
2021-01-06 14:15:48 -06:00
$0
}
",
&[],
);
}
fn do_check_local_name(ra_fixture: &str, expected_offset: u32) {
let (db, position) = TestDB::with_position(ra_fixture);
let file_id = position.file_id;
let offset = position.offset;
2019-11-15 05:47:26 -06:00
let file = db.parse(file_id).ok().unwrap();
let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
.expect("failed to find a name at the target offset");
let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), offset).unwrap();
2019-11-15 05:47:26 -06:00
let function = find_function(&db, file_id);
let scopes = db.expr_scopes(function.into());
2023-02-18 14:32:55 -06:00
let (body, source_map) = db.body_with_source_map(function.into());
2019-11-15 05:47:26 -06:00
let expr_scope = {
let expr_ast = name_ref.syntax().ancestors().find_map(ast::Expr::cast).unwrap();
let expr_id =
2019-11-28 03:50:26 -06:00
source_map.node_expr(InFile { file_id: file_id.into(), value: &expr_ast }).unwrap();
2019-11-15 05:47:26 -06:00
scopes.scope_for(expr_id).unwrap()
};
let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap();
2023-02-18 14:32:55 -06:00
let pat_src = source_map
.pat_syntax(*body.bindings[resolved.binding()].definitions.first().unwrap())
.unwrap();
2019-11-15 05:47:26 -06:00
let local_name = pat_src.value.syntax_node_ptr().to_node(file.syntax());
assert_eq!(local_name.text_range(), expected_name.syntax().text_range());
2019-11-15 05:47:26 -06:00
}
#[test]
fn test_resolve_local_name() {
do_check_local_name(
r#"
fn foo(x: i32, y: u32) {
{
let z = x * 2;
}
{
2021-01-06 14:15:48 -06:00
let t = x$0 * 3;
}
}
"#,
7,
2019-11-15 05:47:26 -06:00
);
}
#[test]
fn test_resolve_local_name_declaration() {
do_check_local_name(
r#"
fn foo(x: String) {
2021-01-06 14:15:48 -06:00
let x : &str = &x$0;
}
"#,
7,
2019-11-15 05:47:26 -06:00
);
}
#[test]
fn test_resolve_local_name_shadow() {
do_check_local_name(
r"
fn foo(x: String) {
let x : &str = &x;
2021-01-06 14:15:48 -06:00
x$0
}
",
28,
2019-11-15 05:47:26 -06:00
);
}
#[test]
fn ref_patterns_contribute_bindings() {
do_check_local_name(
r"
fn foo() {
if let Some(&from) = bar() {
2021-01-06 14:15:48 -06:00
from$0;
}
}
",
28,
2019-11-15 05:47:26 -06:00
);
}
2019-11-21 06:49:24 -06:00
#[test]
2022-01-22 21:39:26 -06:00
fn while_let_adds_binding() {
2019-11-21 06:49:24 -06:00
do_check_local_name(
r#"
fn test() {
let foo: Option<f32> = None;
while let Option::Some(spam) = foo {
2021-01-06 14:15:48 -06:00
spam$0
2019-11-21 06:49:24 -06:00
}
}
"#,
75,
);
2022-01-22 21:39:26 -06:00
do_check_local_name(
r#"
fn test() {
let foo: Option<f32> = None;
while (((let Option::Some(_) = foo))) && let Option::Some(spam) = foo {
spam$0
}
}
"#,
107,
);
}
#[test]
fn match_guard_if_let() {
do_check_local_name(
r#"
fn test() {
let foo: Option<f32> = None;
match foo {
_ if let Option::Some(spam) = foo => spam$0,
}
}
"#,
93,
);
2019-11-21 06:49:24 -06:00
}
#[test]
fn let_chains_can_reference_previous_lets() {
do_check_local_name(
r#"
fn test() {
let foo: Option<i32> = None;
if let Some(spam) = foo && spa$0m > 1 && let Some(spam) = foo && spam > 1 {}
}
"#,
61,
);
do_check_local_name(
r#"
fn test() {
let foo: Option<i32> = None;
if let Some(spam) = foo && spam > 1 && let Some(spam) = foo && sp$0am > 1 {}
}
"#,
100,
);
}
2019-11-15 05:47:26 -06:00
}