rust/crates/hir_def/src/body/scope.rs

471 lines
13 KiB
Rust
Raw Normal View History

2019-11-24 12:00:50 -06:00
//! Name resolution for expressions.
2019-11-14 08:37:22 -06:00
use std::sync::Arc;
2019-11-14 02:56:13 -06:00
use hir_expand::name::Name;
2021-01-14 09:47:42 -06:00
use la_arena::{Arena, Idx};
2019-11-14 02:56:13 -06:00
use rustc_hash::FxHashMap;
use crate::{
body::Body,
2019-11-23 05:44:43 -06:00
db::DefDatabase,
2019-11-14 02:56:13 -06:00
expr::{Expr, ExprId, 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>,
2019-11-14 02:56:13 -06:00
scope_by_expr: FxHashMap<ExprId, ScopeId>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ScopeEntry {
name: Name,
pat: PatId,
}
impl ScopeEntry {
pub fn name(&self) -> &Name {
&self.name
}
pub fn pat(&self) -> PatId {
self.pat
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct ScopeData {
parent: Option<ScopeId>,
2021-02-09 10:11:44 -06:00
block: Option<BlockId>,
2019-11-14 02:56:13 -06:00
entries: Vec<ScopeEntry>,
}
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);
Arc::new(ExprScopes::new(&*body))
}
fn new(body: &Body) -> ExprScopes {
2019-11-14 02:56:13 -06:00
let mut scopes =
ExprScopes { scopes: Arena::default(), scope_by_expr: FxHashMap::default() };
let root = scopes.root_scope();
2019-11-24 09:48:29 -06:00
scopes.add_params_bindings(body, root, &body.params);
compute_expr_scopes(body.body_expr, body, &mut scopes, root);
2019-11-14 02:56:13 -06:00
scopes
}
pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
&self.scopes[scope].entries
}
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
}
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> {
self.scope_by_expr.get(&expr).copied()
}
pub fn scope_by_expr(&self) -> &FxHashMap<ExprId, ScopeId> {
&self.scope_by_expr
}
fn root_scope(&mut self) -> ScopeId {
2021-02-09 10:11:44 -06:00
self.scopes.alloc(ScopeData { parent: None, block: None, entries: vec![] })
2019-11-14 02:56:13 -06:00
}
fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
2021-02-09 10:11:44 -06:00
self.scopes.alloc(ScopeData { parent: Some(parent), block: None, entries: vec![] })
}
fn new_block_scope(&mut self, parent: ScopeId, block: BlockId) -> ScopeId {
self.scopes.alloc(ScopeData { parent: Some(parent), block: Some(block), entries: vec![] })
2019-11-14 02:56:13 -06:00
}
fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
2020-06-21 08:18:10 -05:00
let pattern = &body[pat];
if let Pat::Bind { name, .. } = pattern {
let entry = ScopeEntry { name: name.clone(), pat };
self.scopes[scope].entries.push(entry);
2019-11-14 02:56:13 -06:00
}
2020-06-21 08:18:10 -05:00
pattern.walk_child_pats(|pat| self.add_bindings(body, scope, pat));
2019-11-14 02:56:13 -06:00
}
fn add_params_bindings(&mut self, body: &Body, scope: ScopeId, params: &[PatId]) {
params.iter().for_each(|pat| self.add_bindings(body, scope, *pat));
}
fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
self.scope_by_expr.insert(node, scope);
}
}
fn compute_block_scopes(
statements: &[Statement],
tail: Option<ExprId>,
body: &Body,
scopes: &mut ExprScopes,
mut scope: ScopeId,
) {
for stmt in statements {
match stmt {
Statement::Let { pat, initializer, .. } => {
if let Some(expr) = initializer {
scopes.set_scope(*expr, scope);
compute_expr_scopes(*expr, body, scopes, scope);
}
scope = scopes.new_scope(scope);
scopes.add_bindings(body, scope, *pat);
}
Statement::Expr(expr) => {
scopes.set_scope(*expr, scope);
compute_expr_scopes(*expr, body, scopes, scope);
}
}
}
if let Some(expr) = tail {
compute_expr_scopes(expr, body, scopes, scope);
}
}
fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope: ScopeId) {
scopes.set_scope(expr, scope);
match &body[expr] {
2021-02-09 10:11:44 -06:00
Expr::Block { statements, tail, id, .. } => {
let scope = scopes.new_block_scope(scope, *id);
// 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);
2019-11-14 02:56:13 -06:00
compute_block_scopes(&statements, *tail, body, scopes, scope);
}
2020-05-31 03:59:40 -05:00
Expr::For { iterable, pat, body: body_expr, .. } => {
2019-11-14 02:56:13 -06:00
compute_expr_scopes(*iterable, body, scopes, scope);
let scope = scopes.new_scope(scope);
scopes.add_bindings(body, scope, *pat);
compute_expr_scopes(*body_expr, body, scopes, scope);
}
Expr::Lambda { args, body: body_expr, .. } => {
let scope = scopes.new_scope(scope);
scopes.add_params_bindings(body, scope, &args);
compute_expr_scopes(*body_expr, body, scopes, scope);
}
Expr::Match { expr, arms } => {
compute_expr_scopes(*expr, body, scopes, scope);
for arm in arms {
let scope = scopes.new_scope(scope);
2020-02-09 12:57:01 -06:00
scopes.add_bindings(body, scope, arm.pat);
if let Some(guard) = arm.guard {
scopes.set_scope(guard, scope);
compute_expr_scopes(guard, body, scopes, scope);
}
2019-11-14 02:56:13 -06:00
scopes.set_scope(arm.expr, scope);
compute_expr_scopes(arm.expr, body, scopes, scope);
}
}
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 {
2020-08-13 09:25:38 -05:00
use base_db::{fixture::WithFixture, FileId, SourceDatabase};
2019-11-28 03:50:26 -06:00
use hir_expand::{name::AsName, InFile};
2020-08-12 11:26:51 -05:00
use syntax::{algo::find_node_at_offset, ast, AstNode};
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_string())
.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());
let (_body, source_map) = db.body_with_source_map(function.into());
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();
let pat_src = source_map.pat_syntax(resolved.pat()).unwrap();
let local_name = pat_src.value.either(
|it| it.syntax_node_ptr().to_node(file.syntax()),
|it| it.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]
2019-11-21 08:09:38 -06:00
fn while_let_desugaring() {
2021-03-08 14:19:44 -06:00
cov_mark::check!(infer_resolve_while_let);
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,
);
}
2019-11-15 05:47:26 -06:00
}