1 use test_utils::tested_by;
2 use ra_db::SourceDatabase;
4 AstNode, SyntaxNode, TextUnit, TextRange,
6 ast::{self, ArgListOwner, DocCommentsOwner},
7 algo::find_node_at_offset,
10 use crate::{FilePosition, CallInfo, db::RootDatabase};
12 /// Computes parameter information for the given call expression.
13 pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
14 let file = db.parse(position.file_id);
15 let syntax = file.syntax();
17 // Find the calling expression and it's NameRef
18 let calling_node = FnCallNode::with_node(syntax, position.offset)?;
19 let name_ref = calling_node.name_ref()?;
21 // Resolve the function's NameRef (NOTE: this isn't entirely accurate).
22 let file_symbols = db.index_resolve(name_ref);
23 let symbol = file_symbols
25 .find(|it| it.ptr.kind() == FN_DEF)?;
26 let fn_file = db.parse(symbol.file_id);
27 let fn_def = symbol.ptr.to_node(&fn_file);
28 let fn_def = ast::FnDef::cast(fn_def).unwrap();
29 let mut call_info = CallInfo::new(fn_def)?;
30 // If we have a calling expression let's find which argument we are on
31 let num_params = call_info.parameters.len();
32 let has_self = fn_def.param_list().and_then(|l| l.self_param()).is_some();
36 call_info.active_parameter = Some(0);
38 } else if num_params > 1 {
39 // Count how many parameters into the call we are.
40 // TODO: This is best effort for now and should be fixed at some point.
41 // It may be better to see where we are in the arg_list and then check
42 // where offset is in that list (or beyond).
43 // Revisit this after we get documentation comments in.
44 if let Some(ref arg_list) = calling_node.arg_list() {
45 let arg_list_range = arg_list.syntax().range();
46 if !arg_list_range.contains_inclusive(position.offset) {
47 tested_by!(call_info_bad_offset);
50 let start = arg_list_range.start();
52 let range_search = TextRange::from_to(start, position.offset);
53 let mut commas: usize = arg_list
61 // If we have a method call eat the first param since it's just self.
66 call_info.active_parameter = Some(commas);
74 CallExpr(&'a ast::CallExpr),
75 MethodCallExpr(&'a ast::MethodCallExpr),
78 impl<'a> FnCallNode<'a> {
79 pub fn with_node(syntax: &'a SyntaxNode, offset: TextUnit) -> Option<FnCallNode<'a>> {
80 if let Some(expr) = find_node_at_offset::<ast::CallExpr>(syntax, offset) {
81 return Some(FnCallNode::CallExpr(expr));
83 if let Some(expr) = find_node_at_offset::<ast::MethodCallExpr>(syntax, offset) {
84 return Some(FnCallNode::MethodCallExpr(expr));
89 pub fn name_ref(&self) -> Option<&'a ast::NameRef> {
91 FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()?.kind() {
92 ast::ExprKind::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
96 FnCallNode::MethodCallExpr(call_expr) => call_expr
99 .filter_map(ast::NameRef::cast)
104 pub fn arg_list(&self) -> Option<&'a ast::ArgList> {
106 FnCallNode::CallExpr(expr) => expr.arg_list(),
107 FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
113 fn new(node: &ast::FnDef) -> Option<Self> {
114 let label: String = if let Some(body) = node.body() {
115 let body_range = body.syntax().range();
116 let label: String = node
119 .filter(|child| !child.range().is_subrange(&body_range)) // Filter out body
120 .filter(|child| ast::Comment::cast(child).is_none()) // Filter out doc comments
121 .map(|node| node.text().to_string())
125 node.syntax().text().to_string()
129 if let Some(docs) = node.doc_comment_text() {
131 let mut processed_lines = Vec::new();
132 let mut in_code_block = false;
133 for line in docs.lines() {
134 if line.starts_with("```") {
135 in_code_block = !in_code_block;
138 let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
144 processed_lines.push(line);
147 doc = Some(processed_lines.join("\n"));
151 parameters: param_list(node),
152 label: label.trim().to_owned(),
154 active_parameter: None,
159 fn param_list(node: &ast::FnDef) -> Vec<String> {
160 let mut res = vec![];
161 if let Some(param_list) = node.param_list() {
162 if let Some(self_param) = param_list.self_param() {
163 res.push(self_param.syntax().text().to_string())
166 // Maybe use param.pat here? See if we can just extract the name?
167 //res.extend(param_list.params().map(|p| p.syntax().text().to_string()));
171 .filter_map(|p| p.pat())
172 .map(|pat| pat.syntax().text().to_string()),
180 use test_utils::covers;
182 use crate::mock_analysis::single_file_with_position;
186 fn call_info(text: &str) -> CallInfo {
187 let (analysis, position) = single_file_with_position(text);
188 analysis.call_info(position).unwrap().unwrap()
192 fn test_fn_signature_two_args_first() {
193 let info = call_info(
194 r#"fn foo(x: u32, y: u32) -> u32 {x + y}
195 fn bar() { foo(<|>3, ); }"#,
198 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
199 assert_eq!(info.active_parameter, Some(0));
203 fn test_fn_signature_two_args_second() {
204 let info = call_info(
205 r#"fn foo(x: u32, y: u32) -> u32 {x + y}
206 fn bar() { foo(3, <|>); }"#,
209 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
210 assert_eq!(info.active_parameter, Some(1));
214 fn test_fn_signature_for_impl() {
215 let info = call_info(
216 r#"struct F; impl F { pub fn new() { F{}} }
217 fn bar() {let _ : F = F::new(<|>);}"#,
220 assert_eq!(info.parameters, Vec::<String>::new());
221 assert_eq!(info.active_parameter, None);
225 fn test_fn_signature_for_method_self() {
226 let info = call_info(
233 pub fn do_it(&self) {}
237 let f : F = F::new();
242 assert_eq!(info.parameters, vec!["&self".to_string()]);
243 assert_eq!(info.active_parameter, None);
247 fn test_fn_signature_for_method_with_arg() {
248 let info = call_info(
255 pub fn do_it(&self, x: i32) {}
259 let f : F = F::new();
264 assert_eq!(info.parameters, vec!["&self".to_string(), "x".to_string()]);
265 assert_eq!(info.active_parameter, Some(1));
269 fn test_fn_signature_with_docs_simple() {
270 let info = call_info(
274 fn foo(j: u32) -> u32 {
284 assert_eq!(info.parameters, vec!["j".to_string()]);
285 assert_eq!(info.active_parameter, Some(0));
286 assert_eq!(info.label, "fn foo(j: u32) -> u32".to_string());
287 assert_eq!(info.doc, Some("test".into()));
291 fn test_fn_signature_with_docs() {
292 let info = call_info(
294 /// Adds one to the number given.
301 /// assert_eq!(6, my_crate::add_one(5));
303 pub fn add_one(x: i32) -> i32 {
312 assert_eq!(info.parameters, vec!["x".to_string()]);
313 assert_eq!(info.active_parameter, Some(0));
314 assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
318 r#"Adds one to the number given.
325 assert_eq!(6, my_crate::add_one(5));
333 fn test_fn_signature_with_docs_impl() {
334 let info = call_info(
338 /// Adds one to the number given.
345 /// assert_eq!(6, my_crate::add_one(5));
347 pub fn add_one(x: i32) -> i32 {
358 assert_eq!(info.parameters, vec!["x".to_string()]);
359 assert_eq!(info.active_parameter, Some(0));
360 assert_eq!(info.label, "pub fn add_one(x: i32) -> i32".to_string());
364 r#"Adds one to the number given.
371 assert_eq!(6, my_crate::add_one(5));
379 fn test_fn_signature_with_docs_from_actix() {
380 let info = call_info(
382 pub trait WriteHandler<E>
385 Self::Context: ActorContext,
387 /// Method is called when writer emits error.
389 /// If this method returns `ErrorAction::Continue` writer processing
390 /// continues otherwise stream processing stops.
391 fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
395 /// Method is called when writer finishes.
397 /// By default this method stops actor's `Context`.
398 fn finished(&mut self, ctx: &mut Self::Context) {
413 vec!["&mut self".to_string(), "ctx".to_string()]
415 assert_eq!(info.active_parameter, Some(1));
419 r#"Method is called when writer finishes.
421 By default this method stops actor's `Context`."#
428 fn call_info_bad_offset() {
429 covers!(call_info_bad_offset);
430 let (analysis, position) = single_file_with_position(
431 r#"fn foo(x: u32, y: u32) -> u32 {x + y}
432 fn bar() { foo <|> (3, ); }"#,
434 let call_info = analysis.call_info(position).unwrap();
435 assert!(call_info.is_none());