1 //! `AstTransformer`s are functions that replace nodes in an AST and can be easily combined.
2 use hir::{HirDisplay, PathResolution, SemanticsScope};
3 use ide_db::helpers::mod_path_to_ast;
4 use rustc_hash::FxHashMap;
11 pub fn apply<'a, N: AstNode>(transformer: &dyn AstTransform<'a>, node: N) -> N {
12 SyntaxRewriter::from_fn(|element| match element {
13 syntax::SyntaxElement::Node(n) => {
14 let replacement = transformer.get_substitution(&n, transformer)?;
15 Some(replacement.into())
22 /// `AstTransform` helps with applying bulk transformations to syntax nodes.
24 /// This is mostly useful for IDE code generation. If you paste some existing
25 /// code into a new context (for example, to add method overrides to an `impl`
26 /// block), you generally want to appropriately qualify the names, and sometimes
27 /// you might want to substitute generic parameters as well:
32 /// pub trait T<U> { fn foo(&self, _: U) -> A; }
38 /// impl T<()> for () {
39 /// // If we invoke **Add Missing Members** here, we want to copy-paste `foo`.
40 /// // But we want a slightly-modified version of it:
41 /// fn foo(&self, _: ()) -> x::A {}
46 /// So, a single `AstTransform` describes such function from `SyntaxNode` to
47 /// `SyntaxNode`. Note that the API here is a bit too high-order and high-brow.
48 /// We'd want to somehow express this concept simpler, but so far nobody got to
50 pub trait AstTransform<'a> {
54 recur: &dyn AstTransform<'a>,
55 ) -> Option<SyntaxNode>;
57 fn or<T: AstTransform<'a> + 'a>(self, other: T) -> Box<dyn AstTransform<'a> + 'a>
61 Box::new(Or(Box::new(self), Box::new(other)))
65 struct Or<'a>(Box<dyn AstTransform<'a> + 'a>, Box<dyn AstTransform<'a> + 'a>);
67 impl<'a> AstTransform<'a> for Or<'a> {
71 recur: &dyn AstTransform<'a>,
72 ) -> Option<SyntaxNode> {
73 self.0.get_substitution(node, recur).or_else(|| self.1.get_substitution(node, recur))
77 pub struct SubstituteTypeParams<'a> {
78 source_scope: &'a SemanticsScope<'a>,
79 substs: FxHashMap<hir::TypeParam, ast::Type>,
82 impl<'a> SubstituteTypeParams<'a> {
83 pub fn for_trait_impl(
84 source_scope: &'a SemanticsScope<'a>,
85 // FIXME: there's implicit invariant that `trait_` and `source_scope` match...
88 ) -> SubstituteTypeParams<'a> {
89 let substs = get_syntactic_substs(impl_def).unwrap_or_default();
90 let generic_def: hir::GenericDef = trait_.into();
91 let substs_by_param: FxHashMap<_, _> = generic_def
92 .type_params(source_scope.db)
94 // this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
96 // The actual list of trait type parameters may be longer than the one
97 // used in the `impl` block due to trailing default type parameters.
98 // For that case we extend the `substs` with an empty iterator so we
99 // can still hit those trailing values and check if they actually have
100 // a default type. If they do, go for that type from `hir` to `ast` so
101 // the resulting change can be applied correctly.
102 .zip(substs.into_iter().map(Some).chain(std::iter::repeat(None)))
103 .filter_map(|(k, v)| match v {
104 Some(v) => Some((k, v)),
106 let default = k.default(source_scope.db)?;
111 .display_source_code(source_scope.db, source_scope.module()?.into())
118 return SubstituteTypeParams { source_scope, substs: substs_by_param };
120 // FIXME: It would probably be nicer if we could get this via HIR (i.e. get the
121 // trait ref, and then go from the types in the substs back to the syntax).
122 fn get_syntactic_substs(impl_def: ast::Impl) -> Option<Vec<ast::Type>> {
123 let target_trait = impl_def.trait_()?;
124 let path_type = match target_trait {
125 ast::Type::PathType(path) => path,
128 let generic_arg_list = path_type.path()?.segment()?.generic_arg_list()?;
130 let mut result = Vec::new();
131 for generic_arg in generic_arg_list.generic_args() {
133 ast::GenericArg::TypeArg(type_arg) => result.push(type_arg.ty()?),
134 ast::GenericArg::AssocTypeArg(_)
135 | ast::GenericArg::LifetimeArg(_)
136 | ast::GenericArg::ConstArg(_) => (),
145 impl<'a> AstTransform<'a> for SubstituteTypeParams<'a> {
149 _recur: &dyn AstTransform<'a>,
150 ) -> Option<SyntaxNode> {
151 let type_ref = ast::Type::cast(node.clone())?;
152 let path = match &type_ref {
153 ast::Type::PathType(path_type) => path_type.path()?,
156 let resolution = self.source_scope.speculative_resolve(&path)?;
158 hir::PathResolution::TypeParam(tp) => Some(self.substs.get(&tp)?.syntax().clone()),
164 pub struct QualifyPaths<'a> {
165 target_scope: &'a SemanticsScope<'a>,
166 source_scope: &'a SemanticsScope<'a>,
169 impl<'a> QualifyPaths<'a> {
170 pub fn new(target_scope: &'a SemanticsScope<'a>, source_scope: &'a SemanticsScope<'a>) -> Self {
171 Self { target_scope, source_scope }
175 impl<'a> AstTransform<'a> for QualifyPaths<'a> {
179 recur: &dyn AstTransform<'a>,
180 ) -> Option<SyntaxNode> {
181 // FIXME handle value ns?
182 let from = self.target_scope.module()?;
183 let p = ast::Path::cast(node.clone())?;
184 if p.segment().and_then(|s| s.param_list()).is_some() {
185 // don't try to qualify `Fn(Foo) -> Bar` paths, they are in prelude anyway
188 let resolution = self.source_scope.speculative_resolve(&p)?;
190 PathResolution::Def(def) => {
191 let found_path = from.find_use_path(self.source_scope.db.upcast(), def)?;
192 let mut path = mod_path_to_ast(&found_path);
196 .and_then(|s| s.generic_arg_list())
197 .map(|arg_list| apply(recur, arg_list));
198 if let Some(type_args) = type_args {
199 let last_segment = path.segment().unwrap();
200 path = path.with_segment(last_segment.with_generic_args(type_args))
203 Some(path.syntax().clone())
205 PathResolution::Local(_)
206 | PathResolution::TypeParam(_)
207 | PathResolution::SelfType(_)
208 | PathResolution::ConstParam(_) => None,
209 PathResolution::Macro(_) => None,
210 PathResolution::AssocItem(_) => None,