aboutsummaryrefslogtreecommitdiff
path: root/crates/assists/src/ast_transform.rs
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2020-08-13 16:33:38 +0100
committerAleksey Kladov <[email protected]>2020-08-13 16:33:38 +0100
commitfc34403018079ea053f26d0a31b7517053c7dd8c (patch)
tree500d7c2ec2179309be12a063634cb6a77c9af845 /crates/assists/src/ast_transform.rs
parentae3abd6e575940eb1221acf26c09e96352f052fa (diff)
Rename ra_assists -> assists
Diffstat (limited to 'crates/assists/src/ast_transform.rs')
-rw-r--r--crates/assists/src/ast_transform.rs206
1 files changed, 206 insertions, 0 deletions
diff --git a/crates/assists/src/ast_transform.rs b/crates/assists/src/ast_transform.rs
new file mode 100644
index 000000000..4c41c16d8
--- /dev/null
+++ b/crates/assists/src/ast_transform.rs
@@ -0,0 +1,206 @@
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 syntax::{
6 algo::SyntaxRewriter,
7 ast::{self, AstNode},
8};
9
10pub trait AstTransform<'a> {
11 fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<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: &syntax::SyntaxNode) -> Option<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 parameters.
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(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> {
105 let type_ref = ast::Type::cast(node.clone())?;
106 let path = match &type_ref {
107 ast::Type::PathType(path_type) => path_type.path()?,
108 _ => return None,
109 };
110 // FIXME: use `hir::Path::from_src` instead.
111 #[allow(deprecated)]
112 let path = hir::Path::from_ast(path)?;
113 let resolution = self.source_scope.resolve_hir_path(&path)?;
114 match resolution {
115 hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()),
116 _ => None,
117 }
118 }
119}
120
121impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> {
122 fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> {
123 self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node))
124 }
125 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
126 Box::new(SubstituteTypeParams { previous: other, ..self })
127 }
128}
129
130pub struct QualifyPaths<'a> {
131 target_scope: &'a SemanticsScope<'a>,
132 source_scope: &'a SemanticsScope<'a>,
133 previous: Box<dyn AstTransform<'a> + 'a>,
134}
135
136impl<'a> QualifyPaths<'a> {
137 pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self {
138 Self { target_scope, source_scope, previous: Box::new(NullTransformer) }
139 }
140
141 fn get_substitution_inner(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> {
142 // FIXME handle value ns?
143 let from = self.target_scope.module()?;
144 let p = ast::Path::cast(node.clone())?;
145 if p.segment().and_then(|s| s.param_list()).is_some() {
146 // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway
147 return None;
148 }
149 // FIXME: use `hir::Path::from_src` instead.
150 #[allow(deprecated)]
151 let hir_path = hir::Path::from_ast(p.clone());
152 let resolution = self.source_scope.resolve_hir_path(&hir_path?)?;
153 match resolution {
154 PathResolution::Def(def) => {
155 let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?;
156 let mut path = path_to_ast(found_path);
157
158 let type_args = p
159 .segment()
160 .and_then(|s| s.generic_arg_list())
161 .map(|arg_list| apply(self, arg_list));
162 if let Some(type_args) = type_args {
163 let last_segment = path.segment().unwrap();
164 path = path.with_segment(last_segment.with_type_args(type_args))
165 }
166
167 Some(path.syntax().clone())
168 }
169 PathResolution::Local(_)
170 | PathResolution::TypeParam(_)
171 | PathResolution::SelfType(_) => None,
172 PathResolution::Macro(_) => None,
173 PathResolution::AssocItem(_) => None,
174 }
175 }
176}
177
178pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N {
179 SyntaxRewriter::from_fn(|element| match element {
180 syntax::SyntaxElement::Node(n) => {
181 let replacement = transformer.get_substitution(&n)?;
182 Some(replacement.into())
183 }
184 _ => None,
185 })
186 .rewrite_ast(&node)
187}
188
189impl<'a> AstTransform<'a> for QualifyPaths<'a> {
190 fn get_substitution(&self, node: &syntax::SyntaxNode) -> Option<syntax::SyntaxNode> {
191 self.get_substitution_inner(node).or_else(|| self.previous.get_substitution(node))
192 }
193 fn chain_before(self, other: Box<dyn AstTransform<'a> + 'a>) -> Box<dyn AstTransform<'a> + 'a> {
194 Box::new(QualifyPaths { previous: other, ..self })
195 }
196}
197
198pub(crate) fn path_to_ast(path: hir::ModPath) -> ast::Path {
199 let parse = ast::SourceFile::parse(&path.to_string());
200 parse
201 .tree()
202 .syntax()
203 .descendants()
204 .find_map(ast::Path::cast)
205 .unwrap_or_else(|| panic!("failed to parse path {:?}, `{}`", path, path))
206}