1 use ra_db::SourceDatabase;
3 AstNode, SyntaxNode, TextUnit, TextRange,
5 ast::{self, ArgListOwner, DocCommentsOwner},
6 algo::find_node_at_offset,
9 use crate::{FilePosition, CallInfo, db::RootDatabase};
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();
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()?;
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
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();
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> {
108 let label: String = if let Some(body) = node.body() {
109 let body_range = body.syntax().range();
110 let label: String = node
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())
119 node.syntax().text().to_string()
123 if let Some(docs) = node.doc_comment_text() {
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;
132 let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
138 processed_lines.push(line);
141 doc = Some(processed_lines.join("\n"));
145 parameters: param_list(node),
146 label: label.trim().to_owned(),
148 active_parameter: None,
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())
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()));
165 .filter_map(|p| p.pat())
166 .map(|pat| pat.syntax().text().to_string()),
176 use crate::mock_analysis::single_file_with_position;
178 fn call_info(text: &str) -> CallInfo {
179 let (analysis, position) = single_file_with_position(text);
180 analysis.call_info(position).unwrap().unwrap()
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, ); }"#,
190 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
191 assert_eq!(info.active_parameter, Some(0));
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, <|>); }"#,
201 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
202 assert_eq!(info.active_parameter, Some(1));
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(<|>);}"#,
212 assert_eq!(info.parameters, Vec::<String>::new());
213 assert_eq!(info.active_parameter, None);
217 fn test_fn_signature_for_method_self() {
218 let info = call_info(
225 pub fn do_it(&self) {}
229 let f : F = F::new();
234 assert_eq!(info.parameters, vec!["&self".to_string()]);
235 assert_eq!(info.active_parameter, None);
239 fn test_fn_signature_for_method_with_arg() {
240 let info = call_info(
247 pub fn do_it(&self, x: i32) {}
251 let f : F = F::new();
256 assert_eq!(info.parameters, vec!["&self".to_string(), "x".to_string()]);
257 assert_eq!(info.active_parameter, Some(1));
261 fn test_fn_signature_with_docs_simple() {
262 let info = call_info(
266 fn foo(j: u32) -> u32 {
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()));
283 fn test_fn_signature_with_docs() {
284 let info = call_info(
286 /// Adds one to the number given.
293 /// assert_eq!(6, my_crate::add_one(5));
295 pub fn add_one(x: i32) -> i32 {
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());
310 r#"Adds one to the number given.
317 assert_eq!(6, my_crate::add_one(5));
325 fn test_fn_signature_with_docs_impl() {
326 let info = call_info(
330 /// Adds one to the number given.
337 /// assert_eq!(6, my_crate::add_one(5));
339 pub fn add_one(x: i32) -> i32 {
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());
356 r#"Adds one to the number given.
363 assert_eq!(6, my_crate::add_one(5));
371 fn test_fn_signature_with_docs_from_actix() {
372 let info = call_info(
374 pub trait WriteHandler<E>
377 Self::Context: ActorContext,
379 /// Method is called when writer emits error.
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 {
387 /// Method is called when writer finishes.
389 /// By default this method stops actor's `Context`.
390 fn finished(&mut self, ctx: &mut Self::Context) {
405 vec!["&mut self".to_string(), "ctx".to_string()]
407 assert_eq!(info.active_parameter, Some(1));
411 r#"Method is called when writer finishes.
413 By default this method stops actor's `Context`."#