aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--crates/ra_assists/src/assists/add_missing_impl_members.rs121
-rw-r--r--crates/ra_assists/src/ast_transform.rs178
-rw-r--r--crates/ra_assists/src/lib.rs1
-rw-r--r--crates/ra_ide/src/expand_macro.rs7
-rw-r--r--crates/ra_syntax/src/algo.rs6
-rw-r--r--crates/ra_syntax/src/ast/edit.rs8
-rw-r--r--crates/ra_syntax/src/ast/make.rs11
7 files changed, 206 insertions, 126 deletions
diff --git a/crates/ra_assists/src/assists/add_missing_impl_members.rs b/crates/ra_assists/src/assists/add_missing_impl_members.rs
index 942b34dc1..bf1136193 100644
--- a/crates/ra_assists/src/assists/add_missing_impl_members.rs
+++ b/crates/ra_assists/src/assists/add_missing_impl_members.rs
@@ -1,12 +1,13 @@
1use std::collections::HashMap; 1use hir::{db::HirDatabase, HasSource, InFile};
2
3use hir::{db::HirDatabase, HasSource};
4use ra_syntax::{ 2use ra_syntax::{
5 ast::{self, edit, make, AstNode, NameOwner}, 3 ast::{self, edit, make, AstNode, NameOwner},
6 SmolStr, 4 SmolStr,
7}; 5};
8 6
9use crate::{Assist, AssistCtx, AssistId}; 7use crate::{
8 ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams},
9 Assist, AssistCtx, AssistId,
10};
10 11
11#[derive(PartialEq)] 12#[derive(PartialEq)]
12enum AddMissingImplMembersMode { 13enum AddMissingImplMembersMode {
@@ -146,24 +147,11 @@ fn add_missing_impl_members_inner(
146 None, 147 None,
147 ) 148 )
148 .module(); 149 .module();
149 let substs = get_syntactic_substs(impl_node).unwrap_or_default(); 150 let ast_transform = QualifyPaths::new(db, module)
150 let generic_def: hir::GenericDef = trait_.into(); 151 .or(SubstituteTypeParams::for_trait_impl(db, trait_, impl_node));
151 let substs_by_param: HashMap<_, _> = generic_def
152 .params(db)
153 .into_iter()
154 // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
155 .skip(1)
156 .zip(substs.into_iter())
157 .collect();
158 let items = missing_items 152 let items = missing_items
159 .into_iter() 153 .into_iter()
160 .map(|it| { 154 .map(|it| ast_transform::apply(&*ast_transform, InFile::new(trait_file_id, it)))
161 substitute_type_params(db, hir::InFile::new(trait_file_id, it), &substs_by_param)
162 })
163 .map(|it| match module {
164 Some(module) => qualify_paths(db, hir::InFile::new(trait_file_id, it), module),
165 None => it,
166 })
167 .map(|it| match it { 155 .map(|it| match it {
168 ast::ImplItem::FnDef(def) => ast::ImplItem::FnDef(add_body(def)), 156 ast::ImplItem::FnDef(def) => ast::ImplItem::FnDef(add_body(def)),
169 _ => it, 157 _ => it,
@@ -188,99 +176,6 @@ fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
188 } 176 }
189} 177}
190 178
191// FIXME: It would probably be nicer if we could get this via HIR (i.e. get the
192// trait ref, and then go from the types in the substs back to the syntax)
193// FIXME: This should be a general utility (not even just for assists)
194fn get_syntactic_substs(impl_block: ast::ImplBlock) -> Option<Vec<ast::TypeRef>> {
195 let target_trait = impl_block.target_trait()?;
196 let path_type = match target_trait {
197 ast::TypeRef::PathType(path) => path,
198 _ => return None,
199 };
200 let type_arg_list = path_type.path()?.segment()?.type_arg_list()?;
201 let mut result = Vec::new();
202 for type_arg in type_arg_list.type_args() {
203 let type_arg: ast::TypeArg = type_arg;
204 result.push(type_arg.type_ref()?);
205 }
206 Some(result)
207}
208
209// FIXME: This should be a general utility (not even just for assists)
210fn substitute_type_params<N: AstNode + Clone>(
211 db: &impl HirDatabase,
212 node: hir::InFile<N>,
213 substs: &HashMap<hir::TypeParam, ast::TypeRef>,
214) -> N {
215 let type_param_replacements = node
216 .clone()
217 .descendants::<ast::TypeRef>()
218 .filter_map(|n| {
219 let path = match &n.value {
220 ast::TypeRef::PathType(path_type) => path_type.path()?,
221 _ => return None,
222 };
223 let analyzer = hir::SourceAnalyzer::new(db, n.syntax(), None);
224 let resolution = analyzer.resolve_path(db, &path)?;
225 match resolution {
226 hir::PathResolution::TypeParam(tp) => Some((n.value, substs.get(&tp)?.clone())),
227 _ => None,
228 }
229 })
230 .collect::<Vec<_>>();
231
232 if type_param_replacements.is_empty() {
233 node.value
234 } else {
235 edit::replace_descendants(&node.value, type_param_replacements.into_iter())
236 }
237}
238
239use hir::PathResolution;
240
241// FIXME extract this to a general utility as well
242// FIXME handle value ns?
243// FIXME this doesn't 'commute' with `substitute_type_params`, since type params in newly generated type arg lists don't resolve. Currently we can avoid this problem, but it's worth thinking about a solution
244fn qualify_paths<N: AstNode>(db: &impl HirDatabase, node: hir::InFile<N>, from: hir::Module) -> N {
245 let path_replacements = node
246 .value
247 .syntax()
248 .descendants()
249 .filter_map(ast::Path::cast)
250 .filter_map(|p| {
251 if p.segment().and_then(|s| s.param_list()).is_some() {
252 // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway
253 return None;
254 }
255 // FIXME check if some ancestor is already being replaced, if so skip this
256 let analyzer = hir::SourceAnalyzer::new(db, node.with_value(p.syntax()), None);
257 let resolution = analyzer.resolve_path(db, &p)?;
258 match resolution {
259 PathResolution::Def(def) => {
260 let found_path = from.find_path(db, def)?;
261 // TODO fix type arg replacements being qualified
262 let args = p
263 .segment()
264 .and_then(|s| s.type_arg_list())
265 .map(|arg_list| qualify_paths(db, node.with_value(arg_list), from));
266 Some((p, make::path_with_type_arg_list(found_path.to_ast(), args)))
267 }
268 PathResolution::Local(_)
269 | PathResolution::TypeParam(_)
270 | PathResolution::SelfType(_) => None,
271 PathResolution::Macro(_) => None,
272 PathResolution::AssocItem(_) => None,
273 }
274 })
275 .collect::<Vec<_>>();
276
277 if path_replacements.is_empty() {
278 node.value
279 } else {
280 edit::replace_descendants(&node.value, path_replacements.into_iter())
281 }
282}
283
284/// Given an `ast::ImplBlock`, resolves the target trait (the one being 179/// Given an `ast::ImplBlock`, resolves the target trait (the one being
285/// implemented) to a `ast::TraitDef`. 180/// implemented) to a `ast::TraitDef`.
286fn resolve_target_trait_def( 181fn resolve_target_trait_def(
diff --git a/crates/ra_assists/src/ast_transform.rs b/crates/ra_assists/src/ast_transform.rs
new file mode 100644
index 000000000..846661587
--- /dev/null
+++ b/crates/ra_assists/src/ast_transform.rs
@@ -0,0 +1,178 @@
1//! `AstTransformer`s are functions that replace nodes in an AST and can be easily combined.
2use std::collections::HashMap;
3
4use hir::{db::HirDatabase, InFile, PathResolution};
5use ra_syntax::ast::{self, make, AstNode};
6
7pub trait AstTransform<'a> {
8 fn get_substitution(
9 &self,
10 node: InFile<&ra_syntax::SyntaxNode>,
11 ) -> Option<ra_syntax::SyntaxNode>;
12
13 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a>;
14 fn or<T: AstTransform<'a> + 'a>(self, other: T) -> Box<dyn AstTransform<'a> + 'a>
15 where
16 Self: Sized + 'a,
17 {
18 self.chain_before(Box::new(other))
19 }
20}
21
22struct NullTransformer;
23
24impl<'a> AstTransform<'a> for NullTransformer {
25 fn get_substitution(
26 &self,
27 _node: InFile<&ra_syntax::SyntaxNode>,
28 ) -> Option<ra_syntax::SyntaxNode> {
29 None
30 }
31 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
32 other
33 }
34}
35
36pub struct SubstituteTypeParams<'a, DB: HirDatabase> {
37 db: &'a DB,
38 substs: HashMap<hir::TypeParam, ast::TypeRef>,
39 previous: Box<dyn AstTransform<'a> + 'a>,
40}
41
42impl<'a, DB: HirDatabase> SubstituteTypeParams<'a, DB> {
43 pub fn for_trait_impl(
44 db: &'a DB,
45 trait_: hir::Trait,
46 impl_block: ast::ImplBlock,
47 ) -> SubstituteTypeParams<'a, DB> {
48 let substs = get_syntactic_substs(impl_block).unwrap_or_default();
49 let generic_def: hir::GenericDef = trait_.into();
50 let substs_by_param: HashMap<_, _> = generic_def
51 .params(db)
52 .into_iter()
53 // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
54 .skip(1)
55 .zip(substs.into_iter())
56 .collect();
57 return SubstituteTypeParams {
58 db,
59 substs: substs_by_param,
60 previous: Box::new(NullTransformer),
61 };
62
63 fn get_syntactic_substs(impl_block: ast::ImplBlock) -> Option<Vec<ast::TypeRef>> {
64 let target_trait = impl_block.target_trait()?;
65 let path_type = match target_trait {
66 ast::TypeRef::PathType(path) => path,
67 _ => return None,
68 };
69 let type_arg_list = path_type.path()?.segment()?.type_arg_list()?;
70 let mut result = Vec::new();
71 for type_arg in type_arg_list.type_args() {
72 let type_arg: ast::TypeArg = type_arg;
73 result.push(type_arg.type_ref()?);
74 }
75 Some(result)
76 }
77 }
78 fn get_substitution_inner(
79 &self,
80 node: InFile<&ra_syntax::SyntaxNode>,
81 ) -> Option<ra_syntax::SyntaxNode> {
82 let type_ref = ast::TypeRef::cast(node.value.clone())?;
83 let path = match &type_ref {
84 ast::TypeRef::PathType(path_type) => path_type.path()?,
85 _ => return None,
86 };
87 let analyzer = hir::SourceAnalyzer::new(self.db, node, None);
88 let resolution = analyzer.resolve_path(self.db, &path)?;
89 match resolution {
90 hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()),
91 _ => None,
92 }
93 }
94}
95
96impl<'a, DB: HirDatabase> AstTransform<'a> for SubstituteTypeParams<'a, DB> {
97 fn get_substitution(
98 &self,
99 node: InFile<&ra_syntax::SyntaxNode>,
100 ) -> Option<ra_syntax::SyntaxNode> {
101 self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node))
102 }
103 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
104 Box::new(SubstituteTypeParams { previous: other, ..self })
105 }
106}
107
108pub struct QualifyPaths<'a, DB: HirDatabase> {
109 db: &'a DB,
110 from: Option<hir::Module>,
111 previous: Box<dyn AstTransform<'a> + 'a>,
112}
113
114impl<'a, DB: HirDatabase> QualifyPaths<'a, DB> {
115 pub fn new(db: &'a DB, from: Option<hir::Module>) -> Self {
116 Self { db, from, previous: Box::new(NullTransformer) }
117 }
118
119 fn get_substitution_inner(
120 &self,
121 node: InFile<&ra_syntax::SyntaxNode>,
122 ) -> Option<ra_syntax::SyntaxNode> {
123 // FIXME handle value ns?
124 let from = self.from?;
125 let p = ast::Path::cast(node.value.clone())?;
126 if p.segment().and_then(|s| s.param_list()).is_some() {
127 // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway
128 return None;
129 }
130 let analyzer = hir::SourceAnalyzer::new(self.db, node, None);
131 let resolution = analyzer.resolve_path(self.db, &p)?;
132 match resolution {
133 PathResolution::Def(def) => {
134 let found_path = from.find_path(self.db, def)?;
135 let args = p
136 .segment()
137 .and_then(|s| s.type_arg_list())
138 .map(|arg_list| apply(self, node.with_value(arg_list)));
139 Some(make::path_with_type_arg_list(found_path.to_ast(), args).syntax().clone())
140 }
141 PathResolution::Local(_)
142 | PathResolution::TypeParam(_)
143 | PathResolution::SelfType(_) => None,
144 PathResolution::Macro(_) => None,
145 PathResolution::AssocItem(_) => None,
146 }
147 }
148}
149
150pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: InFile<N>) -> N {
151 let syntax = node.value.syntax();
152 let result = ra_syntax::algo::replace_descendants(syntax, &|element| match element {
153 ra_syntax::SyntaxElement::Node(n) => {
154 let replacement = transformer.get_substitution(node.with_value(&n))?;
155 Some(replacement.into())
156 }
157 _ => None,
158 });
159 N::cast(result).unwrap()
160}
161
162impl<'a, DB: HirDatabase> AstTransform<'a> for QualifyPaths<'a, DB> {
163 fn get_substitution(
164 &self,
165 node: InFile<&ra_syntax::SyntaxNode>,
166 ) -> Option<ra_syntax::SyntaxNode> {
167 self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node))
168 }
169 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
170 Box::new(QualifyPaths { previous: other, ..self })
171 }
172}
173
174// FIXME: It would probably be nicer if we could get this via HIR (i.e. get the
175// trait ref, and then go from the types in the substs back to the syntax)
176// FIXME: This should be a general utility (not even just for assists)
177
178// FIXME: This should be a general utility (not even just for assists)
diff --git a/crates/ra_assists/src/lib.rs b/crates/ra_assists/src/lib.rs
index 98fb20b22..712ff6f6a 100644
--- a/crates/ra_assists/src/lib.rs
+++ b/crates/ra_assists/src/lib.rs
@@ -11,6 +11,7 @@ mod marks;
11mod doc_tests; 11mod doc_tests;
12#[cfg(test)] 12#[cfg(test)]
13mod test_db; 13mod test_db;
14pub mod ast_transform;
14 15
15use hir::db::HirDatabase; 16use hir::db::HirDatabase;
16use ra_db::FileRange; 17use ra_db::FileRange;
diff --git a/crates/ra_ide/src/expand_macro.rs b/crates/ra_ide/src/expand_macro.rs
index bdbc31704..0f7b6e875 100644
--- a/crates/ra_ide/src/expand_macro.rs
+++ b/crates/ra_ide/src/expand_macro.rs
@@ -7,8 +7,7 @@ use rustc_hash::FxHashMap;
7 7
8use ra_syntax::{ 8use ra_syntax::{
9 algo::{find_node_at_offset, replace_descendants}, 9 algo::{find_node_at_offset, replace_descendants},
10 ast::{self}, 10 ast, AstNode, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxNode, WalkEvent, T,
11 AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, T,
12}; 11};
13 12
14pub struct ExpandedMacro { 13pub struct ExpandedMacro {
@@ -43,7 +42,7 @@ fn expand_macro_recur(
43 let mut expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?; 42 let mut expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?;
44 43
45 let children = expanded.descendants().filter_map(ast::MacroCall::cast); 44 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
46 let mut replaces = FxHashMap::default(); 45 let mut replaces: FxHashMap<SyntaxElement, SyntaxElement> = FxHashMap::default();
47 46
48 for child in children.into_iter() { 47 for child in children.into_iter() {
49 let node = hir::InFile::new(macro_file_id, &child); 48 let node = hir::InFile::new(macro_file_id, &child);
@@ -59,7 +58,7 @@ fn expand_macro_recur(
59 } 58 }
60 } 59 }
61 60
62 Some(replace_descendants(&expanded, &replaces)) 61 Some(replace_descendants(&expanded, &|n| replaces.get(n).cloned()))
63} 62}
64 63
65// FIXME: It would also be cool to share logic here and in the mbe tests, 64// FIXME: It would also be cool to share logic here and in the mbe tests,
diff --git a/crates/ra_syntax/src/algo.rs b/crates/ra_syntax/src/algo.rs
index 2b2b295f9..30a479f01 100644
--- a/crates/ra_syntax/src/algo.rs
+++ b/crates/ra_syntax/src/algo.rs
@@ -184,17 +184,17 @@ pub fn replace_children(
184/// to create a type-safe abstraction on top of it instead. 184/// to create a type-safe abstraction on top of it instead.
185pub fn replace_descendants( 185pub fn replace_descendants(
186 parent: &SyntaxNode, 186 parent: &SyntaxNode,
187 map: &FxHashMap<SyntaxElement, SyntaxElement>, 187 map: &impl Fn(&SyntaxElement) -> Option<SyntaxElement>,
188) -> SyntaxNode { 188) -> SyntaxNode {
189 // FIXME: this could be made much faster. 189 // FIXME: this could be made much faster.
190 let new_children = parent.children_with_tokens().map(|it| go(map, it)).collect::<Vec<_>>(); 190 let new_children = parent.children_with_tokens().map(|it| go(map, it)).collect::<Vec<_>>();
191 return with_children(parent, new_children); 191 return with_children(parent, new_children);
192 192
193 fn go( 193 fn go(
194 map: &FxHashMap<SyntaxElement, SyntaxElement>, 194 map: &impl Fn(&SyntaxElement) -> Option<SyntaxElement>,
195 element: SyntaxElement, 195 element: SyntaxElement,
196 ) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 196 ) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
197 if let Some(replacement) = map.get(&element) { 197 if let Some(replacement) = map(&element) {
198 return match replacement { 198 return match replacement {
199 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().clone()), 199 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().clone()),
200 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()), 200 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()),
diff --git a/crates/ra_syntax/src/ast/edit.rs b/crates/ra_syntax/src/ast/edit.rs
index ae5d63927..b736098ac 100644
--- a/crates/ra_syntax/src/ast/edit.rs
+++ b/crates/ra_syntax/src/ast/edit.rs
@@ -236,8 +236,8 @@ pub fn replace_descendants<N: AstNode, D: AstNode>(
236) -> N { 236) -> N {
237 let map = replacement_map 237 let map = replacement_map
238 .map(|(from, to)| (from.syntax().clone().into(), to.syntax().clone().into())) 238 .map(|(from, to)| (from.syntax().clone().into(), to.syntax().clone().into()))
239 .collect::<FxHashMap<_, _>>(); 239 .collect::<FxHashMap<SyntaxElement, _>>();
240 let new_syntax = algo::replace_descendants(parent.syntax(), &map); 240 let new_syntax = algo::replace_descendants(parent.syntax(), &|n| map.get(n).cloned());
241 N::cast(new_syntax).unwrap() 241 N::cast(new_syntax).unwrap()
242} 242}
243 243
@@ -292,7 +292,7 @@ impl IndentLevel {
292 ) 292 )
293 }) 293 })
294 .collect(); 294 .collect();
295 algo::replace_descendants(&node, &replacements) 295 algo::replace_descendants(&node, &|n| replacements.get(n).cloned())
296 } 296 }
297 297
298 pub fn decrease_indent<N: AstNode>(self, node: N) -> N { 298 pub fn decrease_indent<N: AstNode>(self, node: N) -> N {
@@ -320,7 +320,7 @@ impl IndentLevel {
320 ) 320 )
321 }) 321 })
322 .collect(); 322 .collect();
323 algo::replace_descendants(&node, &replacements) 323 algo::replace_descendants(&node, &|n| replacements.get(n).cloned())
324 } 324 }
325} 325}
326 326
diff --git a/crates/ra_syntax/src/ast/make.rs b/crates/ra_syntax/src/ast/make.rs
index 68d64a0cc..9781b748f 100644
--- a/crates/ra_syntax/src/ast/make.rs
+++ b/crates/ra_syntax/src/ast/make.rs
@@ -2,7 +2,7 @@
2//! of smaller pieces. 2//! of smaller pieces.
3use itertools::Itertools; 3use itertools::Itertools;
4 4
5use crate::{ast, AstNode, SourceFile}; 5use crate::{algo, ast, AstNode, SourceFile};
6 6
7pub fn name(text: &str) -> ast::Name { 7pub fn name(text: &str) -> ast::Name {
8 ast_from_text(&format!("mod {};", text)) 8 ast_from_text(&format!("mod {};", text))
@@ -23,7 +23,14 @@ fn path_from_text(text: &str) -> ast::Path {
23} 23}
24pub fn path_with_type_arg_list(path: ast::Path, args: Option<ast::TypeArgList>) -> ast::Path { 24pub fn path_with_type_arg_list(path: ast::Path, args: Option<ast::TypeArgList>) -> ast::Path {
25 if let Some(args) = args { 25 if let Some(args) = args {
26 ast_from_text(&format!("const X: {}{}", path.syntax(), args.syntax())) 26 let syntax = path.syntax();
27 // FIXME: remove existing type args
28 let new_syntax = algo::insert_children(
29 syntax,
30 crate::algo::InsertPosition::Last,
31 &mut Some(args).into_iter().map(|n| n.syntax().clone().into()),
32 );
33 ast::Path::cast(new_syntax).unwrap()
27 } else { 34 } else {
28 path 35 path
29 } 36 }