rust-analyzer/crates/ide_db/src/call_info.rs

232 lines
7.5 KiB
Rust
Raw Normal View History

//! This crate provides primitives for tracking the information about a call site.
use base_db::FilePosition;
use either::Either;
use hir::{HasAttrs, HirDisplay, Semantics, Type};
2020-08-12 16:26:51 +00:00
use stdx::format_to;
use syntax::{
ast::{self, ArgListOwner},
2020-07-16 11:00:56 +00:00
match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize,
2019-01-08 19:33:36 +00:00
};
2020-05-20 10:59:20 +00:00
use test_utils::mark;
2019-01-08 19:33:36 +00:00
2020-10-24 08:07:10 +00:00
use crate::RootDatabase;
2020-07-16 08:29:21 +00:00
/// Contains information about a call site. Specifically the
/// `FunctionSignature`and current parameter.
#[derive(Debug)]
pub struct CallInfo {
2020-07-16 11:00:56 +00:00
pub doc: Option<String>,
pub signature: String,
2020-07-16 08:29:21 +00:00
pub active_parameter: Option<usize>,
2020-07-16 11:00:56 +00:00
parameters: Vec<TextRange>,
}
impl CallInfo {
pub fn parameter_labels(&self) -> impl Iterator<Item = &str> + '_ {
self.parameters.iter().map(move |&it| &self.signature[it])
}
pub fn parameter_ranges(&self) -> &[TextRange] {
&self.parameters
}
fn push_param(&mut self, param: &str) {
if !self.signature.ends_with('(') {
self.signature.push_str(", ");
}
let start = TextSize::of(&self.signature);
self.signature.push_str(param);
let end = TextSize::of(&self.signature);
self.parameters.push(TextRange::new(start, end))
}
2020-07-16 08:29:21 +00:00
}
2019-01-08 19:33:36 +00:00
/// Computes parameter information for the given call expression.
pub fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
let sema = Semantics::new(db);
let file = sema.parse(position.file_id);
let file = file.syntax();
let token = file.token_at_offset(position.offset).next()?;
let token = sema.descend_into_macros(token);
2019-01-08 19:33:36 +00:00
2020-07-16 11:00:56 +00:00
let (callable, active_parameter) = call_info_impl(&sema, token)?;
2020-04-23 23:46:00 +00:00
2020-07-16 11:00:56 +00:00
let mut res =
CallInfo { doc: None, signature: String::new(), parameters: vec![], active_parameter };
match callable.kind() {
hir::CallableKind::Function(func) => {
res.doc = func.docs(db).map(|it| it.as_str().to_string());
format_to!(res.signature, "fn {}", func.name(db));
}
hir::CallableKind::TupleStruct(strukt) => {
res.doc = strukt.docs(db).map(|it| it.as_str().to_string());
format_to!(res.signature, "struct {}", strukt.name(db));
}
hir::CallableKind::TupleEnumVariant(variant) => {
res.doc = variant.docs(db).map(|it| it.as_str().to_string());
format_to!(
res.signature,
"enum {}::{}",
variant.parent_enum(db).name(db),
variant.name(db)
);
}
2020-07-17 08:57:49 +00:00
hir::CallableKind::Closure => (),
2020-04-23 23:46:00 +00:00
}
2020-07-16 11:00:56 +00:00
res.signature.push('(');
{
if let Some(self_param) = callable.receiver_param(db) {
format_to!(res.signature, "{}", self_param)
}
let mut buf = String::new();
for (pat, ty) in callable.params(db) {
buf.clear();
if let Some(pat) = pat {
match pat {
Either::Left(_self) => format_to!(buf, "self: "),
Either::Right(pat) => format_to!(buf, "{}: ", pat),
}
2020-07-16 11:00:56 +00:00
}
format_to!(buf, "{}", ty.display(db));
res.push_param(&buf);
}
2020-04-23 23:46:00 +00:00
}
2020-07-16 11:00:56 +00:00
res.signature.push(')');
match callable.kind() {
2020-07-17 08:57:49 +00:00
hir::CallableKind::Function(_) | hir::CallableKind::Closure => {
2020-07-16 11:00:56 +00:00
let ret_type = callable.return_type();
if !ret_type.is_unit() {
format_to!(res.signature, " -> {}", ret_type.display(db));
}
}
hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_) => {}
}
Some(res)
2020-04-23 23:46:00 +00:00
}
2020-07-16 11:00:56 +00:00
fn call_info_impl(
sema: &Semantics<RootDatabase>,
token: SyntaxToken,
) -> Option<(hir::Callable, Option<usize>)> {
2019-01-08 19:33:36 +00:00
// Find the calling expression and it's NameRef
let calling_node = FnCallNode::with_node(&token.parent())?;
2019-01-08 19:33:36 +00:00
2020-07-16 11:00:56 +00:00
let callable = match &calling_node {
FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?,
FnCallNode::MethodCallExpr(call) => sema.resolve_method_call_as_callable(call)?,
};
let active_param = if let Some(arg_list) = calling_node.arg_list() {
// Number of arguments specified at the call site
let num_args_at_callsite = arg_list.args().count();
let arg_list_range = arg_list.syntax().text_range();
if !arg_list_range.contains_inclusive(token.text_range().start()) {
mark::hit!(call_info_bad_offset);
return None;
2019-10-29 16:16:55 +00:00
}
2020-07-16 11:00:56 +00:00
let param = std::cmp::min(
num_args_at_callsite,
arg_list
.args()
.take_while(|arg| arg.syntax().text_range().end() <= token.text_range().start())
.count(),
);
Some(param)
} else {
None
};
2020-07-16 11:00:56 +00:00
Some((callable, active_param))
}
2020-07-16 11:00:56 +00:00
#[derive(Debug)]
pub struct ActiveParameter {
pub ty: Type,
pub name: String,
2020-07-16 11:00:56 +00:00
}
2019-01-08 19:33:36 +00:00
2020-07-16 11:00:56 +00:00
impl ActiveParameter {
pub fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> {
2020-07-16 11:00:56 +00:00
let sema = Semantics::new(db);
let file = sema.parse(position.file_id);
let file = file.syntax();
let token = file.token_at_offset(position.offset).next()?;
let token = sema.descend_into_macros(token);
Self::at_token(&sema, token)
}
2019-01-08 19:33:36 +00:00
pub fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> {
2020-07-16 11:00:56 +00:00
let (signature, active_parameter) = call_info_impl(&sema, token)?;
2019-01-08 19:33:36 +00:00
2020-07-16 11:00:56 +00:00
let idx = active_parameter?;
let mut params = signature.params(sema.db);
if !(idx < params.len()) {
mark::hit!(too_many_arguments);
return None;
}
2020-07-16 11:00:56 +00:00
let (pat, ty) = params.swap_remove(idx);
let name = pat?.to_string();
Some(ActiveParameter { ty, name })
}
2019-01-08 19:33:36 +00:00
}
2019-10-29 16:16:55 +00:00
#[derive(Debug)]
pub enum FnCallNode {
2019-07-19 09:56:47 +00:00
CallExpr(ast::CallExpr),
MethodCallExpr(ast::MethodCallExpr),
2019-01-08 19:33:36 +00:00
}
2019-07-19 09:56:47 +00:00
impl FnCallNode {
fn with_node(syntax: &SyntaxNode) -> Option<FnCallNode> {
syntax.ancestors().find_map(|node| {
match_ast! {
match node {
2020-04-06 14:21:33 +00:00
ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
2020-02-27 15:05:35 +00:00
ast::MethodCallExpr(it) => {
let arg_list = it.arg_list()?;
2020-04-24 21:40:41 +00:00
if !arg_list.syntax().text_range().contains_range(syntax.text_range()) {
2020-02-27 15:05:35 +00:00
return None;
}
Some(FnCallNode::MethodCallExpr(it))
},
2020-04-06 14:21:33 +00:00
_ => None,
}
}
})
2019-01-08 19:33:36 +00:00
}
pub fn with_node_exact(node: &SyntaxNode) -> Option<FnCallNode> {
match_ast! {
match node {
2020-04-06 14:21:33 +00:00
ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
ast::MethodCallExpr(it) => Some(FnCallNode::MethodCallExpr(it)),
_ => None,
}
}
}
pub fn name_ref(&self) -> Option<ast::NameRef> {
2019-07-19 09:56:47 +00:00
match self {
2019-08-19 11:13:58 +00:00
FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? {
ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
2019-01-08 19:33:36 +00:00
_ => return None,
}),
2019-02-08 11:49:43 +00:00
FnCallNode::MethodCallExpr(call_expr) => {
2020-02-18 13:32:19 +00:00
call_expr.syntax().children().filter_map(ast::NameRef::cast).next()
2019-02-08 11:49:43 +00:00
}
2019-01-08 19:33:36 +00:00
}
}
2019-07-19 09:56:47 +00:00
fn arg_list(&self) -> Option<ast::ArgList> {
match self {
2019-01-08 19:33:36 +00:00
FnCallNode::CallExpr(expr) => expr.arg_list(),
FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
}
}
}
#[cfg(test)]
mod tests;