1 use std::cmp::{max, min};
3 use ra_db::{SyntaxDatabase, Cancelable};
5 AstNode, SyntaxNode, TextUnit, TextRange,
7 ast::{self, ArgListOwner, DocCommentsOwner},
8 algo::find_node_at_offset,
11 use crate::{FilePosition, CallInfo, db::RootDatabase};
13 /// Computes parameter information for the given call expression.
14 pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Cancelable<Option<CallInfo>> {
15 let file = db.source_file(position.file_id);
16 let syntax = file.syntax();
18 // Find the calling expression and it's NameRef
19 let calling_node = ctry!(FnCallNode::with_node(syntax, position.offset));
20 let name_ref = ctry!(calling_node.name_ref());
22 // Resolve the function's NameRef (NOTE: this isn't entirely accurate).
23 let file_symbols = db.index_resolve(name_ref);
24 let symbol = ctry!(file_symbols.into_iter().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 = ctry!(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();
35 call_info.active_parameter = Some(0);
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();
46 let range_search = TextRange::from_to(start, position.offset);
47 let mut commas: usize = arg_list
55 // If we have a method call eat the first param since it's just self.
60 call_info.active_parameter = Some(commas);
68 CallExpr(&'a ast::CallExpr),
69 MethodCallExpr(&'a ast::MethodCallExpr),
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));
77 if let Some(expr) = find_node_at_offset::<ast::MethodCallExpr>(syntax, offset) {
78 return Some(FnCallNode::MethodCallExpr(expr));
83 pub fn name_ref(&self) -> Option<&'a ast::NameRef> {
85 FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()?.kind() {
86 ast::ExprKind::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
90 FnCallNode::MethodCallExpr(call_expr) => call_expr
93 .filter_map(ast::NameRef::cast)
98 pub fn arg_list(&self) -> Option<&'a ast::ArgList> {
100 FnCallNode::CallExpr(expr) => expr.arg_list(),
101 FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
107 fn new(node: &ast::FnDef) -> Option<Self> {
110 // Strip the body out for the label.
111 let mut label: String = if let Some(body) = node.body() {
112 let body_range = body.syntax().range();
113 let label: String = node
116 .filter(|child| !child.range().is_subrange(&body_range))
117 .map(|node| node.text().to_string())
121 node.syntax().text().to_string()
124 if let Some((comment_range, docs)) = extract_doc_comments(node) {
125 let comment_range = comment_range
126 .checked_sub(node.syntax().range().start())
128 let start = comment_range.start().to_usize();
129 let end = comment_range.end().to_usize();
131 // Remove the comment from the label
132 label.replace_range(start..end, "");
135 let mut processed_lines = Vec::new();
136 let mut in_code_block = false;
137 for line in docs.lines() {
138 if line.starts_with("```") {
139 in_code_block = !in_code_block;
142 let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
148 processed_lines.push(line);
151 if !processed_lines.is_empty() {
152 doc = Some(processed_lines.join("\n"));
157 parameters: param_list(node),
158 label: label.trim().to_owned(),
160 active_parameter: None,
165 fn extract_doc_comments(node: &ast::FnDef) -> Option<(TextRange, String)> {
166 if node.doc_comments().count() == 0 {
170 let comment_text = node.doc_comment_text();
172 let (begin, end) = node
174 .map(|comment| comment.syntax().range())
175 .map(|range| (range.start().to_usize(), range.end().to_usize()))
176 .fold((std::usize::MAX, std::usize::MIN), |acc, range| {
177 (min(acc.0, range.0), max(acc.1, range.1))
180 let range = TextRange::from_to(TextUnit::from_usize(begin), TextUnit::from_usize(end));
182 Some((range, comment_text))
185 fn param_list(node: &ast::FnDef) -> Vec<String> {
186 let mut res = vec![];
187 if let Some(param_list) = node.param_list() {
188 if let Some(self_param) = param_list.self_param() {
189 res.push(self_param.syntax().text().to_string())
192 // Maybe use param.pat here? See if we can just extract the name?
193 //res.extend(param_list.params().map(|p| p.syntax().text().to_string()));
197 .filter_map(|p| p.pat())
198 .map(|pat| pat.syntax().text().to_string()),
208 use crate::mock_analysis::single_file_with_position;
210 fn call_info(text: &str) -> CallInfo {
211 let (analysis, position) = single_file_with_position(text);
212 analysis.call_info(position).unwrap().unwrap()
216 fn test_fn_signature_two_args_first() {
217 let info = call_info(
218 r#"fn foo(x: u32, y: u32) -> u32 {x + y}
219 fn bar() { foo(<|>3, ); }"#,
222 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
223 assert_eq!(info.active_parameter, Some(0));
227 fn test_fn_signature_two_args_second() {
228 let info = call_info(
229 r#"fn foo(x: u32, y: u32) -> u32 {x + y}
230 fn bar() { foo(3, <|>); }"#,
233 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
234 assert_eq!(info.active_parameter, Some(1));
238 fn test_fn_signature_for_impl() {
239 let info = call_info(
240 r#"struct F; impl F { pub fn new() { F{}} }
241 fn bar() {let _ : F = F::new(<|>);}"#,
244 assert_eq!(info.parameters, Vec::<String>::new());
245 assert_eq!(info.active_parameter, None);
249 fn test_fn_signature_for_method_self() {
250 let info = call_info(
257 pub fn do_it(&self) {}
261 let f : F = F::new();
266 assert_eq!(info.parameters, vec!["&self".to_string()]);
267 assert_eq!(info.active_parameter, None);
271 fn test_fn_signature_for_method_with_arg() {
272 let info = call_info(
279 pub fn do_it(&self, x: i32) {}
283 let f : F = F::new();
288 assert_eq!(info.parameters, vec!["&self".to_string(), "x".to_string()]);
289 assert_eq!(info.active_parameter, Some(1));
293 fn test_fn_signature_with_docs_simple() {
294 let info = call_info(
298 fn foo(j: u32) -> u32 {
308 assert_eq!(info.parameters, vec!["j".to_string()]);
309 assert_eq!(info.active_parameter, Some(0));
310 assert_eq!(info.label, "fn foo(j: u32) -> u32".to_string());
311 assert_eq!(info.doc, Some("test".into()));
315 fn test_fn_signature_with_docs() {
316 let info = call_info(
318 /// Adds one to the number given.
325 /// assert_eq!(6, my_crate::add_one(5));
327 pub fn add_one(x: i32) -> i32 {
336 assert_eq!(info.parameters, vec!["x".to_string()]);
337 assert_eq!(info.active_parameter, Some(0));
338 assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
342 r#"Adds one to the number given.
349 assert_eq!(6, my_crate::add_one(5));
357 fn test_fn_signature_with_docs_impl() {
358 let info = call_info(
362 /// Adds one to the number given.
369 /// assert_eq!(6, my_crate::add_one(5));
371 pub fn add_one(x: i32) -> i32 {
382 assert_eq!(info.parameters, vec!["x".to_string()]);
383 assert_eq!(info.active_parameter, Some(0));
384 assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
388 r#"Adds one to the number given.
395 assert_eq!(6, my_crate::add_one(5));
403 fn test_fn_signature_with_docs_from_actix() {
404 let info = call_info(
406 pub trait WriteHandler<E>
409 Self::Context: ActorContext,
411 /// Method is called when writer emits error.
413 /// If this method returns `ErrorAction::Continue` writer processing
414 /// continues otherwise stream processing stops.
415 fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
419 /// Method is called when writer finishes.
421 /// By default this method stops actor's `Context`.
422 fn finished(&mut self, ctx: &mut Self::Context) {
437 vec!["&mut self".to_string(), "ctx".to_string()]
439 assert_eq!(info.active_parameter, Some(1));
443 r#"Method is called when writer finishes.
445 By default this method stops actor's `Context`."#