1 //! See [`PathTransform`].
3 use crate::helpers::mod_path_to_ast;
4 use hir::{HirDisplay, SemanticsScope};
5 use rustc_hash::FxHashMap;
11 /// `PathTransform` substitutes path in SyntaxNodes in bulk.
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:
21 /// pub trait T<U> { fn foo(&self, _: U) -> A<U>; }
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<()> {}
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>,
40 impl<'a> PathTransform<'a> {
41 pub fn apply(&self, item: ast::AssocItem) {
42 if let Some(ctx) = self.build_ctx() {
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()?;
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
56 // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
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)),
68 let default = k.default(db)?;
71 ast::make::ty(&default.display_source_code(db, source_module.into()).ok()?),
77 let res = Ctx { substs: substs_by_param, target_module, source_scope: self.source_scope };
83 substs: FxHashMap<hir::TypeParam, ast::Type>,
84 target_module: hir::Module,
85 source_scope: &'a SemanticsScope<'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,
95 if let Some(path) = ast::Path::cast(node.clone()) {
96 self.transform_path(path);
100 fn transform_path(&self, path: ast::Path) -> Option<()> {
101 if path.qualifier().is_some() {
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
109 let resolution = self.source_scope.speculative_resolve(&path)?;
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())
117 hir::PathResolution::Def(def) => {
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())
127 ted::replace(path.syntax(), res.syntax())
129 hir::PathResolution::Local(_)
130 | hir::PathResolution::ConstParam(_)
131 | hir::PathResolution::SelfType(_)
132 | hir::PathResolution::Macro(_)
133 | hir::PathResolution::AssocItem(_) => (),
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,
147 let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?;
149 let mut result = Vec::new();
150 for generic_arg in generic_arg_list.generic_args() {
152 ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?),
153 ast::GenericArg::AssocTypeArg(_)
154 | ast::GenericArg::LifetimeArg(_)
155 | ast::GenericArg::ConstArg(_) => (),