]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/call_info.rs
Make doc comments optional
[rust.git] / crates / ra_ide_api / src / call_info.rs
1 use ra_db::SourceDatabase;
2 use ra_syntax::{
3     AstNode, SyntaxNode, TextUnit, TextRange,
4     SyntaxKind::FN_DEF,
5     ast::{self, ArgListOwner, DocCommentsOwner},
6     algo::find_node_at_offset,
7 };
8
9 use crate::{FilePosition, CallInfo, db::RootDatabase};
10
11 /// Computes parameter information for the given call expression.
12 pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
13     let file = db.parse(position.file_id);
14     let syntax = file.syntax();
15
16     // Find the calling expression and it's NameRef
17     let calling_node = FnCallNode::with_node(syntax, position.offset)?;
18     let name_ref = calling_node.name_ref()?;
19
20     // Resolve the function's NameRef (NOTE: this isn't entirely accurate).
21     let file_symbols = db.index_resolve(name_ref);
22     let symbol = file_symbols
23         .into_iter()
24         .find(|it| it.ptr.kind() == FN_DEF)?;
25     let fn_file = db.parse(symbol.file_id);
26     let fn_def = symbol.ptr.to_node(&fn_file);
27     let fn_def = ast::FnDef::cast(fn_def).unwrap();
28     let mut call_info = CallInfo::new(fn_def)?;
29     // If we have a calling expression let's find which argument we are on
30     let num_params = call_info.parameters.len();
31     let has_self = fn_def.param_list().and_then(|l| l.self_param()).is_some();
32
33     if num_params == 1 {
34         if !has_self {
35             call_info.active_parameter = Some(0);
36         }
37     } else if num_params > 1 {
38         // Count how many parameters into the call we are.
39         // TODO: This is best effort for now and should be fixed at some point.
40         // It may be better to see where we are in the arg_list and then check
41         // where offset is in that list (or beyond).
42         // Revisit this after we get documentation comments in.
43         if let Some(ref arg_list) = calling_node.arg_list() {
44             let start = arg_list.syntax().range().start();
45
46             let range_search = TextRange::from_to(start, position.offset);
47             let mut commas: usize = arg_list
48                 .syntax()
49                 .text()
50                 .slice(range_search)
51                 .to_string()
52                 .matches(',')
53                 .count();
54
55             // If we have a method call eat the first param since it's just self.
56             if has_self {
57                 commas += 1;
58             }
59
60             call_info.active_parameter = Some(commas);
61         }
62     }
63
64     Some(call_info)
65 }
66
67 enum FnCallNode<'a> {
68     CallExpr(&'a ast::CallExpr),
69     MethodCallExpr(&'a ast::MethodCallExpr),
70 }
71
72 impl<'a> FnCallNode<'a> {
73     pub fn with_node(syntax: &'a SyntaxNode, offset: TextUnit) -> Option<FnCallNode<'a>> {
74         if let Some(expr) = find_node_at_offset::<ast::CallExpr>(syntax, offset) {
75             return Some(FnCallNode::CallExpr(expr));
76         }
77         if let Some(expr) = find_node_at_offset::<ast::MethodCallExpr>(syntax, offset) {
78             return Some(FnCallNode::MethodCallExpr(expr));
79         }
80         None
81     }
82
83     pub fn name_ref(&self) -> Option<&'a ast::NameRef> {
84         match *self {
85             FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()?.kind() {
86                 ast::ExprKind::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
87                 _ => return None,
88             }),
89
90             FnCallNode::MethodCallExpr(call_expr) => call_expr
91                 .syntax()
92                 .children()
93                 .filter_map(ast::NameRef::cast)
94                 .nth(0),
95         }
96     }
97
98     pub fn arg_list(&self) -> Option<&'a ast::ArgList> {
99         match *self {
100             FnCallNode::CallExpr(expr) => expr.arg_list(),
101             FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
102         }
103     }
104 }
105
106 impl CallInfo {
107     fn new(node: &ast::FnDef) -> Option<Self> {
108         let label: String = if let Some(body) = node.body() {
109             let body_range = body.syntax().range();
110             let label: String = node
111                 .syntax()
112                 .children()
113                 .filter(|child| !child.range().is_subrange(&body_range)) // Filter out body
114                 .filter(|child| ast::Comment::cast(child).is_none()) // Filter out doc comments
115                 .map(|node| node.text().to_string())
116                 .collect();
117             label
118         } else {
119             node.syntax().text().to_string()
120         };
121
122         let mut doc = None;
123         if let Some(docs) = node.doc_comment_text() {
124             // Massage markdown
125             let mut processed_lines = Vec::new();
126             let mut in_code_block = false;
127             for line in docs.lines() {
128                 if line.starts_with("```") {
129                     in_code_block = !in_code_block;
130                 }
131
132                 let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
133                     "```rust".into()
134                 } else {
135                     line.to_string()
136                 };
137
138                 processed_lines.push(line);
139             }
140
141             doc = Some(processed_lines.join("\n"));
142         }
143
144         Some(CallInfo {
145             parameters: param_list(node),
146             label: label.trim().to_owned(),
147             doc,
148             active_parameter: None,
149         })
150     }
151 }
152
153 fn param_list(node: &ast::FnDef) -> Vec<String> {
154     let mut res = vec![];
155     if let Some(param_list) = node.param_list() {
156         if let Some(self_param) = param_list.self_param() {
157             res.push(self_param.syntax().text().to_string())
158         }
159
160         // Maybe use param.pat here? See if we can just extract the name?
161         //res.extend(param_list.params().map(|p| p.syntax().text().to_string()));
162         res.extend(
163             param_list
164                 .params()
165                 .filter_map(|p| p.pat())
166                 .map(|pat| pat.syntax().text().to_string()),
167         );
168     }
169     res
170 }
171
172 #[cfg(test)]
173 mod tests {
174     use super::*;
175
176     use crate::mock_analysis::single_file_with_position;
177
178     fn call_info(text: &str) -> CallInfo {
179         let (analysis, position) = single_file_with_position(text);
180         analysis.call_info(position).unwrap().unwrap()
181     }
182
183     #[test]
184     fn test_fn_signature_two_args_first() {
185         let info = call_info(
186             r#"fn foo(x: u32, y: u32) -> u32 {x + y}
187 fn bar() { foo(<|>3, ); }"#,
188         );
189
190         assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
191         assert_eq!(info.active_parameter, Some(0));
192     }
193
194     #[test]
195     fn test_fn_signature_two_args_second() {
196         let info = call_info(
197             r#"fn foo(x: u32, y: u32) -> u32 {x + y}
198 fn bar() { foo(3, <|>); }"#,
199         );
200
201         assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
202         assert_eq!(info.active_parameter, Some(1));
203     }
204
205     #[test]
206     fn test_fn_signature_for_impl() {
207         let info = call_info(
208             r#"struct F; impl F { pub fn new() { F{}} }
209 fn bar() {let _ : F = F::new(<|>);}"#,
210         );
211
212         assert_eq!(info.parameters, Vec::<String>::new());
213         assert_eq!(info.active_parameter, None);
214     }
215
216     #[test]
217     fn test_fn_signature_for_method_self() {
218         let info = call_info(
219             r#"struct F;
220 impl F {
221     pub fn new() -> F{
222         F{}
223     }
224
225     pub fn do_it(&self) {}
226 }
227
228 fn bar() {
229     let f : F = F::new();
230     f.do_it(<|>);
231 }"#,
232         );
233
234         assert_eq!(info.parameters, vec!["&self".to_string()]);
235         assert_eq!(info.active_parameter, None);
236     }
237
238     #[test]
239     fn test_fn_signature_for_method_with_arg() {
240         let info = call_info(
241             r#"struct F;
242 impl F {
243     pub fn new() -> F{
244         F{}
245     }
246
247     pub fn do_it(&self, x: i32) {}
248 }
249
250 fn bar() {
251     let f : F = F::new();
252     f.do_it(<|>);
253 }"#,
254         );
255
256         assert_eq!(info.parameters, vec!["&self".to_string(), "x".to_string()]);
257         assert_eq!(info.active_parameter, Some(1));
258     }
259
260     #[test]
261     fn test_fn_signature_with_docs_simple() {
262         let info = call_info(
263             r#"
264 /// test
265 // non-doc-comment
266 fn foo(j: u32) -> u32 {
267     j
268 }
269
270 fn bar() {
271     let _ = foo(<|>);
272 }
273 "#,
274         );
275
276         assert_eq!(info.parameters, vec!["j".to_string()]);
277         assert_eq!(info.active_parameter, Some(0));
278         assert_eq!(info.label, "fn foo(j: u32) -> u32".to_string());
279         assert_eq!(info.doc, Some("test".into()));
280     }
281
282     #[test]
283     fn test_fn_signature_with_docs() {
284         let info = call_info(
285             r#"
286 /// Adds one to the number given.
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// let five = 5;
292 ///
293 /// assert_eq!(6, my_crate::add_one(5));
294 /// ```
295 pub fn add_one(x: i32) -> i32 {
296     x + 1
297 }
298
299 pub fn do() {
300     add_one(<|>
301 }"#,
302         );
303
304         assert_eq!(info.parameters, vec!["x".to_string()]);
305         assert_eq!(info.active_parameter, Some(0));
306         assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
307         assert_eq!(
308             info.doc,
309             Some(
310                 r#"Adds one to the number given.
311
312 # Examples
313
314 ```rust
315 let five = 5;
316
317 assert_eq!(6, my_crate::add_one(5));
318 ```"#
319                     .into()
320             )
321         );
322     }
323
324     #[test]
325     fn test_fn_signature_with_docs_impl() {
326         let info = call_info(
327             r#"
328 struct addr;
329 impl addr {
330     /// Adds one to the number given.
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// let five = 5;
336     ///
337     /// assert_eq!(6, my_crate::add_one(5));
338     /// ```
339     pub fn add_one(x: i32) -> i32 {
340         x + 1
341     }
342 }
343
344 pub fn do_it() {
345     addr {};
346     addr::add_one(<|>);
347 }"#,
348         );
349
350         assert_eq!(info.parameters, vec!["x".to_string()]);
351         assert_eq!(info.active_parameter, Some(0));
352         assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
353         assert_eq!(
354             info.doc,
355             Some(
356                 r#"Adds one to the number given.
357
358 # Examples
359
360 ```rust
361 let five = 5;
362
363 assert_eq!(6, my_crate::add_one(5));
364 ```"#
365                     .into()
366             )
367         );
368     }
369
370     #[test]
371     fn test_fn_signature_with_docs_from_actix() {
372         let info = call_info(
373             r#"
374 pub trait WriteHandler<E>
375 where
376     Self: Actor,
377     Self::Context: ActorContext,
378 {
379     /// Method is called when writer emits error.
380     ///
381     /// If this method returns `ErrorAction::Continue` writer processing
382     /// continues otherwise stream processing stops.
383     fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
384         Running::Stop
385     }
386
387     /// Method is called when writer finishes.
388     ///
389     /// By default this method stops actor's `Context`.
390     fn finished(&mut self, ctx: &mut Self::Context) {
391         ctx.stop()
392     }
393 }
394
395 pub fn foo() {
396     WriteHandler r;
397     r.finished(<|>);
398 }
399
400 "#,
401         );
402
403         assert_eq!(
404             info.parameters,
405             vec!["&mut self".to_string(), "ctx".to_string()]
406         );
407         assert_eq!(info.active_parameter, Some(1));
408         assert_eq!(
409             info.doc,
410             Some(
411                 r#"Method is called when writer finishes.
412
413 By default this method stops actor's `Context`."#
414                     .into()
415             )
416         );
417     }
418
419 }