aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/ast_transform.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/ast_transform.rs')
-rw-r--r--crates/ra_assists/src/ast_transform.rs212
1 files changed, 0 insertions, 212 deletions
diff --git a/crates/ra_assists/src/ast_transform.rs b/crates/ra_assists/src/ast_transform.rs
deleted file mode 100644
index 15ec75c95..000000000
--- a/crates/ra_assists/src/ast_transform.rs
+++ /dev/null
@@ -1,212 +0,0 @@
1//! `AstTransformer`s are functions that replace nodes in an AST and can be easily combined.
2use rustc_hash::FxHashMap;
3
4use hir::{HirDisplay, PathResolution, SemanticsScope};
5use ra_syntax::{
6 algo::SyntaxRewriter,
7 ast::{self, AstNode},
8};
9
10pub trait AstTransform<'a> {
11 fn get_substitution(&self, node: &ra_syntax::SyntaxNode) -> 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(&self, _node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode> {
26 None
27 }
28 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
29 other
30 }
31}
32
33pub struct SubstituteTypeParams<'a> {
34 source_scope: &'a SemanticsScope<'a>,
35 substs: FxHashMap<hir::TypeParam, ast::Type>,
36 previous: Box<dyn AstTransform<'a> + 'a>,
37}
38
39impl<'a> SubstituteTypeParams<'a> {
40 pub fn for_trait_impl(
41 source_scope: &'a SemanticsScope<'a>,
42 // FIXME: there's implicit invariant that `trait_` and `source_scope` match...
43 trait_: hir::Trait,
44 impl_def: ast::Impl,
45 ) -> SubstituteTypeParams<'a> {
46 let substs = get_syntactic_substs(impl_def).unwrap_or_default();
47 let generic_def: hir::GenericDef = trait_.into();
48 let substs_by_param: FxHashMap<_, _> = generic_def
49 .params(source_scope.db)
50 .into_iter()
51 // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
52 .skip(1)
53 // The actual list of trait type parameters may be longer than the one
54 // used in the `impl` block due to trailing default type parametrs.
55 // For that case we extend the `substs` with an empty iterator so we
56 // can still hit those trailing values and check if they actually have
57 // a default type. If they do, go for that type from `hir` to `ast` so
58 // the resulting change can be applied correctly.
59 .zip(substs.into_iter().map(Some).chain(std::iter::repeat(None)))
60 .filter_map(|(k, v)| match v {
61 Some(v) => Some((k, v)),
62 None => {
63 let default = k.default(source_scope.db)?;
64 Some((
65 k,
66 ast::make::ty(
67 &default
68 .display_source_code(source_scope.db, source_scope.module()?.into())
69 .ok()?,
70 ),
71 ))
72 }
73 })
74 .collect();
75 return SubstituteTypeParams {
76 source_scope,
77 substs: substs_by_param,
78 previous: Box::new(NullTransformer),
79 };
80
81 // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the
82 // trait ref, and then go from the types in the substs back to the syntax).
83 fn get_syntactic_substs(impl_def: ast::Impl) -> Option<Vec<ast::Type>> {
84 let target_trait = impl_def.trait_()?;
85 let path_type = match target_trait {
86 ast::Type::PathType(path) => path,
87 _ => return None,
88 };
89 let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?;
90
91 let mut result = Vec::new();
92 for generic_arg in generic_arg_list.generic_args() {
93 match generic_arg {
94 ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?),
95 ast::GenericArg::AssocTypeArg(_)
96 | ast::GenericArg::LifetimeArg(_)
97 | ast::GenericArg::ConstArg(_) => (),
98 }
99 }
100
101 Some(result)
102 }
103 }
104 fn get_substitution_inner(
105 &self,
106 node: &ra_syntax::SyntaxNode,
107 ) -> Option<ra_syntax::SyntaxNode> {
108 let type_ref = ast::Type::cast(node.clone())?;
109 let path = match &type_ref {
110 ast::Type::PathType(path_type) => path_type.path()?,
111 _ => return None,
112 };
113 // FIXME: use `hir::Path::from_src` instead.
114 #[allow(deprecated)]
115 let path = hir::Path::from_ast(path)?;
116 let resolution = self.source_scope.resolve_hir_path(&path)?;
117 match resolution {
118 hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()),
119 _ => None,
120 }
121 }
122}
123
124impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> {
125 fn get_substitution(&self, node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode> {
126 self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node))
127 }
128 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
129 Box::new(SubstituteTypeParams { previous: other, ..self })
130 }
131}
132
133pub struct QualifyPaths<'a> {
134 target_scope: &'a SemanticsScope<'a>,
135 source_scope: &'a SemanticsScope<'a>,
136 previous: Box<dyn AstTransform<'a> + 'a>,
137}
138
139impl<'a> QualifyPaths<'a> {
140 pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self {
141 Self { target_scope, source_scope, previous: Box::new(NullTransformer) }
142 }
143
144 fn get_substitution_inner(
145 &self,
146 node: &ra_syntax::SyntaxNode,
147 ) -> Option<ra_syntax::SyntaxNode> {
148 // FIXME handle value ns?
149 let from = self.target_scope.module()?;
150 let p = ast::Path::cast(node.clone())?;
151 if p.segment().and_then(|s| s.param_list()).is_some() {
152 // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway
153 return None;
154 }
155 // FIXME: use `hir::Path::from_src` instead.
156 #[allow(deprecated)]
157 let hir_path = hir::Path::from_ast(p.clone());
158 let resolution = self.source_scope.resolve_hir_path(&hir_path?)?;
159 match resolution {
160 PathResolution::Def(def) => {
161 let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?;
162 let mut path = path_to_ast(found_path);
163
164 let type_args = p
165 .segment()
166 .and_then(|s| s.generic_arg_list())
167 .map(|arg_list| apply(self, arg_list));
168 if let Some(type_args) = type_args {
169 let last_segment = path.segment().unwrap();
170 path = path.with_segment(last_segment.with_type_args(type_args))
171 }
172
173 Some(path.syntax().clone())
174 }
175 PathResolution::Local(_)
176 | PathResolution::TypeParam(_)
177 | PathResolution::SelfType(_) => None,
178 PathResolution::Macro(_) => None,
179 PathResolution::AssocItem(_) => None,
180 }
181 }
182}
183
184pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N {
185 SyntaxRewriter::from_fn(|element| match element {
186 ra_syntax::SyntaxElement::Node(n) => {
187 let replacement = transformer.get_substitution(&n)?;
188 Some(replacement.into())
189 }
190 _ => None,
191 })
192 .rewrite_ast(&node)
193}
194
195impl<'a> AstTransform<'a> for QualifyPaths<'a> {
196 fn get_substitution(&self, node: &ra_syntax::SyntaxNode) -> Option<ra_syntax::SyntaxNode> {
197 self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node))
198 }
199 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
200 Box::new(QualifyPaths { previous: other, ..self })
201 }
202}
203
204pub(crate) fn path_to_ast(path: hir::ModPath) -> ast::Path {
205 let parse = ast::SourceFile::parse(&path.to_string());
206 parse
207 .tree()
208 .syntax()
209 .descendants()
210 .find_map(ast::Path::cast)
211 .unwrap_or_else(|| panic!("failed to parse path {:?}, `{}`", path, path))
212}