aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2020-07-27 09:06:18 +0100
committerGitHub <[email protected]>2020-07-27 09:06:18 +0100
commit91b2f0baafa5fe1827ed13c56721b5f505564e7c (patch)
treee47d887f72abf2e38df06956e0a7635c255acd5b /crates
parent401a9c25151c1b659b8e80e2ffe70fa96a1f8ef1 (diff)
parentb3ca36b2d9fe5f2ef27cc19ced232e3168b77a38 (diff)
Merge #5539
5539: SSR: Fix path resolution of locals in current scope r=matklad a=davidlattimore Co-authored-by: David Lattimore <[email protected]>
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_ssr/src/lib.rs26
-rw-r--r--crates/ra_ssr/src/resolving.rs67
-rw-r--r--crates/ra_ssr/src/tests.rs37
3 files changed, 103 insertions, 27 deletions
diff --git a/crates/ra_ssr/src/lib.rs b/crates/ra_ssr/src/lib.rs
index 2fb326b45..7014a6ac6 100644
--- a/crates/ra_ssr/src/lib.rs
+++ b/crates/ra_ssr/src/lib.rs
@@ -51,8 +51,7 @@ pub struct MatchFinder<'db> {
51 /// Our source of information about the user's code. 51 /// Our source of information about the user's code.
52 sema: Semantics<'db, ra_ide_db::RootDatabase>, 52 sema: Semantics<'db, ra_ide_db::RootDatabase>,
53 rules: Vec<ResolvedRule>, 53 rules: Vec<ResolvedRule>,
54 scope: hir::SemanticsScope<'db>, 54 resolution_scope: resolving::ResolutionScope<'db>,
55 hygiene: hir::Hygiene,
56} 55}
57 56
58impl<'db> MatchFinder<'db> { 57impl<'db> MatchFinder<'db> {
@@ -63,21 +62,8 @@ impl<'db> MatchFinder<'db> {
63 lookup_context: FilePosition, 62 lookup_context: FilePosition,
64 ) -> MatchFinder<'db> { 63 ) -> MatchFinder<'db> {
65 let sema = Semantics::new(db); 64 let sema = Semantics::new(db);
66 let file = sema.parse(lookup_context.file_id); 65 let resolution_scope = resolving::ResolutionScope::new(&sema, lookup_context);
67 // Find a node at the requested position, falling back to the whole file. 66 MatchFinder { sema: Semantics::new(db), rules: Vec::new(), resolution_scope }
68 let node = file
69 .syntax()
70 .token_at_offset(lookup_context.offset)
71 .left_biased()
72 .map(|token| token.parent())
73 .unwrap_or_else(|| file.syntax().clone());
74 let scope = sema.scope(&node);
75 MatchFinder {
76 sema: Semantics::new(db),
77 rules: Vec::new(),
78 scope,
79 hygiene: hir::Hygiene::new(db, lookup_context.file_id.into()),
80 }
81 } 67 }
82 68
83 /// Constructs an instance using the start of the first file in `db` as the lookup context. 69 /// Constructs an instance using the start of the first file in `db` as the lookup context.
@@ -106,8 +92,7 @@ impl<'db> MatchFinder<'db> {
106 for parsed_rule in rule.parsed_rules { 92 for parsed_rule in rule.parsed_rules {
107 self.rules.push(ResolvedRule::new( 93 self.rules.push(ResolvedRule::new(
108 parsed_rule, 94 parsed_rule,
109 &self.scope, 95 &self.resolution_scope,
110 &self.hygiene,
111 self.rules.len(), 96 self.rules.len(),
112 )?); 97 )?);
113 } 98 }
@@ -140,8 +125,7 @@ impl<'db> MatchFinder<'db> {
140 for parsed_rule in pattern.parsed_rules { 125 for parsed_rule in pattern.parsed_rules {
141 self.rules.push(ResolvedRule::new( 126 self.rules.push(ResolvedRule::new(
142 parsed_rule, 127 parsed_rule,
143 &self.scope, 128 &self.resolution_scope,
144 &self.hygiene,
145 self.rules.len(), 129 self.rules.len(),
146 )?); 130 )?);
147 } 131 }
diff --git a/crates/ra_ssr/src/resolving.rs b/crates/ra_ssr/src/resolving.rs
index 75f556785..123bd2bb2 100644
--- a/crates/ra_ssr/src/resolving.rs
+++ b/crates/ra_ssr/src/resolving.rs
@@ -3,10 +3,16 @@
3use crate::errors::error; 3use crate::errors::error;
4use crate::{parsing, SsrError}; 4use crate::{parsing, SsrError};
5use parsing::Placeholder; 5use parsing::Placeholder;
6use ra_db::FilePosition;
6use ra_syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; 7use ra_syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken};
7use rustc_hash::{FxHashMap, FxHashSet}; 8use rustc_hash::{FxHashMap, FxHashSet};
8use test_utils::mark; 9use test_utils::mark;
9 10
11pub(crate) struct ResolutionScope<'db> {
12 scope: hir::SemanticsScope<'db>,
13 hygiene: hir::Hygiene,
14}
15
10pub(crate) struct ResolvedRule { 16pub(crate) struct ResolvedRule {
11 pub(crate) pattern: ResolvedPattern, 17 pub(crate) pattern: ResolvedPattern,
12 pub(crate) template: Option<ResolvedPattern>, 18 pub(crate) template: Option<ResolvedPattern>,
@@ -30,12 +36,11 @@ pub(crate) struct ResolvedPath {
30impl ResolvedRule { 36impl ResolvedRule {
31 pub(crate) fn new( 37 pub(crate) fn new(
32 rule: parsing::ParsedRule, 38 rule: parsing::ParsedRule,
33 scope: &hir::SemanticsScope, 39 resolution_scope: &ResolutionScope,
34 hygiene: &hir::Hygiene,
35 index: usize, 40 index: usize,
36 ) -> Result<ResolvedRule, SsrError> { 41 ) -> Result<ResolvedRule, SsrError> {
37 let resolver = 42 let resolver =
38 Resolver { scope, hygiene, placeholders_by_stand_in: rule.placeholders_by_stand_in }; 43 Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in };
39 let resolved_template = if let Some(template) = rule.template { 44 let resolved_template = if let Some(template) = rule.template {
40 Some(resolver.resolve_pattern_tree(template)?) 45 Some(resolver.resolve_pattern_tree(template)?)
41 } else { 46 } else {
@@ -57,8 +62,7 @@ impl ResolvedRule {
57} 62}
58 63
59struct Resolver<'a, 'db> { 64struct Resolver<'a, 'db> {
60 scope: &'a hir::SemanticsScope<'db>, 65 resolution_scope: &'a ResolutionScope<'db>,
61 hygiene: &'a hir::Hygiene,
62 placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, 66 placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>,
63} 67}
64 68
@@ -104,6 +108,7 @@ impl Resolver<'_, '_> {
104 && !self.path_contains_placeholder(&path) 108 && !self.path_contains_placeholder(&path)
105 { 109 {
106 let resolution = self 110 let resolution = self
111 .resolution_scope
107 .resolve_path(&path) 112 .resolve_path(&path)
108 .ok_or_else(|| error!("Failed to resolve path `{}`", node.text()))?; 113 .ok_or_else(|| error!("Failed to resolve path `{}`", node.text()))?;
109 resolved_paths.insert(node, ResolvedPath { resolution, depth }); 114 resolved_paths.insert(node, ResolvedPath { resolution, depth });
@@ -131,9 +136,32 @@ impl Resolver<'_, '_> {
131 } 136 }
132 false 137 false
133 } 138 }
139}
140
141impl<'db> ResolutionScope<'db> {
142 pub(crate) fn new(
143 sema: &hir::Semantics<'db, ra_ide_db::RootDatabase>,
144 lookup_context: FilePosition,
145 ) -> ResolutionScope<'db> {
146 use ra_syntax::ast::AstNode;
147 let file = sema.parse(lookup_context.file_id);
148 // Find a node at the requested position, falling back to the whole file.
149 let node = file
150 .syntax()
151 .token_at_offset(lookup_context.offset)
152 .left_biased()
153 .map(|token| token.parent())
154 .unwrap_or_else(|| file.syntax().clone());
155 let node = pick_node_for_resolution(node);
156 let scope = sema.scope(&node);
157 ResolutionScope {
158 scope,
159 hygiene: hir::Hygiene::new(sema.db, lookup_context.file_id.into()),
160 }
161 }
134 162
135 fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> { 163 fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> {
136 let hir_path = hir::Path::from_src(path.clone(), self.hygiene)?; 164 let hir_path = hir::Path::from_src(path.clone(), &self.hygiene)?;
137 // First try resolving the whole path. This will work for things like 165 // First try resolving the whole path. This will work for things like
138 // `std::collections::HashMap`, but will fail for things like 166 // `std::collections::HashMap`, but will fail for things like
139 // `std::collections::HashMap::new`. 167 // `std::collections::HashMap::new`.
@@ -158,6 +186,33 @@ impl Resolver<'_, '_> {
158 } 186 }
159} 187}
160 188
189/// Returns a suitable node for resolving paths in the current scope. If we create a scope based on
190/// a statement node, then we can't resolve local variables that were defined in the current scope
191/// (only in parent scopes). So we find another node, ideally a child of the statement where local
192/// variable resolution is permitted.
193fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode {
194 match node.kind() {
195 SyntaxKind::EXPR_STMT => {
196 if let Some(n) = node.first_child() {
197 mark::hit!(cursor_after_semicolon);
198 return n;
199 }
200 }
201 SyntaxKind::LET_STMT | SyntaxKind::BIND_PAT => {
202 if let Some(next) = node.next_sibling() {
203 return pick_node_for_resolution(next);
204 }
205 }
206 SyntaxKind::NAME => {
207 if let Some(parent) = node.parent() {
208 return pick_node_for_resolution(parent);
209 }
210 }
211 _ => {}
212 }
213 node
214}
215
161/// Returns whether `path` or any of its qualifiers contains type arguments. 216/// Returns whether `path` or any of its qualifiers contains type arguments.
162fn path_contains_type_arguments(path: Option<ast::Path>) -> bool { 217fn path_contains_type_arguments(path: Option<ast::Path>) -> bool {
163 if let Some(path) = path { 218 if let Some(path) = path {
diff --git a/crates/ra_ssr/src/tests.rs b/crates/ra_ssr/src/tests.rs
index b38807c0f..18ef2506a 100644
--- a/crates/ra_ssr/src/tests.rs
+++ b/crates/ra_ssr/src/tests.rs
@@ -885,3 +885,40 @@ fn ufcs_matches_method_call() {
885 "#]], 885 "#]],
886 ); 886 );
887} 887}
888
889#[test]
890fn replace_local_variable_reference() {
891 // The pattern references a local variable `foo` in the block containing the cursor. We should
892 // only replace references to this variable `foo`, not other variables that just happen to have
893 // the same name.
894 mark::check!(cursor_after_semicolon);
895 assert_ssr_transform(
896 "foo + $a ==>> $a - foo",
897 r#"
898 fn bar1() -> i32 {
899 let mut res = 0;
900 let foo = 5;
901 res += foo + 1;
902 let foo = 10;
903 res += foo + 2;<|>
904 res += foo + 3;
905 let foo = 15;
906 res += foo + 4;
907 res
908 }
909 "#,
910 expect![[r#"
911 fn bar1() -> i32 {
912 let mut res = 0;
913 let foo = 5;
914 res += foo + 1;
915 let foo = 10;
916 res += 2 - foo;
917 res += 3 - foo;
918 let foo = 15;
919 res += foo + 4;
920 res
921 }
922 "#]],
923 )
924}