move resolve local name

This commit is contained in:
Aleksey Kladov 2018-10-31 15:13:49 +03:00
parent b67295134b
commit c02be1502c
7 changed files with 31 additions and 94 deletions

View file

@ -151,15 +151,7 @@ pub fn find_node_at_offset<'a, N: AstNode<'a>>(
leaf.ancestors().filter_map(N::cast).next()
}
pub fn resolve_local_name(
name_ref: ast::NameRef,
) -> Option<(SmolStr, TextRange)> {
let fn_def = name_ref.syntax().ancestors().find_map(ast::FnDef::cast)?;
let scopes = scope::FnScopes::new(fn_def);
let scope_entry = scope::resolve_local_name(name_ref, &scopes)?;
let name = scope_entry.ast().name()?;
Some((scope_entry.name(), name.syntax().range()))
}
#[cfg(test)]
mod tests {

View file

@ -258,22 +258,6 @@ struct ScopeData {
entries: Vec<ScopeEntry>,
}
pub fn resolve_local_name<'a>(
name_ref: ast::NameRef,
scopes: &'a FnScopes,
) -> Option<&'a ScopeEntry> {
use rustc_hash::FxHashSet;
let mut shadowed = FxHashSet::default();
let ret = scopes
.scope_chain(name_ref.syntax())
.flat_map(|scope| scopes.entries(scope).iter())
.filter(|entry| shadowed.insert(entry.name()))
.filter(|entry| entry.name() == name_ref.text())
.nth(0);
ret
}
#[cfg(test)]
mod tests {
use super::*;
@ -376,61 +360,4 @@ mod tests {
&["x"],
);
}
fn do_check_local_name(code: &str, expected_offset: u32) {
let (off, code) = extract_offset(code);
let file = File::parse(&code);
let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap();
let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap();
let scopes = FnScopes::new(fn_def);
let local_name = resolve_local_name(name_ref, &scopes)
.unwrap()
.ast()
.name()
.unwrap();
let expected_name =
find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into()).unwrap();
assert_eq!(local_name.syntax().range(), expected_name.syntax().range());
}
#[test]
fn test_resolve_local_name() {
do_check_local_name(
r#"
fn foo(x: i32, y: u32) {
{
let z = x * 2;
}
{
let t = x<|> * 3;
}
}"#,
21,
);
}
#[test]
fn test_resolve_local_name_declaration() {
do_check_local_name(
r#"
fn foo(x: String) {
let x : &str = &x<|>;
}"#,
21,
);
}
#[test]
fn test_resolve_local_name_shadow() {
do_check_local_name(
r"
fn foo(x: String) {
let x : &str = &x;
x<|>
}",
46,
);
}
}

View file

@ -2,6 +2,6 @@ mod fn_scope;
mod mod_scope;
pub use self::{
fn_scope::{resolve_local_name, FnScopes},
fn_scope::{FnScopes},
mod_scope::ModuleScope,
};