1 use ra_db::SyntaxDatabase;
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.source_file(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.source_file(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 let docs = node.doc_comment_text();
124 if !docs.is_empty() {
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;
133 let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
139 processed_lines.push(line);
142 doc = Some(processed_lines.join("\n"));
146 parameters: param_list(node),
147 label: label.trim().to_owned(),
149 active_parameter: None,
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())
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()));
166 .filter_map(|p| p.pat())
167 .map(|pat| pat.syntax().text().to_string()),
177 use crate::mock_analysis::single_file_with_position;
179 fn call_info(text: &str) -> CallInfo {
180 let (analysis, position) = single_file_with_position(text);
181 analysis.call_info(position).unwrap().unwrap()
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, ); }"#,
191 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
192 assert_eq!(info.active_parameter, Some(0));
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, <|>); }"#,
202 assert_eq!(info.parameters, vec!("x".to_string(), "y".to_string()));
203 assert_eq!(info.active_parameter, Some(1));
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(<|>);}"#,
213 assert_eq!(info.parameters, Vec::<String>::new());
214 assert_eq!(info.active_parameter, None);
218 fn test_fn_signature_for_method_self() {
219 let info = call_info(
226 pub fn do_it(&self) {}
230 let f : F = F::new();
235 assert_eq!(info.parameters, vec!["&self".to_string()]);
236 assert_eq!(info.active_parameter, None);
240 fn test_fn_signature_for_method_with_arg() {
241 let info = call_info(
248 pub fn do_it(&self, x: i32) {}
252 let f : F = F::new();
257 assert_eq!(info.parameters, vec!["&self".to_string(), "x".to_string()]);
258 assert_eq!(info.active_parameter, Some(1));
262 fn test_fn_signature_with_docs_simple() {
263 let info = call_info(
267 fn foo(j: u32) -> u32 {
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()));
284 fn test_fn_signature_with_docs() {
285 let info = call_info(
287 /// Adds one to the number given.
294 /// assert_eq!(6, my_crate::add_one(5));
296 pub fn add_one(x: i32) -> i32 {
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());
311 r#"Adds one to the number given.
318 assert_eq!(6, my_crate::add_one(5));
326 fn test_fn_signature_with_docs_impl() {
327 let info = call_info(
331 /// Adds one to the number given.
338 /// assert_eq!(6, my_crate::add_one(5));
340 pub fn add_one(x: i32) -> i32 {
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());
357 r#"Adds one to the number given.
364 assert_eq!(6, my_crate::add_one(5));
372 fn test_fn_signature_with_docs_from_actix() {
373 let info = call_info(
375 pub trait WriteHandler<E>
378 Self::Context: ActorContext,
380 /// Method is called when writer emits error.
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 {
388 /// Method is called when writer finishes.
390 /// By default this method stops actor's `Context`.
391 fn finished(&mut self, ctx: &mut Self::Context) {
406 vec!["&mut self".to_string(), "ctx".to_string()]
408 assert_eq!(info.active_parameter, Some(1));
412 r#"Method is called when writer finishes.
414 By default this method stops actor's `Context`."#