]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/call_info.rs
Simplify CallInfo label and documentation
[rust.git] / crates / ra_ide_api / src / call_info.rs
1 use ra_db::SyntaxDatabase;
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.source_file(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.source_file(symbol.file_id);
26     let fn_def = symbol.ptr.resolve(&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         let docs = node.doc_comment_text();
124         if !docs.is_empty() {
125             // Massage markdown
126             let mut processed_lines = Vec::new();
127             let mut in_code_block = false;
128             for line in docs.lines() {
129                 if line.starts_with("```") {
130                     in_code_block = !in_code_block;
131                 }
132
133                 let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
134                     "```rust".into()
135                 } else {
136                     line.to_string()
137                 };
138
139                 processed_lines.push(line);
140             }
141
142             doc = Some(processed_lines.join("\n"));
143         }
144
145         Some(CallInfo {
146             parameters: param_list(node),
147             label: label.trim().to_owned(),
148             doc,
149             active_parameter: None,
150         })
151     }
152 }
153
154 fn param_list(node: &ast::FnDef) -> Vec<String> {
155     let mut res = vec![];
156     if let Some(param_list) = node.param_list() {
157         if let Some(self_param) = param_list.self_param() {
158             res.push(self_param.syntax().text().to_string())
159         }
160
161         // Maybe use param.pat here? See if we can just extract the name?
162         //res.extend(param_list.params().map(|p| p.syntax().text().to_string()));
163         res.extend(
164             param_list
165                 .params()
166                 .filter_map(|p| p.pat())
167                 .map(|pat| pat.syntax().text().to_string()),
168         );
169     }
170     res
171 }
172
173 #[cfg(test)]
174 mod tests {
175     use super::*;
176
177     use crate::mock_analysis::single_file_with_position;
178
179     fn call_info(text: &str) -> CallInfo {
180         let (analysis, position) = single_file_with_position(text);
181         analysis.call_info(position).unwrap().unwrap()
182     }
183
184     #[test]
185     fn test_fn_signature_two_args_first() {
186         let info = call_info(
187             r#"fn foo(x: u32, y: u32) -> u32 {x + y}
188 fn bar() { foo(<|>3, ); }"#,
189         );
190
191         assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
192         assert_eq!(info.active_parameter, Some(0));
193     }
194
195     #[test]
196     fn test_fn_signature_two_args_second() {
197         let info = call_info(
198             r#"fn foo(x: u32, y: u32) -> u32 {x + y}
199 fn bar() { foo(3, <|>); }"#,
200         );
201
202         assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
203         assert_eq!(info.active_parameter, Some(1));
204     }
205
206     #[test]
207     fn test_fn_signature_for_impl() {
208         let info = call_info(
209             r#"struct F; impl F { pub fn new() { F{}} }
210 fn bar() {let _ : F = F::new(<|>);}"#,
211         );
212
213         assert_eq!(info.parameters, Vec::<String>::new());
214         assert_eq!(info.active_parameter, None);
215     }
216
217     #[test]
218     fn test_fn_signature_for_method_self() {
219         let info = call_info(
220             r#"struct F;
221 impl F {
222     pub fn new() -> F{
223         F{}
224     }
225
226     pub fn do_it(&self) {}
227 }
228
229 fn bar() {
230     let f : F = F::new();
231     f.do_it(<|>);
232 }"#,
233         );
234
235         assert_eq!(info.parameters, vec!["&self".to_string()]);
236         assert_eq!(info.active_parameter, None);
237     }
238
239     #[test]
240     fn test_fn_signature_for_method_with_arg() {
241         let info = call_info(
242             r#"struct F;
243 impl F {
244     pub fn new() -> F{
245         F{}
246     }
247
248     pub fn do_it(&self, x: i32) {}
249 }
250
251 fn bar() {
252     let f : F = F::new();
253     f.do_it(<|>);
254 }"#,
255         );
256
257         assert_eq!(info.parameters, vec!["&self".to_string(), "x".to_string()]);
258         assert_eq!(info.active_parameter, Some(1));
259     }
260
261     #[test]
262     fn test_fn_signature_with_docs_simple() {
263         let info = call_info(
264             r#"
265 /// test
266 // non-doc-comment
267 fn foo(j: u32) -> u32 {
268     j
269 }
270
271 fn bar() {
272     let _ = foo(<|>);
273 }
274 "#,
275         );
276
277         assert_eq!(info.parameters, vec!["j".to_string()]);
278         assert_eq!(info.active_parameter, Some(0));
279         assert_eq!(info.label, "fn foo(j: u32) -> u32".to_string());
280         assert_eq!(info.doc, Some("test".into()));
281     }
282
283     #[test]
284     fn test_fn_signature_with_docs() {
285         let info = call_info(
286             r#"
287 /// Adds one to the number given.
288 ///
289 /// # Examples
290 ///
291 /// ```
292 /// let five = 5;
293 ///
294 /// assert_eq!(6, my_crate::add_one(5));
295 /// ```
296 pub fn add_one(x: i32) -> i32 {
297     x + 1
298 }
299
300 pub fn do() {
301     add_one(<|>
302 }"#,
303         );
304
305         assert_eq!(info.parameters, vec!["x".to_string()]);
306         assert_eq!(info.active_parameter, Some(0));
307         assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
308         assert_eq!(
309             info.doc,
310             Some(
311                 r#"Adds one to the number given.
312
313 # Examples
314
315 ```rust
316 let five = 5;
317
318 assert_eq!(6, my_crate::add_one(5));
319 ```"#
320                     .into()
321             )
322         );
323     }
324
325     #[test]
326     fn test_fn_signature_with_docs_impl() {
327         let info = call_info(
328             r#"
329 struct addr;
330 impl addr {
331     /// Adds one to the number given.
332     ///
333     /// # Examples
334     ///
335     /// ```
336     /// let five = 5;
337     ///
338     /// assert_eq!(6, my_crate::add_one(5));
339     /// ```
340     pub fn add_one(x: i32) -> i32 {
341         x + 1
342     }
343 }
344
345 pub fn do_it() {
346     addr {};
347     addr::add_one(<|>);
348 }"#,
349         );
350
351         assert_eq!(info.parameters, vec!["x".to_string()]);
352         assert_eq!(info.active_parameter, Some(0));
353         assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
354         assert_eq!(
355             info.doc,
356             Some(
357                 r#"Adds one to the number given.
358
359 # Examples
360
361 ```rust
362 let five = 5;
363
364 assert_eq!(6, my_crate::add_one(5));
365 ```"#
366                     .into()
367             )
368         );
369     }
370
371     #[test]
372     fn test_fn_signature_with_docs_from_actix() {
373         let info = call_info(
374             r#"
375 pub trait WriteHandler<E>
376 where
377     Self: Actor,
378     Self::Context: ActorContext,
379 {
380     /// Method is called when writer emits error.
381     ///
382     /// If this method returns `ErrorAction::Continue` writer processing
383     /// continues otherwise stream processing stops.
384     fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
385         Running::Stop
386     }
387
388     /// Method is called when writer finishes.
389     ///
390     /// By default this method stops actor's `Context`.
391     fn finished(&mut self, ctx: &mut Self::Context) {
392         ctx.stop()
393     }
394 }
395
396 pub fn foo() {
397     WriteHandler r;
398     r.finished(<|>);
399 }
400
401 "#,
402         );
403
404         assert_eq!(
405             info.parameters,
406             vec!["&mut self".to_string(), "ctx".to_string()]
407         );
408         assert_eq!(info.active_parameter, Some(1));
409         assert_eq!(
410             info.doc,
411             Some(
412                 r#"Method is called when writer finishes.
413
414 By default this method stops actor's `Context`."#
415                     .into()
416             )
417         );
418     }
419
420 }