Skip to content

Add ide-assist: generate_documentation_from_trait #20408

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 190 additions & 0 deletions crates/ide-assists/src/handlers/generate_documentation_from_trait.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
use hir::{AsAssocItem, HasSource};
use ide_db::assists::AssistId;
use syntax::{
AstNode, NodeOrToken, SyntaxElement,
ast::{
self, AnyHasName, HasDocComments, HasName,
edit::{AstNodeEdit, IndentLevel},
make,
},
syntax_editor::Position,
};

use crate::assist_context::{AssistContext, Assists};

// Assist: generate_documentation_from_trait
//
// Generate documents from items defined in the trait.
//
// ```
// trait Foo {
// /// some docs
// fn foo(&self);
// }
// impl Foo for () {
// fn $0foo(&self) {}
// }
// ```
// ->
// ```
// trait Foo {
// /// some docs
// fn foo(&self);
// }
// impl Foo for () {
// /// some docs
// fn foo(&self) {}
// }
// ```
pub(crate) fn generate_documentation_from_trait(
acc: &mut Assists,
ctx: &AssistContext<'_>,
) -> Option<()> {
let name = ctx.find_node_at_offset::<ast::Name>()?;
let ast_func = name.syntax().parent().and_then(ast::Fn::cast)?;
if ast_func.doc_comments().next().is_some() {
return None;
}
let assoc_item = ctx.sema.to_def(&ast_func)?.as_assoc_item(ctx.db())?;
let trait_ = assoc_item.implemented_trait(ctx.db())?.source(ctx.db())?.value;
let origin_item = trait_.assoc_item_list()?.assoc_items().find(|it| {
AnyHasName::cast(it.syntax().clone())
.and_then(|it| it.name())
.is_some_and(|it| it.text() == name.text())
})?;
let _first = origin_item.doc_comments().next()?;

let comments = origin_item.doc_comments();
let indent = ast_func.indent_level();
let origin_indent = origin_item.indent_level();

acc.add(
AssistId::generate("generate_documentation_from_trait"),
"Generate a documentation from trait",
ast_func.syntax().text_range(),
|builder| {
let mut edit = builder.make_editor(ast_func.syntax());

let comments = comments
.flat_map(|doc| {
generate_docs(doc.doc_comment().unwrap_or(""), indent, origin_indent)
})
.collect();
edit.insert_all(Position::before(ast_func.syntax()), comments);

builder.add_file_edits(ctx.vfs_file_id(), edit);
},
)
}

fn generate_docs(doc: &str, indent: IndentLevel, origin_indent: IndentLevel) -> Vec<SyntaxElement> {
let ws = format!("\n{indent}");
let trim_indent = origin_indent.to_string();

doc.trim_end()
.split('\n')
.flat_map(|doc| {
let trimmed_doc = line_doc(&trim_indent, doc);
[make::tokens::doc_comment(&trimmed_doc), make::tokens::whitespace(&ws)]
})
.map(NodeOrToken::Token)
.collect()
}

fn line_doc(trim_indent: &str, line: &str) -> String {
let text = line.strip_prefix(trim_indent).unwrap_or(line.trim()).trim_end();
if text.is_empty() { "///".to_owned() } else { format!("/// {text}") }
}

#[cfg(test)]
mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};

use super::*;

#[test]
fn test_generate_documentation_from_trait() {
check_assist(
generate_documentation_from_trait,
r#"
trait Foo {
/// some docs
///
/// # Examples
/// ...
fn foo(&self);
}
impl Foo for () {
fn $0foo(&self) {}
}
"#,
r#"
trait Foo {
/// some docs
///
/// # Examples
/// ...
fn foo(&self);
}
impl Foo for () {
/// some docs
///
/// # Examples
/// ...
fn foo(&self) {}
}
"#,
);
}

#[test]
fn test_generate_documentation_from_trait_with_multi_line() {
check_assist(
generate_documentation_from_trait,
r#"
trait Foo {
/** some docs
...
*/
fn foo(&self);
}
impl Foo for () {
fn $0foo(&self) {}
}
"#,
r#"
trait Foo {
/** some docs
...
*/
fn foo(&self);
}
impl Foo for () {
/// some docs
/// ...
fn foo(&self) {}
}
"#,
);
}

#[test]
fn test_generate_documentation_from_trait_not_applicable_existing_doc() {
check_assist_not_applicable(
generate_documentation_from_trait,
r#"
trait Foo {
/// some docs
///
/// # Examples
/// ...
fn foo(&self);
}
impl Foo for () {
/// existing docs
fn $0foo(&self) {}
}
"#,
);
}
}
2 changes: 2 additions & 0 deletions crates/ide-assists/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ mod handlers {
mod generate_delegate_trait;
mod generate_deref;
mod generate_derive;
mod generate_documentation_from_trait;
mod generate_documentation_template;
mod generate_enum_is_method;
mod generate_enum_projection_method;
Expand Down Expand Up @@ -293,6 +294,7 @@ mod handlers {
generate_derive::generate_derive,
generate_documentation_template::generate_doc_example,
generate_documentation_template::generate_documentation_template,
generate_documentation_from_trait::generate_documentation_from_trait,
generate_enum_is_method::generate_enum_is_method,
generate_enum_projection_method::generate_enum_as_method,
generate_enum_projection_method::generate_enum_try_into_method,
Expand Down
26 changes: 26 additions & 0 deletions crates/ide-assists/src/tests/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1563,6 +1563,32 @@ pub fn add(a: i32, b: i32) -> i32 { a + b }
)
}

#[test]
fn doctest_generate_documentation_from_trait() {
check_doc_test(
"generate_documentation_from_trait",
r#####"
trait Foo {
/// some docs
fn foo(&self);
}
impl Foo for () {
fn $0foo(&self) {}
}
"#####,
r#####"
trait Foo {
/// some docs
fn foo(&self);
}
impl Foo for () {
/// some docs
fn foo(&self) {}
}
"#####,
)
}

#[test]
fn doctest_generate_documentation_template() {
check_doc_test(
Expand Down
2 changes: 1 addition & 1 deletion crates/syntax/src/ast/make.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1399,7 +1399,7 @@ pub mod tokens {
pub fn doc_comment(text: &str) -> SyntaxToken {
assert!(!text.trim().is_empty());
let sf = SourceFile::parse(text, Edition::CURRENT).ok().unwrap();
sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
}

pub fn literal(text: &str) -> SyntaxToken {
Expand Down
Loading