]> git.lizzy.rs Git - rust.git/blobdiff - crates/assists/src/utils.rs
Add getter/setter assists
[rust.git] / crates / assists / src / utils.rs
index cd80c29586a52d21a603789662195eee87dccb52..643dade238b6fbb9cfba7768286ec9bb8d778d2d 100644 (file)
@@ -5,12 +5,13 @@
 use hir::{Adt, HasSource};
 use ide_db::{helpers::SnippetCap, RootDatabase};
 use itertools::Itertools;
+use stdx::format_to;
 use syntax::{
     ast::edit::AstNodeEdit,
     ast::AttrsOwner,
     ast::NameOwner,
-    ast::{self, edit, make, ArgListOwner},
-    AstNode, Direction,
+    ast::{self, edit, make, ArgListOwner, GenericParamsOwner},
+    AstNode, Direction, SmolStr,
     SyntaxKind::*,
     SyntaxNode, TextSize, T,
 };
@@ -354,3 +355,29 @@ pub(crate) fn find_impl_block(impl_def: ast::Impl, buf: &mut String) -> Option<T
         .end();
     Some(start)
 }
+
+// Generates the surrounding `impl Type { <code> }` including type and lifetime
+// parameters
+pub(crate) fn generate_impl_text(adt: &ast::Adt, code: &str) -> String {
+    let type_params = adt.generic_param_list();
+    let mut buf = String::with_capacity(code.len());
+    buf.push_str("\n\nimpl");
+    if let Some(type_params) = &type_params {
+        format_to!(buf, "{}", type_params.syntax());
+    }
+    buf.push(' ');
+    buf.push_str(adt.name().unwrap().text());
+    if let Some(type_params) = type_params {
+        let lifetime_params = type_params
+            .lifetime_params()
+            .filter_map(|it| it.lifetime())
+            .map(|it| SmolStr::from(it.text()));
+        let type_params =
+            type_params.type_params().filter_map(|it| it.name()).map(|it| SmolStr::from(it.text()));
+        format_to!(buf, "<{}>", lifetime_params.chain(type_params).format(", "))
+    }
+
+    format_to!(buf, " {{\n{}\n}}", code);
+
+    buf
+}