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 {
92 Some(format!("Creates a new [`{}`].", self_type_without_lifetimes(ast_func)?))
100 .unwrap_or_else(|| ".".into())
103 /// Builds an `# Examples` section. An option is returned to be able to manage an error in the AST.
104 fn examples_builder(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<Vec<String>> {
105 let mut lines = string_vec_from(&["# Examples", "", "```"]);
106 if is_in_trait_def(ast_func, ctx) {
107 lines.push("// Example template not implemented for trait functions".into());
109 lines.append(&mut gen_ex_template(ast_func, ctx)?)
112 lines.push("```".into());
116 /// Builds an optional `# Panics` section
117 fn panics_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
118 match can_panic(ast_func) {
119 Some(true) => Some(string_vec_from(&["# Panics", "", "Panics if ."])),
124 /// Builds an optional `# Errors` section
125 fn errors_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
126 match return_type(ast_func)?.to_string().contains("Result") {
127 true => Some(string_vec_from(&["# Errors", "", "This function will return an error if ."])),
132 /// Builds an optional `# Safety` section
133 fn safety_builder(ast_func: &ast::Fn) -> Option<Vec<String>> {
134 let is_unsafe = ast_func.unsafe_token().is_some();
136 true => Some(string_vec_from(&["# Safety", "", "."])),
141 /// Generates an example template
142 fn gen_ex_template(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<Vec<String>> {
143 let mut lines = Vec::new();
144 let is_unsafe = ast_func.unsafe_token().is_some();
145 let param_list = ast_func.param_list()?;
146 let ref_mut_params = ref_mut_params(¶m_list);
147 let self_name: Option<String> = self_name(ast_func);
149 lines.push(format!("use {};", build_path(ast_func, ctx)?));
150 lines.push("".into());
151 if let Some(self_definition) = self_definition(ast_func, self_name.as_deref()) {
152 lines.push(self_definition);
154 for param_name in &ref_mut_params {
155 lines.push(format!("let mut {} = ;", param_name))
157 // Call the function, check result
158 let function_call = function_call(ast_func, ¶m_list, self_name.as_deref(), is_unsafe)?;
159 if returns_a_value(ast_func, ctx) {
160 if count_parameters(¶m_list) < 3 {
161 lines.push(format!("assert_eq!({}, );", function_call));
163 lines.push(format!("let result = {};", function_call));
164 lines.push("assert_eq!(result, );".into());
167 lines.push(format!("{};", function_call));
169 // Check the mutated values
170 if is_ref_mut_self(ast_func) == Some(true) {
171 lines.push(format!("assert_eq!({}, );", self_name?));
173 for param_name in &ref_mut_params {
174 lines.push(format!("assert_eq!({}, );", param_name));
179 /// Checks if the function is public / exported
180 fn is_public(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<bool> {
181 let hir_func = ctx.sema.to_def(ast_func)?;
183 hir_func.visibility(ctx.db()) == Visibility::Public
184 && all_parent_mods_public(&hir_func, ctx),
188 /// Checks that all parent modules of the function are public / exported
189 fn all_parent_mods_public(hir_func: &hir::Function, ctx: &AssistContext) -> bool {
190 let mut module = hir_func.module(ctx.db());
192 if let Some(parent) = module.parent(ctx.db()) {
193 match ModuleDef::from(module).visibility(ctx.db()) {
194 Visibility::Public => module = parent,
203 /// Returns the name of the current crate
204 fn crate_name(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
205 let krate = ctx.sema.scope(&ast_func.syntax()).module()?.krate();
206 Some(krate.display_name(ctx.db())?.to_string())
209 /// `None` if function without a body; some bool to guess if function can panic
210 fn can_panic(ast_func: &ast::Fn) -> Option<bool> {
211 let body = ast_func.body()?.to_string();
212 let can_panic = body.contains("panic!(")
213 // FIXME it would be better to not match `debug_assert*!` macro invocations
214 || body.contains("assert!(")
215 || body.contains(".unwrap()")
216 || body.contains(".expect(");
220 /// Helper function to get the name that should be given to `self` arguments
221 fn self_name(ast_func: &ast::Fn) -> Option<String> {
222 self_partial_type(ast_func).map(|name| to_lower_snake_case(&name))
225 /// Heper function to get the name of the type of `self`
226 fn self_type(ast_func: &ast::Fn) -> Option<ast::Type> {
227 ast_func.syntax().ancestors().find_map(ast::Impl::cast).and_then(|i| i.self_ty())
230 /// Output the real name of `Self` like `MyType<T>`, without the lifetimes.
231 fn self_type_without_lifetimes(ast_func: &ast::Fn) -> Option<String> {
233 ast::PathType::cast(self_type(ast_func)?.syntax().clone())?.path()?.segment()?;
234 let mut name = path_segment.name_ref()?.to_string();
235 let generics = path_segment
238 .filter(|generic| matches!(generic, ast::GenericArg::TypeArg(_)))
239 .map(|generic| generic.to_string());
240 let generics: String = Itertools::intersperse(generics, ", ".to_string()).collect();
241 if !generics.is_empty() {
243 name.push_str(&generics);
249 /// Heper function to get the name of the type of `self` without generic arguments
250 fn self_partial_type(ast_func: &ast::Fn) -> Option<String> {
251 let mut self_type = self_type(ast_func)?.to_string();
252 if let Some(idx) = self_type.find(|c| ['<', ' '].contains(&c)) {
253 self_type.truncate(idx);
258 /// Helper function to determine if the function is in a trait implementation
259 fn is_in_trait_impl(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
262 .and_then(|hir_func| hir_func.as_assoc_item(ctx.db()))
263 .and_then(|assoc_item| assoc_item.containing_trait_impl(ctx.db()))
267 /// Helper function to determine if the function definition is in a trait definition
268 fn is_in_trait_def(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
271 .and_then(|hir_func| hir_func.as_assoc_item(ctx.db()))
272 .and_then(|assoc_item| assoc_item.containing_trait(ctx.db()))
276 /// Returns `None` if no `self` at all, `Some(true)` if there is `&mut self` else `Some(false)`
277 fn is_ref_mut_self(ast_func: &ast::Fn) -> Option<bool> {
278 let self_param = ast_func.param_list()?.self_param()?;
279 Some(self_param.mut_token().is_some() && self_param.amp_token().is_some())
282 /// Helper function to define an variable to be the `self` argument
283 fn self_definition(ast_func: &ast::Fn, self_name: Option<&str>) -> Option<String> {
284 let definition = match is_ref_mut_self(ast_func)? {
285 true => format!("let mut {} = ;", self_name?),
286 false => format!("let {} = ;", self_name?),
291 /// Helper function to determine if a parameter is `&mut`
292 fn is_a_ref_mut_param(param: &ast::Param) -> bool {
294 Some(ast::Type::RefType(param_ref)) => param_ref.mut_token().is_some(),
299 /// Helper function to build the list of `&mut` parameters
300 fn ref_mut_params(param_list: &ast::ParamList) -> Vec<String> {
303 .filter_map(|param| match is_a_ref_mut_param(¶m) {
304 // Maybe better filter the param name (to do this maybe extract a function from
305 // `arguments_from_params`?) in case of a `mut a: &mut T`. Anyway managing most (not
306 // all) cases might be enough, the goal is just to produce a template.
307 true => Some(param.pat()?.to_string()),
313 /// Helper function to build the comma-separated list of arguments of the function
314 fn arguments_from_params(param_list: &ast::ParamList) -> String {
315 let args_iter = param_list.params().map(|param| match param.pat() {
316 // To avoid `mut` in the function call (which would be a nonsense), `Pat` should not be
317 // written as is so its variants must be managed independently. Other variants (for
318 // instance `TuplePat`) could be managed later.
319 Some(ast::Pat::IdentPat(ident_pat)) => match ident_pat.name() {
320 Some(name) => match is_a_ref_mut_param(¶m) {
321 true => format!("&mut {}", name),
322 false => name.to_string(),
324 None => "_".to_string(),
326 _ => "_".to_string(),
328 Itertools::intersperse(args_iter, ", ".to_string()).collect()
331 /// Helper function to build a function call. `None` if expected `self_name` was not provided
334 param_list: &ast::ParamList,
335 self_name: Option<&str>,
337 ) -> Option<String> {
338 let name = ast_func.name()?;
339 let arguments = arguments_from_params(¶m_list);
340 let function_call = if param_list.self_param().is_some() {
341 format!("{}.{}({})", self_name?, name, arguments)
342 } else if let Some(implementation) = self_partial_type(ast_func) {
343 format!("{}::{}({})", implementation, name, arguments)
345 format!("{}({})", name, arguments)
348 true => Some(format!("unsafe {{ {} }}", function_call)),
349 false => Some(function_call),
353 /// Helper function to count the parameters including `self`
354 fn count_parameters(param_list: &ast::ParamList) -> usize {
355 param_list.params().count() + if param_list.self_param().is_some() { 1 } else { 0 }
358 /// Helper function to transform lines of documentation into a Rust code documentation
359 fn documentation_from_lines(doc_lines: Vec<String>, indent_level: IndentLevel) -> String {
360 let mut result = String::new();
361 for doc_line in doc_lines {
362 result.push_str("///");
363 if !doc_line.is_empty() {
365 result.push_str(&doc_line);
368 result.push_str(&indent_level.to_string());
373 /// Helper function to transform an array of borrowed strings to an owned `Vec<String>`
374 fn string_vec_from(string_array: &[&str]) -> Vec<String> {
375 string_array.iter().map(|&s| s.to_owned()).collect()
378 /// Helper function to build the path of the module in the which is the node
379 fn build_path(ast_func: &ast::Fn, ctx: &AssistContext) -> Option<String> {
380 let crate_name = crate_name(ast_func, ctx)?;
381 let leaf = self_partial_type(ast_func)
382 .or_else(|| ast_func.name().map(|n| n.to_string()))
383 .unwrap_or_else(|| "*".into());
384 let module_def: ModuleDef = ctx.sema.to_def(ast_func)?.module(ctx.db()).into();
385 match module_def.canonical_path(ctx.db()) {
386 Some(path) => Some(format!("{}::{}::{}", crate_name, path, leaf)),
387 None => Some(format!("{}::{}", crate_name, leaf)),
391 /// Helper function to get the return type of a function
392 fn return_type(ast_func: &ast::Fn) -> Option<ast::Type> {
393 ast_func.ret_type()?.ty()
396 /// Helper function to determine if the function returns some data
397 fn returns_a_value(ast_func: &ast::Fn, ctx: &AssistContext) -> bool {
400 .map(|hir_func| hir_func.ret_type(ctx.db()))
401 .map(|ret_ty| !ret_ty.is_unit() && !ret_ty.is_never())
407 use crate::tests::{check_assist, check_assist_not_applicable};
412 fn not_applicable_on_function_calls() {
413 check_assist_not_applicable(
414 generate_documentation_template,
417 fn calls_hello_world() {
425 fn not_applicable_in_trait_impl() {
426 check_assist_not_applicable(
427 generate_documentation_template,
431 impl MyTrait for MyStruct {
439 fn not_applicable_if_function_is_private() {
440 check_assist_not_applicable(generate_documentation_template, r#"fn priv$0ate() {}"#);
444 fn not_applicable_if_function_is_pub_crate() {
445 check_assist_not_applicable(
446 generate_documentation_template,
447 r#"pub(crate) fn pri$0vate() {}"#,
452 fn not_applicable_if_function_is_in_private_mod() {
453 check_assist_not_applicable(
454 generate_documentation_template,
457 pub fn pri$0vate() {}
463 fn not_applicable_if_function_is_in_pub_crate_mod() {
464 check_assist_not_applicable(
465 generate_documentation_template,
467 pub(crate) mod PrivateModule {
468 pub fn pr$0ivate() {}
474 fn not_applicable_if_function_is_in_non_public_mod_is_recursive() {
475 check_assist_not_applicable(
476 generate_documentation_template,
478 mod ParentPrivateModule {
479 pub mod PrivateModule {
480 pub fn pr$0ivate() {}
487 fn not_applicable_if_function_already_documented() {
488 check_assist_not_applicable(
489 generate_documentation_template,
491 /// Some documentation here
492 pub fn $0documented_function() {}
498 fn supports_noop_function() {
500 generate_documentation_template,
520 fn supports_a_parameter() {
522 generate_documentation_template,
524 pub fn no$0op_with_param(_a: i32) {}
532 /// use test::noop_with_param;
534 /// noop_with_param(_a);
536 pub fn noop_with_param(_a: i32) {}
542 fn detects_unsafe_function() {
544 generate_documentation_template,
546 pub unsafe fn no$0op_unsafe() {}
554 /// use test::noop_unsafe;
556 /// unsafe { noop_unsafe() };
562 pub unsafe fn noop_unsafe() {}
568 fn guesses_panic_macro_can_panic() {
570 generate_documentation_template,
572 pub fn panic$0s_if(a: bool) {
584 /// use test::panics_if;
592 pub fn panics_if(a: bool) {
602 fn guesses_assert_macro_can_panic() {
604 generate_documentation_template,
606 pub fn $0panics_if_not(a: bool) {
616 /// use test::panics_if_not;
618 /// panics_if_not(a);
624 pub fn panics_if_not(a: bool) {
632 fn guesses_unwrap_can_panic() {
634 generate_documentation_template,
636 pub fn $0panics_if_none(a: Option<()>) {
646 /// use test::panics_if_none;
648 /// panics_if_none(a);
654 pub fn panics_if_none(a: Option<()>) {
662 fn guesses_expect_can_panic() {
664 generate_documentation_template,
666 pub fn $0panics_if_none2(a: Option<()>) {
676 /// use test::panics_if_none2;
678 /// panics_if_none2(a);
684 pub fn panics_if_none2(a: Option<()>) {
692 fn checks_output_in_example() {
694 generate_documentation_template,
696 pub fn returns_a_value$0() -> i32 {
706 /// use test::returns_a_value;
708 /// assert_eq!(returns_a_value(), );
710 pub fn returns_a_value() -> i32 {
718 fn detects_result_output() {
720 generate_documentation_template,
722 pub fn returns_a_result$0() -> Result<i32, std::io::Error> {
732 /// use test::returns_a_result;
734 /// assert_eq!(returns_a_result(), );
739 /// This function will return an error if .
740 pub fn returns_a_result() -> Result<i32, std::io::Error> {
748 fn checks_ref_mut_in_example() {
750 generate_documentation_template,
752 pub fn modifies_a_value$0(a: &mut i32) {
762 /// use test::modifies_a_value;
765 /// modifies_a_value(&mut a);
768 pub fn modifies_a_value(a: &mut i32) {
776 fn stores_result_if_at_least_3_params() {
778 generate_documentation_template,
780 pub fn sum3$0(a: i32, b: i32, c: i32) -> i32 {
792 /// let result = sum3(a, b, c);
793 /// assert_eq!(result, );
795 pub fn sum3(a: i32, b: i32, c: i32) -> i32 {
803 fn supports_fn_in_mods() {
805 generate_documentation_template,
821 /// use test::a::b::noop;
833 fn supports_fn_in_impl() {
835 generate_documentation_template,
850 /// use test::MyStruct;
852 /// MyStruct::noop();
861 fn supports_fn_in_trait() {
863 generate_documentation_template,
866 fn fun$0ction_trait();
876 /// // Example template not implemented for trait functions
885 fn supports_unsafe_fn_in_trait() {
887 generate_documentation_template,
890 unsafe fn unsafe_funct$0ion_trait();
900 /// // Example template not implemented for trait functions
906 unsafe fn unsafe_function_trait();
913 fn supports_fn_in_trait_with_default_panicking() {
915 generate_documentation_template,
918 fn function_trait_with_$0default_panicking() {
930 /// // Example template not implemented for trait functions
936 fn function_trait_with_default_panicking() {
945 fn supports_fn_in_trait_returning_result() {
947 generate_documentation_template,
950 fn function_tr$0ait_returning_result() -> Result<(), std::io::Error>;
960 /// // Example template not implemented for trait functions
965 /// This function will return an error if .
966 fn function_trait_returning_result() -> Result<(), std::io::Error>;
975 generate_documentation_template,
977 #[derive(Debug, PartialEq)]
978 pub struct MyGenericStruct<T> {
981 impl<T> MyGenericStruct<T> {
982 pub fn new$0(x: T) -> MyGenericStruct<T> {
983 MyGenericStruct { x }
988 #[derive(Debug, PartialEq)]
989 pub struct MyGenericStruct<T> {
992 impl<T> MyGenericStruct<T> {
993 /// Creates a new [`MyGenericStruct<T>`].
998 /// use test::MyGenericStruct;
1000 /// assert_eq!(MyGenericStruct::new(x), );
1002 pub fn new(x: T) -> MyGenericStruct<T> {
1003 MyGenericStruct { x }
1011 fn removes_one_lifetime_from_description() {
1013 generate_documentation_template,
1015 #[derive(Debug, PartialEq)]
1016 pub struct MyGenericStruct<'a, T> {
1019 impl<'a, T> MyGenericStruct<'a, T> {
1020 pub fn new$0(x: &'a T) -> Self {
1021 MyGenericStruct { x }
1026 #[derive(Debug, PartialEq)]
1027 pub struct MyGenericStruct<'a, T> {
1030 impl<'a, T> MyGenericStruct<'a, T> {
1031 /// Creates a new [`MyGenericStruct<T>`].
1036 /// use test::MyGenericStruct;
1038 /// assert_eq!(MyGenericStruct::new(x), );
1040 pub fn new(x: &'a T) -> Self {
1041 MyGenericStruct { x }
1049 fn removes_all_lifetimes_from_description() {
1051 generate_documentation_template,
1053 #[derive(Debug, PartialEq)]
1054 pub struct MyGenericStruct<'a, 'b, T> {
1058 impl<'a, 'b, T> MyGenericStruct<'a, 'b, T> {
1059 pub fn new$0(x: &'a T, y: &'b T) -> Self {
1060 MyGenericStruct { x, y }
1065 #[derive(Debug, PartialEq)]
1066 pub struct MyGenericStruct<'a, 'b, T> {
1070 impl<'a, 'b, T> MyGenericStruct<'a, 'b, T> {
1071 /// Creates a new [`MyGenericStruct<T>`].
1076 /// use test::MyGenericStruct;
1078 /// assert_eq!(MyGenericStruct::new(x, y), );
1080 pub fn new(x: &'a T, y: &'b T) -> Self {
1081 MyGenericStruct { x, y }
1089 fn removes_all_lifetimes_and_brackets_from_description() {
1091 generate_documentation_template,
1093 #[derive(Debug, PartialEq)]
1094 pub struct MyGenericStruct<'a, 'b> {
1098 impl<'a, 'b> MyGenericStruct<'a, 'b> {
1099 pub fn new$0(x: &'a usize, y: &'b usize) -> Self {
1100 MyGenericStruct { x, y }
1105 #[derive(Debug, PartialEq)]
1106 pub struct MyGenericStruct<'a, 'b> {
1110 impl<'a, 'b> MyGenericStruct<'a, 'b> {
1111 /// Creates a new [`MyGenericStruct`].
1116 /// use test::MyGenericStruct;
1118 /// assert_eq!(MyGenericStruct::new(x, y), );
1120 pub fn new(x: &'a usize, y: &'b usize) -> Self {
1121 MyGenericStruct { x, y }
1129 fn detects_new_with_self() {
1131 generate_documentation_template,
1133 #[derive(Debug, PartialEq)]
1134 pub struct MyGenericStruct2<T> {
1137 impl<T> MyGenericStruct2<T> {
1138 pub fn new$0(x: T) -> Self {
1139 MyGenericStruct2 { x }
1144 #[derive(Debug, PartialEq)]
1145 pub struct MyGenericStruct2<T> {
1148 impl<T> MyGenericStruct2<T> {
1149 /// Creates a new [`MyGenericStruct2<T>`].
1154 /// use test::MyGenericStruct2;
1156 /// assert_eq!(MyGenericStruct2::new(x), );
1158 pub fn new(x: T) -> Self {
1159 MyGenericStruct2 { x }
1167 fn supports_method_call() {
1169 generate_documentation_template,
1171 impl<T> MyGenericStruct<T> {
1172 pub fn co$0nsume(self) {}
1176 impl<T> MyGenericStruct<T> {
1182 /// use test::MyGenericStruct;
1184 /// let my_generic_struct = ;
1185 /// my_generic_struct.consume();
1187 pub fn consume(self) {}
1194 fn checks_modified_self_param() {
1196 generate_documentation_template,
1198 impl<T> MyGenericStruct<T> {
1199 pub fn modi$0fy(&mut self, new_value: T) {
1205 impl<T> MyGenericStruct<T> {
1211 /// use test::MyGenericStruct;
1213 /// let mut my_generic_struct = ;
1214 /// my_generic_struct.modify(new_value);
1215 /// assert_eq!(my_generic_struct, );
1217 pub fn modify(&mut self, new_value: T) {