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 // Introduction / short function description before the sections
63 let mut doc_lines = vec![introduction_builder(&ast_func, ctx)];
64 // Then come the sections
65 if let Some(mut lines) = examples_builder(&ast_func, ctx) {
66 doc_lines.push("".into());
67 doc_lines.append(&mut lines);
69 for section_builder in [panics_builder, errors_builder, safety_builder] {
70 if let Some(mut lines) = section_builder(&ast_func) {
71 doc_lines.push("".into());
72 doc_lines.append(&mut lines);
75 builder.insert(text_range.start(), documentation_from_lines(doc_lines, indent_level));
80 /// Builds an introduction, trying to be smart if the function is `::new()`
81 fn introduction_builder(ast_func: &ast::Fn, ctx: &AssistContext) -> String {
82 || -> Option<String> {
83 let hir_func = ctx.sema.to_def(ast_func)?;
84 let container = hir_func.as_assoc_item(ctx.db())?.container(ctx.db());
85 if let hir::AssocItemContainer::Impl(implementation) = container {
86 let ret_ty = hir_func.ret_type(ctx.db());
87 let self_ty = implementation.self_ty(ctx.db());
89 let is_new = ast_func.name()?.to_string() == "new";
90 match is_new && ret_ty == self_ty {
91 true => Some(format!("Creates a new [`{}`].", self_type(ast_func)?)),
98 .unwrap_or_else(|| ".".into())
101 /// Builds an `# Examples` section. An option is returned to be able to manage an error in the AST.
102 fn examples_builder(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<Vec<String>> {
103 let mut lines = string_vec_from(&["# Examples", "", "```"]);
104 if is_in_trait_def(ast_func, ctx) {
105 lines.push("// Example template not implemented for trait functions".into());
107 lines.append(&mut gen_ex_template(ast_func, ctx)?)
110 lines.push("```".into());
114 /// Builds an optional `# Panics` section
115 fn panics_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
116 match can_panic(ast_func) {
117 Some(true) => Some(string_vec_from(&["# Panics", "", "Panics if ."])),
122 /// Builds an optional `# Errors` section
123 fn errors_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
124 match return_type(ast_func)?.to_string().contains("Result") {
125 true => Some(string_vec_from(&["# Errors", "", "This function will return an error if ."])),
130 /// Builds an optional `# Safety` section
131 fn safety_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
132 let is_unsafe = ast_func.unsafe_token().is_some();
134 true => Some(string_vec_from(&["# Safety", "", "."])),
139 /// Generates an example template
140 fn gen_ex_template(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<Vec<String>> {
141 let mut lines = Vec::new();
142 let is_unsafe = ast_func.unsafe_token().is_some();
143 let param_list = ast_func.param_list()?;
144 let ref_mut_params = ref_mut_params(¶m_list);
145 let self_name: Option<String> = self_name(ast_func);
147 lines.push(format!("use {};", build_path(ast_func, ctx)?));
148 lines.push("".into());
149 if let Some(self_definition) = self_definition(ast_func, self_name.as_deref()) {
150 lines.push(self_definition);
152 for param_name in &ref_mut_params {
153 lines.push(format!("let mut {} = ;", param_name))
155 // Call the function, check result
156 let function_call = function_call(ast_func, ¶m_list, self_name.as_deref(), is_unsafe)?;
157 if returns_a_value(ast_func, ctx) {
158 if count_parameters(¶m_list) < 3 {
159 lines.push(format!("assert_eq!({}, );", function_call));
161 lines.push(format!("let result = {};", function_call));
162 lines.push("assert_eq!(result, );".into());
165 lines.push(format!("{};", function_call));
167 // Check the mutated values
168 if is_ref_mut_self(ast_func) == Some(true) {
169 lines.push(format!("assert_eq!({}, );", self_name?));
171 for param_name in &ref_mut_params {
172 lines.push(format!("assert_eq!({}, );", param_name));
177 /// Checks if the function is public / exported
178 fn is_public(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<bool> {
179 let hir_func = ctx.sema.to_def(ast_func)?;
181 hir_func.visibility(ctx.db()) == Visibility::Public
182 && all_parent_mods_public(&hir_func, ctx),
186 /// Checks that all parent modules of the function are public / exported
187 fn all_parent_mods_public(hir_func: &hir::Function, ctx: &AssistContext) -> bool {
188 let mut module = hir_func.module(ctx.db());
190 if let Some(parent) = module.parent(ctx.db()) {
191 match ModuleDef::from(module).visibility(ctx.db()) {
192 Visibility::Public => module = parent,
201 /// Returns the name of the current crate
202 fn crate_name(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
203 let krate = ctx.sema.scope(&ast_func.syntax()).module()?.krate();
204 Some(krate.display_name(ctx.db())?.to_string())
207 /// `None` if function without a body; some bool to guess if function can panic
208 fn can_panic(ast_func: &ast::Fn) -> Option<bool> {
209 let body = ast_func.body()?.to_string();
210 let can_panic = body.contains("panic!(")
211 // FIXME it would be better to not match `debug_assert*!` macro invocations
212 || body.contains("assert!(")
213 || body.contains(".unwrap()")
214 || body.contains(".expect(");
218 /// Helper function to get the name that should be given to `self` arguments
219 fn self_name(ast_func: &ast::Fn) -> Option<String> {
220 self_partial_type(ast_func).map(|name| to_lower_snake_case(&name))
223 /// Heper function to get the name of the type of `self`
224 fn self_type(ast_func: &ast::Fn) -> Option<String> {
228 .find_map(ast::Impl::cast)
229 .and_then(|i| i.self_ty())
230 .map(|t| (t.to_string()))
233 /// Heper function to get the name of the type of `self` without generic arguments
234 fn self_partial_type(ast_func: &ast::Fn) -> Option<String> {
235 let mut self_type = self_type(ast_func)?;
236 if let Some(idx) = self_type.find(|c| ['<', ' '].contains(&c)) {
237 self_type.truncate(idx);
242 /// Helper function to determine if the function is in a trait implementation
243 fn is_in_trait_impl(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
246 .and_then(|hir_func| hir_func.as_assoc_item(ctx.db()))
247 .and_then(|assoc_item| assoc_item.containing_trait_impl(ctx.db()))
251 /// Helper function to determine if the function definition is in a trait definition
252 fn is_in_trait_def(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
255 .and_then(|hir_func| hir_func.as_assoc_item(ctx.db()))
256 .and_then(|assoc_item| assoc_item.containing_trait(ctx.db()))
260 /// Returns `None` if no `self` at all, `Some(true)` if there is `&mut self` else `Some(false)`
261 fn is_ref_mut_self(ast_func: &ast::Fn) -> Option<bool> {
262 let self_param = ast_func.param_list()?.self_param()?;
263 Some(self_param.mut_token().is_some() && self_param.amp_token().is_some())
266 /// Helper function to define an variable to be the `self` argument
267 fn self_definition(ast_func: &ast::Fn, self_name: Option<&str>) -> Option<String> {
268 let definition = match is_ref_mut_self(ast_func)? {
269 true => format!("let mut {} = ;", self_name?),
270 false => format!("let {} = ;", self_name?),
275 /// Helper function to determine if a parameter is `&mut`
276 fn is_a_ref_mut_param(param: &ast::Param) -> bool {
278 Some(ast::Type::RefType(param_ref)) => param_ref.mut_token().is_some(),
283 /// Helper function to build the list of `&mut` parameters
284 fn ref_mut_params(param_list: &ast::ParamList) -> Vec<String> {
287 .filter_map(|param| match is_a_ref_mut_param(¶m) {
288 // Maybe better filter the param name (to do this maybe extract a function from
289 // `arguments_from_params`?) in case of a `mut a: &mut T`. Anyway managing most (not
290 // all) cases might be enough, the goal is just to produce a template.
291 true => Some(param.pat()?.to_string()),
297 /// Helper function to build the comma-separated list of arguments of the function
298 fn arguments_from_params(param_list: &ast::ParamList) -> String {
299 let args_iter = param_list.params().map(|param| match param.pat() {
300 // To avoid `mut` in the function call (which would be a nonsense), `Pat` should not be
301 // written as is so its variants must be managed independently. Other variants (for
302 // instance `TuplePat`) could be managed later.
303 Some(ast::Pat::IdentPat(ident_pat)) => match ident_pat.name() {
304 Some(name) => match is_a_ref_mut_param(¶m) {
305 true => format!("&mut {}", name),
306 false => name.to_string(),
308 None => "_".to_string(),
310 _ => "_".to_string(),
312 Itertools::intersperse(args_iter, ", ".to_string()).collect()
315 /// Helper function to build a function call. `None` if expected `self_name` was not provided
318 param_list: &ast::ParamList,
319 self_name: Option<&str>,
321 ) -> Option<String> {
322 let name = ast_func.name()?;
323 let arguments = arguments_from_params(¶m_list);
324 let function_call = if param_list.self_param().is_some() {
325 format!("{}.{}({})", self_name?, name, arguments)
326 } else if let Some(implementation) = self_partial_type(ast_func) {
327 format!("{}::{}({})", implementation, name, arguments)
329 format!("{}({})", name, arguments)
332 true => Some(format!("unsafe {{ {} }}", function_call)),
333 false => Some(function_call),
337 /// Helper function to count the parameters including `self`
338 fn count_parameters(param_list: &ast::ParamList) -> usize {
339 param_list.params().count() + if param_list.self_param().is_some() { 1 } else { 0 }
342 /// Helper function to transform lines of documentation into a Rust code documentation
343 fn documentation_from_lines(doc_lines: Vec<String>, indent_level: IndentLevel) -> String {
344 let mut result = String::new();
345 for doc_line in doc_lines {
346 result.push_str("///");
347 if !doc_line.is_empty() {
349 result.push_str(&doc_line);
352 result.push_str(&indent_level.to_string());
357 /// Helper function to transform an array of borrowed strings to an owned `Vec<String>`
358 fn string_vec_from(string_array: &[&str]) -> Vec<String> {
359 string_array.iter().map(|&s| s.to_owned()).collect()
362 /// Helper function to build the path of the module in the which is the node
363 fn build_path(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
364 let crate_name = crate_name(ast_func, ctx)?;
365 let leaf = self_partial_type(ast_func)
366 .or_else(|| ast_func.name().map(|n| n.to_string()))
367 .unwrap_or_else(|| "*".into());
368 let module_def: ModuleDef = ctx.sema.to_def(ast_func)?.module(ctx.db()).into();
369 match module_def.canonical_path(ctx.db()) {
370 Some(path) => Some(format!("{}::{}::{}", crate_name, path, leaf)),
371 None => Some(format!("{}::{}", crate_name, leaf)),
375 /// Helper function to get the return type of a function
376 fn return_type(ast_func: &ast::Fn) -> Option<ast::Type> {
377 ast_func.ret_type()?.ty()
380 /// Helper function to determine if the function returns some data
381 fn returns_a_value(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
384 .map(|hir_func| hir_func.ret_type(ctx.db()))
385 .map(|ret_ty| !ret_ty.is_unit() && !ret_ty.is_never())
391 use crate::tests::{check_assist, check_assist_not_applicable};
396 fn not_applicable_on_function_calls() {
397 check_assist_not_applicable(
398 generate_documentation_template,
401 fn calls_hello_world() {
409 fn not_applicable_in_trait_impl() {
410 check_assist_not_applicable(
411 generate_documentation_template,
415 impl MyTrait for MyStruct {
423 fn not_applicable_if_function_is_private() {
424 check_assist_not_applicable(generate_documentation_template, r#"fn priv$0ate() {}"#);
428 fn not_applicable_if_function_is_pub_crate() {
429 check_assist_not_applicable(
430 generate_documentation_template,
431 r#"pub(crate) fn pri$0vate() {}"#,
436 fn not_applicable_if_function_is_in_private_mod() {
437 check_assist_not_applicable(
438 generate_documentation_template,
441 pub fn pri$0vate() {}
447 fn not_applicable_if_function_is_in_pub_crate_mod() {
448 check_assist_not_applicable(
449 generate_documentation_template,
451 pub(crate) mod PrivateModule {
452 pub fn pr$0ivate() {}
458 fn not_applicable_if_function_is_in_non_public_mod_is_recursive() {
459 check_assist_not_applicable(
460 generate_documentation_template,
462 mod ParentPrivateModule {
463 pub mod PrivateModule {
464 pub fn pr$0ivate() {}
471 fn not_applicable_if_function_already_documented() {
472 check_assist_not_applicable(
473 generate_documentation_template,
475 /// Some documentation here
476 pub fn $0documented_function() {}
482 fn supports_noop_function() {
484 generate_documentation_template,
504 fn supports_a_parameter() {
506 generate_documentation_template,
508 pub fn no$0op_with_param(_a: i32) {}
516 /// use test::noop_with_param;
518 /// noop_with_param(_a);
520 pub fn noop_with_param(_a: i32) {}
526 fn detects_unsafe_function() {
528 generate_documentation_template,
530 pub unsafe fn no$0op_unsafe() {}
538 /// use test::noop_unsafe;
540 /// unsafe { noop_unsafe() };
546 pub unsafe fn noop_unsafe() {}
552 fn guesses_panic_macro_can_panic() {
554 generate_documentation_template,
556 pub fn panic$0s_if(a: bool) {
568 /// use test::panics_if;
576 pub fn panics_if(a: bool) {
586 fn guesses_assert_macro_can_panic() {
588 generate_documentation_template,
590 pub fn $0panics_if_not(a: bool) {
600 /// use test::panics_if_not;
602 /// panics_if_not(a);
608 pub fn panics_if_not(a: bool) {
616 fn guesses_unwrap_can_panic() {
618 generate_documentation_template,
620 pub fn $0panics_if_none(a: Option<()>) {
630 /// use test::panics_if_none;
632 /// panics_if_none(a);
638 pub fn panics_if_none(a: Option<()>) {
646 fn guesses_expect_can_panic() {
648 generate_documentation_template,
650 pub fn $0panics_if_none2(a: Option<()>) {
660 /// use test::panics_if_none2;
662 /// panics_if_none2(a);
668 pub fn panics_if_none2(a: Option<()>) {
676 fn checks_output_in_example() {
678 generate_documentation_template,
680 pub fn returns_a_value$0() -> i32 {
690 /// use test::returns_a_value;
692 /// assert_eq!(returns_a_value(), );
694 pub fn returns_a_value() -> i32 {
702 fn detects_result_output() {
704 generate_documentation_template,
706 pub fn returns_a_result$0() -> Result<i32, std::io::Error> {
716 /// use test::returns_a_result;
718 /// assert_eq!(returns_a_result(), );
723 /// This function will return an error if .
724 pub fn returns_a_result() -> Result<i32, std::io::Error> {
732 fn checks_ref_mut_in_example() {
734 generate_documentation_template,
736 pub fn modifies_a_value$0(a: &mut i32) {
746 /// use test::modifies_a_value;
749 /// modifies_a_value(&mut a);
752 pub fn modifies_a_value(a: &mut i32) {
760 fn stores_result_if_at_least_3_params() {
762 generate_documentation_template,
764 pub fn sum3$0(a: i32, b: i32, c: i32) -> i32 {
776 /// let result = sum3(a, b, c);
777 /// assert_eq!(result, );
779 pub fn sum3(a: i32, b: i32, c: i32) -> i32 {
787 fn supports_fn_in_mods() {
789 generate_documentation_template,
805 /// use test::a::b::noop;
817 fn supports_fn_in_impl() {
819 generate_documentation_template,
834 /// use test::MyStruct;
836 /// MyStruct::noop();
845 fn supports_fn_in_trait() {
847 generate_documentation_template,
850 fn fun$0ction_trait();
860 /// // Example template not implemented for trait functions
869 fn supports_unsafe_fn_in_trait() {
871 generate_documentation_template,
874 unsafe fn unsafe_funct$0ion_trait();
884 /// // Example template not implemented for trait functions
890 unsafe fn unsafe_function_trait();
897 fn supports_fn_in_trait_with_default_panicking() {
899 generate_documentation_template,
902 fn function_trait_with_$0default_panicking() {
914 /// // Example template not implemented for trait functions
920 fn function_trait_with_default_panicking() {
929 fn supports_fn_in_trait_returning_result() {
931 generate_documentation_template,
934 fn function_tr$0ait_returning_result() -> Result<(), std::io::Error>;
944 /// // Example template not implemented for trait functions
949 /// This function will return an error if .
950 fn function_trait_returning_result() -> Result<(), std::io::Error>;
959 generate_documentation_template,
961 #[derive(Debug, PartialEq)]
962 pub struct MyGenericStruct<T> {
965 impl<T> MyGenericStruct<T> {
966 pub fn new$0(x: T) -> MyGenericStruct<T> {
967 MyGenericStruct { x }
972 #[derive(Debug, PartialEq)]
973 pub struct MyGenericStruct<T> {
976 impl<T> MyGenericStruct<T> {
977 /// Creates a new [`MyGenericStruct<T>`].
982 /// use test::MyGenericStruct;
984 /// assert_eq!(MyGenericStruct::new(x), );
986 pub fn new(x: T) -> MyGenericStruct<T> {
987 MyGenericStruct { x }
995 fn detects_new_with_self() {
997 generate_documentation_template,
999 #[derive(Debug, PartialEq)]
1000 pub struct MyGenericStruct2<T> {
1003 impl<T> MyGenericStruct2<T> {
1004 pub fn new$0(x: T) -> Self {
1005 MyGenericStruct2 { x }
1010 #[derive(Debug, PartialEq)]
1011 pub struct MyGenericStruct2<T> {
1014 impl<T> MyGenericStruct2<T> {
1015 /// Creates a new [`MyGenericStruct2<T>`].
1020 /// use test::MyGenericStruct2;
1022 /// assert_eq!(MyGenericStruct2::new(x), );
1024 pub fn new(x: T) -> Self {
1025 MyGenericStruct2 { x }
1033 fn supports_method_call() {
1035 generate_documentation_template,
1037 impl<T> MyGenericStruct<T> {
1038 pub fn co$0nsume(self) {}
1042 impl<T> MyGenericStruct<T> {
1048 /// use test::MyGenericStruct;
1050 /// let my_generic_struct = ;
1051 /// my_generic_struct.consume();
1053 pub fn consume(self) {}
1060 fn checks_modified_self_param() {
1062 generate_documentation_template,
1064 impl<T> MyGenericStruct<T> {
1065 pub fn modi$0fy(&mut self, new_value: T) {
1071 impl<T> MyGenericStruct<T> {
1077 /// use test::MyGenericStruct;
1079 /// let mut my_generic_struct = ;
1080 /// my_generic_struct.modify(new_value);
1081 /// assert_eq!(my_generic_struct, );
1083 pub fn modify(&mut self, new_value: T) {