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 generic_def: hir::GenericDef,
36 substs: Vec<ast::Type>,
37 target_scope: &'a SemanticsScope<'a>,
38 source_scope: &'a SemanticsScope<'a>,
41 impl<'a> PathTransform<'a> {
43 target_scope: &'a SemanticsScope<'a>,
44 source_scope: &'a SemanticsScope<'a>,
47 ) -> PathTransform<'a> {
51 generic_def: trait_.into(),
52 substs: get_syntactic_substs(impl_).unwrap_or_default(),
57 target_scope: &'a SemanticsScope<'a>,
58 source_scope: &'a SemanticsScope<'a>,
59 function: hir::Function,
60 generic_arg_list: ast::GenericArgList,
61 ) -> PathTransform<'a> {
65 generic_def: function.into(),
66 substs: get_type_args_from_arg_list(generic_arg_list).unwrap_or_default(),
70 pub fn apply(&self, syntax: &SyntaxNode) {
71 if let Some(ctx) = self.build_ctx() {
76 fn build_ctx(&self) -> Option<Ctx<'a>> {
77 let db = self.source_scope.db;
78 let target_module = self.target_scope.module()?;
79 let source_module = self.source_scope.module()?;
80 let skip = match self.generic_def {
81 // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
82 hir::GenericDef::Trait(_) => 1,
85 let substs_by_param: FxHashMap<_, _> = self
90 // The actual list of trait type parameters may be longer than the one
91 // used in the `impl` block due to trailing default type parameters.
92 // For that case we extend the `substs` with an empty iterator so we
93 // can still hit those trailing values and check if they actually have
94 // a default type. If they do, go for that type from `hir` to `ast` so
95 // the resulting change can be applied correctly.
96 .zip(self.substs.iter().map(Some).chain(std::iter::repeat(None)))
97 .filter_map(|(k, v)| match v {
98 Some(v) => Some((k, v.clone())),
100 let default = k.default(db)?;
103 ast::make::ty(&default.display_source_code(db, source_module.into()).ok()?),
108 let res = Ctx { substs: substs_by_param, target_module, source_scope: self.source_scope };
114 substs: FxHashMap<hir::TypeParam, ast::Type>,
115 target_module: hir::Module,
116 source_scope: &'a SemanticsScope<'a>,
120 fn apply(&self, item: &SyntaxNode) {
121 for event in item.preorder() {
122 let node = match event {
123 syntax::WalkEvent::Enter(_) => continue,
124 syntax::WalkEvent::Leave(it) => it,
126 if let Some(path) = ast::Path::cast(node.clone()) {
127 self.transform_path(path);
131 fn transform_path(&self, path: ast::Path) -> Option<()> {
132 if path.qualifier().is_some() {
135 if path.segment().map_or(false, |s| {
136 s.param_list().is_some() || (s.self_token().is_some() && path.parent_path().is_none())
138 // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway
139 // don't try to qualify sole `self` either, they are usually locals, but are returned as modules due to namespace clashing
143 let resolution = self.source_scope.speculative_resolve(&path)?;
146 hir::PathResolution::TypeParam(tp) => {
147 if let Some(subst) = self.substs.get(&tp) {
148 ted::replace(path.syntax(), subst.clone_subtree().clone_for_update().syntax())
151 hir::PathResolution::Def(def) => {
153 self.target_module.find_use_path(self.source_scope.db.upcast(), def)?;
154 let res = mod_path_to_ast(&found_path).clone_for_update();
155 if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) {
156 if let Some(segment) = res.segment() {
157 let old = segment.get_or_create_generic_arg_list();
158 ted::replace(old.syntax(), args.clone_subtree().syntax().clone_for_update())
161 ted::replace(path.syntax(), res.syntax())
163 hir::PathResolution::Local(_)
164 | hir::PathResolution::ConstParam(_)
165 | hir::PathResolution::SelfType(_)
166 | hir::PathResolution::Macro(_)
167 | hir::PathResolution::AssocItem(_)
168 | hir::PathResolution::BuiltinAttr(_)
169 | hir::PathResolution::ToolModule(_) => (),
175 // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the
176 // trait ref, and then go from the types in the substs back to the syntax).
177 fn get_syntactic_substs(impl_def: ast::Impl) -> Option<Vec<ast::Type>> {
178 let target_trait = impl_def.trait_()?;
179 let path_type = match target_trait {
180 ast::Type::PathType(path) => path,
183 let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?;
185 get_type_args_from_arg_list(generic_arg_list)
188 fn get_type_args_from_arg_list(generic_arg_list: ast::GenericArgList) -> Option<Vec<ast::Type>> {
189 let mut result = Vec::new();
190 for generic_arg in generic_arg_list.generic_args() {
191 if let ast::GenericArg::TypeArg(type_arg) = generic_arg {
192 result.push(type_arg.ty()?)