diff options
Diffstat (limited to 'crates/ide_assists/src/path_transform.rs')
-rw-r--r-- | crates/ide_assists/src/path_transform.rs | 159 |
1 files changed, 159 insertions, 0 deletions
diff --git a/crates/ide_assists/src/path_transform.rs b/crates/ide_assists/src/path_transform.rs new file mode 100644 index 000000000..6ec318c4c --- /dev/null +++ b/crates/ide_assists/src/path_transform.rs | |||
@@ -0,0 +1,159 @@ | |||
1 | //! See `PathTransform` | ||
2 | use hir::{HirDisplay, SemanticsScope}; | ||
3 | use ide_db::helpers::mod_path_to_ast; | ||
4 | use rustc_hash::FxHashMap; | ||
5 | use syntax::{ | ||
6 | ast::{self, AstNode}, | ||
7 | ted, | ||
8 | }; | ||
9 | |||
10 | /// `PathTransform` substitutes path in SyntaxNodes in bulk. | ||
11 | /// | ||
12 | /// This is mostly useful for IDE code generation. If you paste some existing | ||
13 | /// code into a new context (for example, to add method overrides to an `impl` | ||
14 | /// block), you generally want to appropriately qualify the names, and sometimes | ||
15 | /// you might want to substitute generic parameters as well: | ||
16 | /// | ||
17 | /// ``` | ||
18 | /// mod x { | ||
19 | /// pub struct A<V>; | ||
20 | /// pub trait T<U> { fn foo(&self, _: U) -> A<U>; } | ||
21 | /// } | ||
22 | /// | ||
23 | /// mod y { | ||
24 | /// use x::T; | ||
25 | /// | ||
26 | /// impl T<()> for () { | ||
27 | /// // If we invoke **Add Missing Members** here, we want to copy-paste `foo`. | ||
28 | /// // But we want a slightly-modified version of it: | ||
29 | /// fn foo(&self, _: ()) -> x::A<()> {} | ||
30 | /// } | ||
31 | /// } | ||
32 | /// ``` | ||
33 | pub(crate) struct PathTransform<'a> { | ||
34 | pub(crate) subst: (hir::Trait, ast::Impl), | ||
35 | pub(crate) target_scope: &'a SemanticsScope<'a>, | ||
36 | pub(crate) source_scope: &'a SemanticsScope<'a>, | ||
37 | } | ||
38 | |||
39 | impl<'a> PathTransform<'a> { | ||
40 | pub(crate) fn apply(&self, item: ast::AssocItem) { | ||
41 | if let Some(ctx) = self.build_ctx() { | ||
42 | ctx.apply(item) | ||
43 | } | ||
44 | } | ||
45 | fn build_ctx(&self) -> Option<Ctx<'a>> { | ||
46 | let db = self.source_scope.db; | ||
47 | let target_module = self.target_scope.module()?; | ||
48 | let source_module = self.source_scope.module()?; | ||
49 | |||
50 | let substs = get_syntactic_substs(self.subst.1.clone()).unwrap_or_default(); | ||
51 | let generic_def: hir::GenericDef = self.subst.0.into(); | ||
52 | let substs_by_param: FxHashMap<_, _> = generic_def | ||
53 | .type_params(db) | ||
54 | .into_iter() | ||
55 | // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky | ||
56 | .skip(1) | ||
57 | // The actual list of trait type parameters may be longer than the one | ||
58 | // used in the `impl` block due to trailing default type parameters. | ||
59 | // For that case we extend the `substs` with an empty iterator so we | ||
60 | // can still hit those trailing values and check if they actually have | ||
61 | // a default type. If they do, go for that type from `hir` to `ast` so | ||
62 | // the resulting change can be applied correctly. | ||
63 | .zip(substs.into_iter().map(Some).chain(std::iter::repeat(None))) | ||
64 | .filter_map(|(k, v)| match v { | ||
65 | Some(v) => Some((k, v)), | ||
66 | None => { | ||
67 | let default = k.default(db)?; | ||
68 | Some(( | ||
69 | k, | ||
70 | ast::make::ty(&default.display_source_code(db, source_module.into()).ok()?), | ||
71 | )) | ||
72 | } | ||
73 | }) | ||
74 | .collect(); | ||
75 | |||
76 | let res = Ctx { substs: substs_by_param, target_module, source_scope: self.source_scope }; | ||
77 | Some(res) | ||
78 | } | ||
79 | } | ||
80 | |||
81 | struct Ctx<'a> { | ||
82 | substs: FxHashMap<hir::TypeParam, ast::Type>, | ||
83 | target_module: hir::Module, | ||
84 | source_scope: &'a SemanticsScope<'a>, | ||
85 | } | ||
86 | |||
87 | impl<'a> Ctx<'a> { | ||
88 | fn apply(&self, item: ast::AssocItem) { | ||
89 | for event in item.syntax().preorder() { | ||
90 | let node = match event { | ||
91 | syntax::WalkEvent::Enter(_) => continue, | ||
92 | syntax::WalkEvent::Leave(it) => it, | ||
93 | }; | ||
94 | if let Some(path) = ast::Path::cast(node.clone()) { | ||
95 | self.transform_path(path); | ||
96 | } | ||
97 | } | ||
98 | } | ||
99 | fn transform_path(&self, path: ast::Path) -> Option<()> { | ||
100 | if path.qualifier().is_some() { | ||
101 | return None; | ||
102 | } | ||
103 | if path.segment().and_then(|s| s.param_list()).is_some() { | ||
104 | // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway | ||
105 | return None; | ||
106 | } | ||
107 | |||
108 | let resolution = self.source_scope.speculative_resolve(&path)?; | ||
109 | |||
110 | match resolution { | ||
111 | hir::PathResolution::TypeParam(tp) => { | ||
112 | if let Some(subst) = self.substs.get(&tp) { | ||
113 | ted::replace(path.syntax(), subst.clone_subtree().clone_for_update().syntax()) | ||
114 | } | ||
115 | } | ||
116 | hir::PathResolution::Def(def) => { | ||
117 | let found_path = | ||
118 | self.target_module.find_use_path(self.source_scope.db.upcast(), def)?; | ||
119 | let res = mod_path_to_ast(&found_path).clone_for_update(); | ||
120 | if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) { | ||
121 | if let Some(segment) = res.segment() { | ||
122 | let old = segment.get_or_create_generic_arg_list(); | ||
123 | ted::replace(old.syntax(), args.clone_subtree().syntax().clone_for_update()) | ||
124 | } | ||
125 | } | ||
126 | ted::replace(path.syntax(), res.syntax()) | ||
127 | } | ||
128 | hir::PathResolution::Local(_) | ||
129 | | hir::PathResolution::ConstParam(_) | ||
130 | | hir::PathResolution::SelfType(_) | ||
131 | | hir::PathResolution::Macro(_) | ||
132 | | hir::PathResolution::AssocItem(_) => (), | ||
133 | } | ||
134 | Some(()) | ||
135 | } | ||
136 | } | ||
137 | |||
138 | // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the | ||
139 | // trait ref, and then go from the types in the substs back to the syntax). | ||
140 | fn get_syntactic_substs(impl_def: ast::Impl) -> Option<Vec<ast::Type>> { | ||
141 | let target_trait = impl_def.trait_()?; | ||
142 | let path_type = match target_trait { | ||
143 | ast::Type::PathType(path) => path, | ||
144 | _ => return None, | ||
145 | }; | ||
146 | let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?; | ||
147 | |||
148 | let mut result = Vec::new(); | ||
149 | for generic_arg in generic_arg_list.generic_args() { | ||
150 | match generic_arg { | ||
151 | ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?), | ||
152 | ast::GenericArg::AssocTypeArg(_) | ||
153 | | ast::GenericArg::LifetimeArg(_) | ||
154 | | ast::GenericArg::ConstArg(_) => (), | ||
155 | } | ||
156 | } | ||
157 | |||
158 | Some(result) | ||
159 | } | ||