1 use hir::{AsAssocItem, HasVisibility, ModuleDef, Visibility};
2 use ide_db::assists::{AssistId, AssistKind};
3 use itertools::Itertools;
4 use stdx::to_lower_snake_case;
6 ast::{self, edit::IndentLevel, HasDocComments, HasName},
10 use crate::assist_context::{AssistContext, Assists};
12 // Assist: generate_documentation_template
14 // Adds a documentation template above a function definition / declaration.
17 // pub fn my_$0func(a: i32, b: i32) -> Result<(), std::io::Error> {
28 // /// use test::my_func;
30 // /// assert_eq!(my_func(a, b), );
35 // /// This function will return an error if .
36 // pub fn my_func(a: i32, b: i32) -> Result<(), std::io::Error> {
40 pub(crate) fn generate_documentation_template(
44 let name = ctx.find_node_at_offset::<ast::Name>()?;
45 let ast_func = name.syntax().parent().and_then(ast::Fn::cast)?;
46 if is_in_trait_impl(&ast_func, ctx)
47 || !is_public(&ast_func, ctx)?
48 || ast_func.doc_comments().next().is_some()
53 let parent_syntax = ast_func.syntax();
54 let text_range = parent_syntax.text_range();
55 let indent_level = IndentLevel::from_node(&parent_syntax);
58 AssistId("generate_documentation_template", AssistKind::Generate),
59 "Generate a documentation template",
62 let mut doc_lines = Vec::new();
63 // Introduction / short function description before the sections
64 doc_lines.push(introduction_builder(&ast_func, ctx));
65 // Then come the sections
66 if let Some(mut lines) = examples_builder(&ast_func, ctx) {
67 doc_lines.push("".into());
68 doc_lines.append(&mut lines);
70 for section_builder in [panics_builder, errors_builder, safety_builder] {
71 if let Some(mut lines) = section_builder(&ast_func) {
72 doc_lines.push("".into());
73 doc_lines.append(&mut lines);
76 builder.insert(text_range.start(), documentation_from_lines(doc_lines, indent_level));
81 /// Builds an introduction, trying to be smart if the function is `::new()`
82 fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext) -> String {
83 || -> Option<String> {
84 let hir_func = ctx.sema.to_def(ast_func)?;
85 let container = hir_func.as_assoc_item(ctx.db())?.container(ctx.db());
86 if let hir::AssocItemContainer::Impl(implementation) = container {
87 let ret_ty = hir_func.ret_type(ctx.db());
88 let self_ty = implementation.self_ty(ctx.db());
90 let is_new = ast_func.name()?.to_string() == "new";
91 match is_new && ret_ty == self_ty {
92 true => Some(format!("Creates a new [`{}`].", self_type(ast_func)?)),
99 .unwrap_or_else(|| ".".into())
102 /// Builds an `# Examples` section. An option is returned to be able to manage an error in the AST.
103 fn examples_builder(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<Vec<String>> {
104 let mut lines = string_vec_from(&["# Examples", "", "```"]);
105 if is_in_trait_def(ast_func, ctx) {
106 lines.push("// Example template not implemented for trait functions".into());
108 lines.append(&mut gen_ex_template(ast_func, ctx)?)
111 lines.push("```".into());
115 /// Builds an optional `# Panics` section
116 fn panics_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
117 match can_panic(ast_func) {
118 Some(true) => Some(string_vec_from(&["# Panics", "", "Panics if ."])),
123 /// Builds an optional `# Errors` section
124 fn errors_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
125 match return_type(ast_func)?.to_string().contains("Result") {
126 true => Some(string_vec_from(&["# Errors", "", "This function will return an error if ."])),
131 /// Builds an optional `# Safety` section
132 fn safety_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
133 let is_unsafe = ast_func.unsafe_token().is_some();
135 true => Some(string_vec_from(&["# Safety", "", "."])),
140 /// Generates an example template
141 fn gen_ex_template(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<Vec<String>> {
142 let mut lines = Vec::new();
143 let is_unsafe = ast_func.unsafe_token().is_some();
144 let param_list = ast_func.param_list()?;
145 let ref_mut_params = ref_mut_params(¶m_list);
146 let self_name: Option<String> = self_name(ast_func);
148 lines.push(format!("use {};", build_path(ast_func, ctx)?));
149 lines.push("".into());
150 if let Some(self_definition) = self_definition(ast_func, self_name.as_deref()) {
151 lines.push(self_definition);
153 for param_name in &ref_mut_params {
154 lines.push(format!("let mut {} = ;", param_name))
156 // Call the function, check result
157 let function_call = function_call(ast_func, ¶m_list, self_name.as_deref(), is_unsafe)?;
158 if returns_a_value(ast_func, ctx) {
159 if count_parameters(¶m_list) < 3 {
160 lines.push(format!("assert_eq!({}, );", function_call));
162 lines.push(format!("let result = {};", function_call));
163 lines.push("assert_eq!(result, );".into());
166 lines.push(format!("{};", function_call));
168 // Check the mutated values
169 if is_ref_mut_self(ast_func) == Some(true) {
170 lines.push(format!("assert_eq!({}, );", self_name?));
172 for param_name in &ref_mut_params {
173 lines.push(format!("assert_eq!({}, );", param_name));
178 /// Checks if the function is public / exported
179 fn is_public(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<bool> {
180 let hir_func = ctx.sema.to_def(ast_func)?;
182 hir_func.visibility(ctx.db()) == Visibility::Public
183 && all_parent_mods_public(&hir_func, ctx),
187 /// Checks that all parent modules of the function are public / exported
188 fn all_parent_mods_public(hir_func: &hir::Function, ctx: &AssistContext) -> bool {
189 let mut module = hir_func.module(ctx.db());
191 if let Some(parent) = module.parent(ctx.db()) {
192 match ModuleDef::from(module).visibility(ctx.db()) {
193 Visibility::Public => module = parent,
202 /// Returns the name of the current crate
203 fn crate_name(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
204 let krate = ctx.sema.scope(&ast_func.syntax()).module()?.krate();
205 Some(krate.display_name(ctx.db())?.to_string())
208 /// `None` if function without a body; some bool to guess if function can panic
209 fn can_panic(ast_func: &ast::Fn) -> Option<bool> {
210 let body = ast_func.body()?.to_string();
211 let can_panic = body.contains("panic!(")
212 // FIXME it would be better to not match `debug_assert*!` macro invocations
213 || body.contains("assert!(")
214 || body.contains(".unwrap()")
215 || body.contains(".expect(");
219 /// Helper function to get the name that should be given to `self` arguments
220 fn self_name(ast_func: &ast::Fn) -> Option<String> {
221 self_partial_type(ast_func).map(|name| to_lower_snake_case(&name))
224 /// Heper function to get the name of the type of `self`
225 fn self_type(ast_func: &ast::Fn) -> Option<String> {
229 .find_map(ast::Impl::cast)
230 .and_then(|i| i.self_ty())
231 .map(|t| (t.to_string()))
234 /// Heper function to get the name of the type of `self` without generic arguments
235 fn self_partial_type(ast_func: &ast::Fn) -> Option<String> {
236 let mut self_type = self_type(ast_func)?;
237 if let Some(idx) = self_type.find(|c| ['<', ' '].contains(&c)) {
238 self_type.truncate(idx);
243 /// Helper function to determine if the function is in a trait implementation
244 fn is_in_trait_impl(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
247 .and_then(|hir_func| hir_func.as_assoc_item(ctx.db()))
248 .and_then(|assoc_item| assoc_item.containing_trait_impl(ctx.db()))
252 /// Helper function to determine if the function definition is in a trait definition
253 fn is_in_trait_def(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
256 .and_then(|hir_func| hir_func.as_assoc_item(ctx.db()))
257 .and_then(|assoc_item| assoc_item.containing_trait(ctx.db()))
261 /// Returns `None` if no `self` at all, `Some(true)` if there is `&mut self` else `Some(false)`
262 fn is_ref_mut_self(ast_func: &ast::Fn) -> Option<bool> {
263 let self_param = ast_func.param_list()?.self_param()?;
264 Some(self_param.mut_token().is_some() && self_param.amp_token().is_some())
267 /// Helper function to define an variable to be the `self` argument
268 fn self_definition(ast_func: &ast::Fn, self_name: Option<&str>) -> Option<String> {
269 let definition = match is_ref_mut_self(ast_func)? {
270 true => format!("let mut {} = ;", self_name?),
271 false => format!("let {} = ;", self_name?),
276 /// Helper function to determine if a parameter is `&mut`
277 fn is_a_ref_mut_param(param: &ast::Param) -> bool {
279 Some(ast::Type::RefType(param_ref)) => param_ref.mut_token().is_some(),
284 /// Helper function to build the list of `&mut` parameters
285 fn ref_mut_params(param_list: &ast::ParamList) -> Vec<String> {
288 .filter_map(|param| match is_a_ref_mut_param(¶m) {
289 // Maybe better filter the param name (to do this maybe extract a function from
290 // `arguments_from_params`?) in case of a `mut a: &mut T`. Anyway managing most (not
291 // all) cases might be enough, the goal is just to produce a template.
292 true => Some(param.pat()?.to_string()),
298 /// Helper function to build the comma-separated list of arguments of the function
299 fn arguments_from_params(param_list: &ast::ParamList) -> String {
300 let args_iter = param_list.params().map(|param| match param.pat() {
301 // To avoid `mut` in the function call (which would be a nonsense), `Pat` should not be
302 // written as is so its variants must be managed independently. Other variants (for
303 // instance `TuplePat`) could be managed later.
304 Some(ast::Pat::IdentPat(ident_pat)) => match ident_pat.name() {
305 Some(name) => match is_a_ref_mut_param(¶m) {
306 true => format!("&mut {}", name.to_string()),
307 false => name.to_string(),
309 None => "_".to_string(),
311 _ => "_".to_string(),
313 Itertools::intersperse(args_iter, ", ".to_string()).collect()
316 /// Helper function to build a function call. `None` if expected `self_name` was not provided
319 param_list: &ast::ParamList,
320 self_name: Option<&str>,
322 ) -> Option<String> {
323 let name = ast_func.name()?;
324 let arguments = arguments_from_params(¶m_list);
325 let function_call = if param_list.self_param().is_some() {
326 format!("{}.{}({})", self_name?, name, arguments)
327 } else if let Some(implementation) = self_partial_type(ast_func) {
328 format!("{}::{}({})", implementation, name, arguments)
330 format!("{}({})", name, arguments)
333 true => Some(format!("unsafe {{ {} }}", function_call)),
334 false => Some(function_call),
338 /// Helper function to count the parameters including `self`
339 fn count_parameters(param_list: &ast::ParamList) -> usize {
340 param_list.params().count() + if param_list.self_param().is_some() { 1 } else { 0 }
343 /// Helper function to transform lines of documentation into a Rust code documentation
344 fn documentation_from_lines(doc_lines: Vec<String>, indent_level: IndentLevel) -> String {
345 let mut result = String::new();
346 for doc_line in doc_lines {
347 result.push_str("///");
348 if !doc_line.is_empty() {
350 result.push_str(&doc_line);
353 result.push_str(&indent_level.to_string());
358 /// Helper function to transform an array of borrowed strings to an owned `Vec<String>`
359 fn string_vec_from(string_array: &[&str]) -> Vec<String> {
360 string_array.iter().map(|&s| s.to_owned()).collect()
363 /// Helper function to build the path of the module in the which is the node
364 fn build_path(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
365 let crate_name = crate_name(ast_func, ctx)?;
366 let leaf = self_partial_type(ast_func)
367 .or_else(|| ast_func.name().map(|n| n.to_string()))
368 .unwrap_or_else(|| "*".into());
369 let module_def: ModuleDef = ctx.sema.to_def(ast_func)?.module(ctx.db()).into();
370 match module_def.canonical_path(ctx.db()) {
371 Some(path) => Some(format!("{}::{}::{}", crate_name, path, leaf)),
372 None => Some(format!("{}::{}", crate_name, leaf)),
376 /// Helper function to get the return type of a function
377 fn return_type(ast_func: &ast::Fn) -> Option<ast::Type> {
378 ast_func.ret_type()?.ty()
381 /// Helper function to determine if the function returns some data
382 fn returns_a_value(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
385 .map(|hir_func| hir_func.ret_type(ctx.db()))
386 .map(|ret_ty| !ret_ty.is_unit() && !ret_ty.is_never())
392 use crate::tests::{check_assist, check_assist_not_applicable};
397 fn not_applicable_on_function_calls() {
398 check_assist_not_applicable(
399 generate_documentation_template,
402 fn calls_hello_world() {
410 fn not_applicable_in_trait_impl() {
411 check_assist_not_applicable(
412 generate_documentation_template,
416 impl MyTrait for MyStruct {
424 fn not_applicable_if_function_is_private() {
425 check_assist_not_applicable(generate_documentation_template, r#"fn priv$0ate() {}"#);
429 fn not_applicable_if_function_is_pub_crate() {
430 check_assist_not_applicable(
431 generate_documentation_template,
432 r#"pub(crate) fn pri$0vate() {}"#,
437 fn not_applicable_if_function_is_in_private_mod() {
438 check_assist_not_applicable(
439 generate_documentation_template,
442 pub fn pri$0vate() {}
448 fn not_applicable_if_function_is_in_pub_crate_mod() {
449 check_assist_not_applicable(
450 generate_documentation_template,
452 pub(crate) mod PrivateModule {
453 pub fn pr$0ivate() {}
459 fn not_applicable_if_function_is_in_non_public_mod_is_recursive() {
460 check_assist_not_applicable(
461 generate_documentation_template,
463 mod ParentPrivateModule {
464 pub mod PrivateModule {
465 pub fn pr$0ivate() {}
472 fn not_applicable_if_function_already_documented() {
473 check_assist_not_applicable(
474 generate_documentation_template,
476 /// Some documentation here
477 pub fn $0documented_function() {}
483 fn supports_noop_function() {
485 generate_documentation_template,
505 fn supports_a_parameter() {
507 generate_documentation_template,
509 pub fn no$0op_with_param(_a: i32) {}
517 /// use test::noop_with_param;
519 /// noop_with_param(_a);
521 pub fn noop_with_param(_a: i32) {}
527 fn detects_unsafe_function() {
529 generate_documentation_template,
531 pub unsafe fn no$0op_unsafe() {}
539 /// use test::noop_unsafe;
541 /// unsafe { noop_unsafe() };
547 pub unsafe fn noop_unsafe() {}
553 fn guesses_panic_macro_can_panic() {
555 generate_documentation_template,
557 pub fn panic$0s_if(a: bool) {
569 /// use test::panics_if;
577 pub fn panics_if(a: bool) {
587 fn guesses_assert_macro_can_panic() {
589 generate_documentation_template,
591 pub fn $0panics_if_not(a: bool) {
601 /// use test::panics_if_not;
603 /// panics_if_not(a);
609 pub fn panics_if_not(a: bool) {
617 fn guesses_unwrap_can_panic() {
619 generate_documentation_template,
621 pub fn $0panics_if_none(a: Option<()>) {
631 /// use test::panics_if_none;
633 /// panics_if_none(a);
639 pub fn panics_if_none(a: Option<()>) {
647 fn guesses_expect_can_panic() {
649 generate_documentation_template,
651 pub fn $0panics_if_none2(a: Option<()>) {
661 /// use test::panics_if_none2;
663 /// panics_if_none2(a);
669 pub fn panics_if_none2(a: Option<()>) {
677 fn checks_output_in_example() {
679 generate_documentation_template,
681 pub fn returns_a_value$0() -> i32 {
691 /// use test::returns_a_value;
693 /// assert_eq!(returns_a_value(), );
695 pub fn returns_a_value() -> i32 {
703 fn detects_result_output() {
705 generate_documentation_template,
707 pub fn returns_a_result$0() -> Result<i32, std::io::Error> {
717 /// use test::returns_a_result;
719 /// assert_eq!(returns_a_result(), );
724 /// This function will return an error if .
725 pub fn returns_a_result() -> Result<i32, std::io::Error> {
733 fn checks_ref_mut_in_example() {
735 generate_documentation_template,
737 pub fn modifies_a_value$0(a: &mut i32) {
747 /// use test::modifies_a_value;
750 /// modifies_a_value(&mut a);
753 pub fn modifies_a_value(a: &mut i32) {
761 fn stores_result_if_at_least_3_params() {
763 generate_documentation_template,
765 pub fn sum3$0(a: i32, b: i32, c: i32) -> i32 {
777 /// let result = sum3(a, b, c);
778 /// assert_eq!(result, );
780 pub fn sum3(a: i32, b: i32, c: i32) -> i32 {
788 fn supports_fn_in_mods() {
790 generate_documentation_template,
806 /// use test::a::b::noop;
818 fn supports_fn_in_impl() {
820 generate_documentation_template,
835 /// use test::MyStruct;
837 /// MyStruct::noop();
846 fn supports_fn_in_trait() {
848 generate_documentation_template,
851 fn fun$0ction_trait();
861 /// // Example template not implemented for trait functions
870 fn supports_unsafe_fn_in_trait() {
872 generate_documentation_template,
875 unsafe fn unsafe_funct$0ion_trait();
885 /// // Example template not implemented for trait functions
891 unsafe fn unsafe_function_trait();
898 fn supports_fn_in_trait_with_default_panicking() {
900 generate_documentation_template,
903 fn function_trait_with_$0default_panicking() {
915 /// // Example template not implemented for trait functions
921 fn function_trait_with_default_panicking() {
930 fn supports_fn_in_trait_returning_result() {
932 generate_documentation_template,
935 fn function_tr$0ait_returning_result() -> Result<(), std::io::Error>;
945 /// // Example template not implemented for trait functions
950 /// This function will return an error if .
951 fn function_trait_returning_result() -> Result<(), std::io::Error>;
960 generate_documentation_template,
962 #[derive(Debug, PartialEq)]
963 pub struct MyGenericStruct<T> {
966 impl<T> MyGenericStruct<T> {
967 pub fn new$0(x: T) -> MyGenericStruct<T> {
968 MyGenericStruct { x }
973 #[derive(Debug, PartialEq)]
974 pub struct MyGenericStruct<T> {
977 impl<T> MyGenericStruct<T> {
978 /// Creates a new [`MyGenericStruct<T>`].
983 /// use test::MyGenericStruct;
985 /// assert_eq!(MyGenericStruct::new(x), );
987 pub fn new(x: T) -> MyGenericStruct<T> {
988 MyGenericStruct { x }
996 fn detects_new_with_self() {
998 generate_documentation_template,
1000 #[derive(Debug, PartialEq)]
1001 pub struct MyGenericStruct2<T> {
1004 impl<T> MyGenericStruct2<T> {
1005 pub fn new$0(x: T) -> Self {
1006 MyGenericStruct2 { x }
1011 #[derive(Debug, PartialEq)]
1012 pub struct MyGenericStruct2<T> {
1015 impl<T> MyGenericStruct2<T> {
1016 /// Creates a new [`MyGenericStruct2<T>`].
1021 /// use test::MyGenericStruct2;
1023 /// assert_eq!(MyGenericStruct2::new(x), );
1025 pub fn new(x: T) -> Self {
1026 MyGenericStruct2 { x }
1034 fn supports_method_call() {
1036 generate_documentation_template,
1038 impl<T> MyGenericStruct<T> {
1039 pub fn co$0nsume(self) {}
1043 impl<T> MyGenericStruct<T> {
1049 /// use test::MyGenericStruct;
1051 /// let my_generic_struct = ;
1052 /// my_generic_struct.consume();
1054 pub fn consume(self) {}
1061 fn checks_modified_self_param() {
1063 generate_documentation_template,
1065 impl<T> MyGenericStruct<T> {
1066 pub fn modi$0fy(&mut self, new_value: T) {
1072 impl<T> MyGenericStruct<T> {
1078 /// use test::MyGenericStruct;
1080 /// let mut my_generic_struct = ;
1081 /// my_generic_struct.modify(new_value);
1082 /// assert_eq!(my_generic_struct, );
1084 pub fn modify(&mut self, new_value: T) {