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