]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/call_info.rs
Use `todo!()` instead of `()` for missing fields
[rust.git] / crates / ide_db / src / call_info.rs
1 //! This crate provides primitives for tracking the information about a call site.
2 use base_db::FilePosition;
3 use either::Either;
4 use hir::{HasAttrs, HirDisplay, Semantics, Type};
5 use stdx::format_to;
6 use syntax::{
7     algo,
8     ast::{self, ArgListOwner, NameOwner},
9     match_ast, AstNode, Direction, SyntaxNode, SyntaxToken, TextRange, TextSize,
10 };
11
12 use crate::RootDatabase;
13
14 /// Contains information about a call site. Specifically the
15 /// `FunctionSignature`and current parameter.
16 #[derive(Debug)]
17 pub struct CallInfo {
18     pub doc: Option<String>,
19     pub signature: String,
20     pub active_parameter: Option<usize>,
21     parameters: Vec<TextRange>,
22 }
23
24 impl CallInfo {
25     pub fn parameter_labels(&self) -> impl Iterator<Item = &str> + '_ {
26         self.parameters.iter().map(move |&it| &self.signature[it])
27     }
28     pub fn parameter_ranges(&self) -> &[TextRange] {
29         &self.parameters
30     }
31     fn push_param(&mut self, param: &str) {
32         if !self.signature.ends_with('(') {
33             self.signature.push_str(", ");
34         }
35         let start = TextSize::of(&self.signature);
36         self.signature.push_str(param);
37         let end = TextSize::of(&self.signature);
38         self.parameters.push(TextRange::new(start, end))
39     }
40 }
41
42 /// Computes parameter information for the given call expression.
43 pub fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
44     let sema = Semantics::new(db);
45     let file = sema.parse(position.file_id);
46     let file = file.syntax();
47     let token = file
48         .token_at_offset(position.offset)
49         .left_biased()
50         // if the cursor is sandwiched between two space tokens and the call is unclosed
51         // this prevents us from leaving the CallExpression
52         .and_then(|tok| algo::skip_trivia_token(tok, Direction::Prev))?;
53     let token = sema.descend_into_macros(token);
54
55     let (callable, active_parameter) = call_info_impl(&sema, token)?;
56
57     let mut res =
58         CallInfo { doc: None, signature: String::new(), parameters: vec![], active_parameter };
59
60     match callable.kind() {
61         hir::CallableKind::Function(func) => {
62             res.doc = func.docs(db).map(|it| it.into());
63             format_to!(res.signature, "fn {}", func.name(db));
64         }
65         hir::CallableKind::TupleStruct(strukt) => {
66             res.doc = strukt.docs(db).map(|it| it.into());
67             format_to!(res.signature, "struct {}", strukt.name(db));
68         }
69         hir::CallableKind::TupleEnumVariant(variant) => {
70             res.doc = variant.docs(db).map(|it| it.into());
71             format_to!(
72                 res.signature,
73                 "enum {}::{}",
74                 variant.parent_enum(db).name(db),
75                 variant.name(db)
76             );
77         }
78         hir::CallableKind::Closure => (),
79     }
80
81     res.signature.push('(');
82     {
83         if let Some(self_param) = callable.receiver_param(db) {
84             format_to!(res.signature, "{}", self_param)
85         }
86         let mut buf = String::new();
87         for (pat, ty) in callable.params(db) {
88             buf.clear();
89             if let Some(pat) = pat {
90                 match pat {
91                     Either::Left(_self) => format_to!(buf, "self: "),
92                     Either::Right(pat) => format_to!(buf, "{}: ", pat),
93                 }
94             }
95             format_to!(buf, "{}", ty.display(db));
96             res.push_param(&buf);
97         }
98     }
99     res.signature.push(')');
100
101     match callable.kind() {
102         hir::CallableKind::Function(_) | hir::CallableKind::Closure => {
103             let ret_type = callable.return_type();
104             if !ret_type.is_unit() {
105                 format_to!(res.signature, " -> {}", ret_type.display(db));
106             }
107         }
108         hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_) => {}
109     }
110     Some(res)
111 }
112
113 fn call_info_impl(
114     sema: &Semantics<RootDatabase>,
115     token: SyntaxToken,
116 ) -> Option<(hir::Callable, Option<usize>)> {
117     // Find the calling expression and it's NameRef
118     let calling_node = FnCallNode::with_node(&token.parent()?)?;
119
120     let callable = match &calling_node {
121         FnCallNode::CallExpr(call) => {
122             sema.type_of_expr(&call.expr()?)?.adjusted().as_callable(sema.db)?
123         }
124         FnCallNode::MethodCallExpr(call) => sema.resolve_method_call_as_callable(call)?,
125     };
126     let active_param = if let Some(arg_list) = calling_node.arg_list() {
127         // Number of arguments specified at the call site
128         let num_args_at_callsite = arg_list.args().count();
129
130         let arg_list_range = arg_list.syntax().text_range();
131         if !arg_list_range.contains_inclusive(token.text_range().start()) {
132             cov_mark::hit!(call_info_bad_offset);
133             return None;
134         }
135         let param = std::cmp::min(
136             num_args_at_callsite,
137             arg_list
138                 .args()
139                 .take_while(|arg| arg.syntax().text_range().end() <= token.text_range().start())
140                 .count(),
141         );
142
143         Some(param)
144     } else {
145         None
146     };
147     Some((callable, active_param))
148 }
149
150 #[derive(Debug)]
151 pub struct ActiveParameter {
152     pub ty: Type,
153     pub pat: Either<ast::SelfParam, ast::Pat>,
154 }
155
156 impl ActiveParameter {
157     pub fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> {
158         let sema = Semantics::new(db);
159         let file = sema.parse(position.file_id);
160         let file = file.syntax();
161         let token = file.token_at_offset(position.offset).next()?;
162         let token = sema.descend_into_macros(token);
163         Self::at_token(&sema, token)
164     }
165
166     pub fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> {
167         let (signature, active_parameter) = call_info_impl(sema, token)?;
168
169         let idx = active_parameter?;
170         let mut params = signature.params(sema.db);
171         if !(idx < params.len()) {
172             cov_mark::hit!(too_many_arguments);
173             return None;
174         }
175         let (pat, ty) = params.swap_remove(idx);
176         pat.map(|pat| ActiveParameter { ty, pat })
177     }
178
179     pub fn ident(&self) -> Option<ast::Name> {
180         self.pat.as_ref().right().and_then(|param| match param {
181             ast::Pat::IdentPat(ident) => ident.name(),
182             _ => None,
183         })
184     }
185 }
186
187 #[derive(Debug)]
188 pub enum FnCallNode {
189     CallExpr(ast::CallExpr),
190     MethodCallExpr(ast::MethodCallExpr),
191 }
192
193 impl FnCallNode {
194     fn with_node(syntax: &SyntaxNode) -> Option<FnCallNode> {
195         syntax.ancestors().find_map(|node| {
196             match_ast! {
197                 match node {
198                     ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
199                     ast::MethodCallExpr(it) => {
200                         let arg_list = it.arg_list()?;
201                         if !arg_list.syntax().text_range().contains_range(syntax.text_range()) {
202                             return None;
203                         }
204                         Some(FnCallNode::MethodCallExpr(it))
205                     },
206                     _ => None,
207                 }
208             }
209         })
210     }
211
212     pub fn with_node_exact(node: &SyntaxNode) -> Option<FnCallNode> {
213         match_ast! {
214             match node {
215                 ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
216                 ast::MethodCallExpr(it) => Some(FnCallNode::MethodCallExpr(it)),
217                 _ => None,
218             }
219         }
220     }
221
222     pub fn name_ref(&self) -> Option<ast::NameRef> {
223         match self {
224             FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? {
225                 ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
226                 _ => return None,
227             }),
228             FnCallNode::MethodCallExpr(call_expr) => {
229                 call_expr.syntax().children().find_map(ast::NameRef::cast)
230             }
231         }
232     }
233
234     fn arg_list(&self) -> Option<ast::ArgList> {
235         match self {
236             FnCallNode::CallExpr(expr) => expr.arg_list(),
237             FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
238         }
239     }
240 }
241
242 #[cfg(test)]
243 mod tests;