From b6ea56ea091ad1dbd765831d8dfe79e4d3cdf004 Mon Sep 17 00:00:00 2001 From: Igor Aleksanov Date: Sat, 24 Oct 2020 11:07:10 +0300 Subject: Make call_info a part of ide_db --- Cargo.lock | 17 +- crates/call_info/Cargo.toml | 26 - crates/call_info/src/lib.rs | 755 ----------------------- crates/completion/Cargo.toml | 1 - crates/completion/src/completion_context.rs | 3 +- crates/ide/Cargo.toml | 1 - crates/ide/src/call_hierarchy.rs | 2 +- crates/ide/src/lib.rs | 4 +- crates/ide/src/syntax_highlighting/injection.rs | 2 +- crates/ide_db/Cargo.toml | 3 + crates/ide_db/src/call_info.rs | 756 ++++++++++++++++++++++++ crates/ide_db/src/lib.rs | 1 + 12 files changed, 766 insertions(+), 805 deletions(-) delete mode 100644 crates/call_info/Cargo.toml delete mode 100644 crates/call_info/src/lib.rs create mode 100644 crates/ide_db/src/call_info.rs diff --git a/Cargo.lock b/Cargo.lock index a69aef199..bc0f0862d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -127,20 +127,6 @@ version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" -[[package]] -name = "call_info" -version = "0.0.0" -dependencies = [ - "base_db", - "either", - "expect-test", - "hir", - "ide_db", - "stdx", - "syntax", - "test_utils", -] - [[package]] name = "cargo_metadata" version = "0.12.0" @@ -269,7 +255,6 @@ name = "completion" version = "0.0.0" dependencies = [ "base_db", - "call_info", "expect-test", "hir", "ide_db", @@ -643,7 +628,6 @@ version = "0.0.0" dependencies = [ "assists", "base_db", - "call_info", "cfg", "completion", "either", @@ -672,6 +656,7 @@ version = "0.0.0" dependencies = [ "base_db", "either", + "expect-test", "fst", "hir", "log", diff --git a/crates/call_info/Cargo.toml b/crates/call_info/Cargo.toml deleted file mode 100644 index 98c0bd6db..000000000 --- a/crates/call_info/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "call_info" -version = "0.0.0" -description = "TBD" -license = "MIT OR Apache-2.0" -authors = ["rust-analyzer developers"] -edition = "2018" - -[lib] -doctest = false - -[dependencies] -either = "1.5.3" - -stdx = { path = "../stdx", version = "0.0.0" } -syntax = { path = "../syntax", version = "0.0.0" } -base_db = { path = "../base_db", version = "0.0.0" } -ide_db = { path = "../ide_db", version = "0.0.0" } -test_utils = { path = "../test_utils", version = "0.0.0" } - -# call_info crate should depend only on the top-level `hir` package. if you need -# something from some `hir_xxx` subpackage, reexport the API via `hir`. -hir = { path = "../hir", version = "0.0.0" } - -[dev-dependencies] -expect-test = "1.0" diff --git a/crates/call_info/src/lib.rs b/crates/call_info/src/lib.rs deleted file mode 100644 index c45406c25..000000000 --- a/crates/call_info/src/lib.rs +++ /dev/null @@ -1,755 +0,0 @@ -//! 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}; -use ide_db::RootDatabase; -use stdx::format_to; -use syntax::{ - ast::{self, ArgListOwner}, - match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize, -}; -use test_utils::mark; - -/// Contains information about a call site. Specifically the -/// `FunctionSignature`and current parameter. -#[derive(Debug)] -pub struct CallInfo { - pub doc: Option, - pub signature: String, - pub active_parameter: Option, - parameters: Vec, -} - -impl CallInfo { - pub fn parameter_labels(&self) -> impl Iterator + '_ { - 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)) - } -} - -/// Computes parameter information for the given call expression. -pub fn call_info(db: &RootDatabase, position: FilePosition) -> Option { - 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); - - let (callable, active_parameter) = call_info_impl(&sema, token)?; - - 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) - ); - } - hir::CallableKind::Closure => (), - } - - 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), - } - } - format_to!(buf, "{}", ty.display(db)); - res.push_param(&buf); - } - } - res.signature.push(')'); - - match callable.kind() { - hir::CallableKind::Function(_) | hir::CallableKind::Closure => { - 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) -} - -fn call_info_impl( - sema: &Semantics, - token: SyntaxToken, -) -> Option<(hir::Callable, Option)> { - // Find the calling expression and it's NameRef - let calling_node = FnCallNode::with_node(&token.parent())?; - - 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; - } - 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 - }; - Some((callable, active_param)) -} - -#[derive(Debug)] -pub struct ActiveParameter { - pub ty: Type, - pub name: String, -} - -impl ActiveParameter { - pub fn at(db: &RootDatabase, position: FilePosition) -> Option { - 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) - } - - pub fn at_token(sema: &Semantics, token: SyntaxToken) -> Option { - let (signature, active_parameter) = call_info_impl(&sema, token)?; - - let idx = active_parameter?; - let mut params = signature.params(sema.db); - if !(idx < params.len()) { - mark::hit!(too_many_arguments); - return None; - } - let (pat, ty) = params.swap_remove(idx); - let name = pat?.to_string(); - Some(ActiveParameter { ty, name }) - } -} - -#[derive(Debug)] -pub enum FnCallNode { - CallExpr(ast::CallExpr), - MethodCallExpr(ast::MethodCallExpr), -} - -impl FnCallNode { - fn with_node(syntax: &SyntaxNode) -> Option { - syntax.ancestors().find_map(|node| { - match_ast! { - match node { - ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)), - ast::MethodCallExpr(it) => { - let arg_list = it.arg_list()?; - if !arg_list.syntax().text_range().contains_range(syntax.text_range()) { - return None; - } - Some(FnCallNode::MethodCallExpr(it)) - }, - _ => None, - } - } - }) - } - - pub fn with_node_exact(node: &SyntaxNode) -> Option { - match_ast! { - match node { - ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)), - ast::MethodCallExpr(it) => Some(FnCallNode::MethodCallExpr(it)), - _ => None, - } - } - } - - pub fn name_ref(&self) -> Option { - match self { - FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? { - ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?, - _ => return None, - }), - - FnCallNode::MethodCallExpr(call_expr) => { - call_expr.syntax().children().filter_map(ast::NameRef::cast).next() - } - } - } - - fn arg_list(&self) -> Option { - match self { - FnCallNode::CallExpr(expr) => expr.arg_list(), - FnCallNode::MethodCallExpr(expr) => expr.arg_list(), - } - } -} - -#[cfg(test)] -mod tests { - use base_db::{fixture::ChangeFixture, FilePosition}; - use expect_test::{expect, Expect}; - use ide_db::RootDatabase; - use test_utils::{mark, RangeOrOffset}; - - /// Creates analysis from a multi-file fixture, returns positions marked with <|>. - pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) { - let change_fixture = ChangeFixture::parse(ra_fixture); - let mut database = RootDatabase::default(); - database.apply_change(change_fixture.change); - let (file_id, range_or_offset) = - change_fixture.file_position.expect("expected a marker (<|>)"); - let offset = match range_or_offset { - RangeOrOffset::Range(_) => panic!(), - RangeOrOffset::Offset(it) => it, - }; - (database, FilePosition { file_id, offset }) - } - - fn check(ra_fixture: &str, expect: Expect) { - let (db, position) = position(ra_fixture); - let call_info = crate::call_info(&db, position); - let actual = match call_info { - Some(call_info) => { - let docs = match &call_info.doc { - None => "".to_string(), - Some(docs) => format!("{}\n------\n", docs.as_str()), - }; - let params = call_info - .parameter_labels() - .enumerate() - .map(|(i, param)| { - if Some(i) == call_info.active_parameter { - format!("<{}>", param) - } else { - param.to_string() - } - }) - .collect::>() - .join(", "); - format!("{}{}\n({})\n", docs, call_info.signature, params) - } - None => String::new(), - }; - expect.assert_eq(&actual); - } - - #[test] - fn test_fn_signature_two_args() { - check( - r#" -fn foo(x: u32, y: u32) -> u32 {x + y} -fn bar() { foo(<|>3, ); } -"#, - expect![[r#" - fn foo(x: u32, y: u32) -> u32 - (, y: u32) - "#]], - ); - check( - r#" -fn foo(x: u32, y: u32) -> u32 {x + y} -fn bar() { foo(3<|>, ); } -"#, - expect![[r#" - fn foo(x: u32, y: u32) -> u32 - (, y: u32) - "#]], - ); - check( - r#" -fn foo(x: u32, y: u32) -> u32 {x + y} -fn bar() { foo(3,<|> ); } -"#, - expect![[r#" - fn foo(x: u32, y: u32) -> u32 - (x: u32, ) - "#]], - ); - check( - r#" -fn foo(x: u32, y: u32) -> u32 {x + y} -fn bar() { foo(3, <|>); } -"#, - expect![[r#" - fn foo(x: u32, y: u32) -> u32 - (x: u32, ) - "#]], - ); - } - - #[test] - fn test_fn_signature_two_args_empty() { - check( - r#" -fn foo(x: u32, y: u32) -> u32 {x + y} -fn bar() { foo(<|>); } -"#, - expect![[r#" - fn foo(x: u32, y: u32) -> u32 - (, y: u32) - "#]], - ); - } - - #[test] - fn test_fn_signature_two_args_first_generics() { - check( - r#" -fn foo(x: T, y: U) -> u32 - where T: Copy + Display, U: Debug -{ x + y } - -fn bar() { foo(<|>3, ); } -"#, - expect![[r#" - fn foo(x: i32, y: {unknown}) -> u32 - (, y: {unknown}) - "#]], - ); - } - - #[test] - fn test_fn_signature_no_params() { - check( - r#" -fn foo() -> T where T: Copy + Display {} -fn bar() { foo(<|>); } -"#, - expect![[r#" - fn foo() -> {unknown} - () - "#]], - ); - } - - #[test] - fn test_fn_signature_for_impl() { - check( - r#" -struct F; -impl F { pub fn new() { } } -fn bar() { - let _ : F = F::new(<|>); -} -"#, - expect![[r#" - fn new() - () - "#]], - ); - } - - #[test] - fn test_fn_signature_for_method_self() { - check( - r#" -struct S; -impl S { pub fn do_it(&self) {} } - -fn bar() { - let s: S = S; - s.do_it(<|>); -} -"#, - expect![[r#" - fn do_it(&self) - () - "#]], - ); - } - - #[test] - fn test_fn_signature_for_method_with_arg() { - check( - r#" -struct S; -impl S { - fn foo(&self, x: i32) {} -} - -fn main() { S.foo(<|>); } -"#, - expect![[r#" - fn foo(&self, x: i32) - () - "#]], - ); - } - - #[test] - fn test_fn_signature_for_method_with_arg_as_assoc_fn() { - check( - r#" -struct S; -impl S { - fn foo(&self, x: i32) {} -} - -fn main() { S::foo(<|>); } -"#, - expect![[r#" - fn foo(self: &S, x: i32) - (, x: i32) - "#]], - ); - } - - #[test] - fn test_fn_signature_with_docs_simple() { - check( - r#" -/// test -// non-doc-comment -fn foo(j: u32) -> u32 { - j -} - -fn bar() { - let _ = foo(<|>); -} -"#, - expect![[r#" - test - ------ - fn foo(j: u32) -> u32 - () - "#]], - ); - } - - #[test] - fn test_fn_signature_with_docs() { - check( - r#" -/// Adds one to the number given. -/// -/// # Examples -/// -/// ``` -/// let five = 5; -/// -/// assert_eq!(6, my_crate::add_one(5)); -/// ``` -pub fn add_one(x: i32) -> i32 { - x + 1 -} - -pub fn do() { - add_one(<|> -}"#, - expect![[r##" - Adds one to the number given. - - # Examples - - ``` - let five = 5; - - assert_eq!(6, my_crate::add_one(5)); - ``` - ------ - fn add_one(x: i32) -> i32 - () - "##]], - ); - } - - #[test] - fn test_fn_signature_with_docs_impl() { - check( - r#" -struct addr; -impl addr { - /// Adds one to the number given. - /// - /// # Examples - /// - /// ``` - /// let five = 5; - /// - /// assert_eq!(6, my_crate::add_one(5)); - /// ``` - pub fn add_one(x: i32) -> i32 { - x + 1 - } -} - -pub fn do_it() { - addr {}; - addr::add_one(<|>); -} -"#, - expect![[r##" - Adds one to the number given. - - # Examples - - ``` - let five = 5; - - assert_eq!(6, my_crate::add_one(5)); - ``` - ------ - fn add_one(x: i32) -> i32 - () - "##]], - ); - } - - #[test] - fn test_fn_signature_with_docs_from_actix() { - check( - r#" -struct WriteHandler; - -impl WriteHandler { - /// Method is called when writer emits error. - /// - /// If this method returns `ErrorAction::Continue` writer processing - /// continues otherwise stream processing stops. - fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running { - Running::Stop - } - - /// Method is called when writer finishes. - /// - /// By default this method stops actor's `Context`. - fn finished(&mut self, ctx: &mut Self::Context) { - ctx.stop() - } -} - -pub fn foo(mut r: WriteHandler<()>) { - r.finished(<|>); -} -"#, - expect![[r#" - Method is called when writer finishes. - - By default this method stops actor's `Context`. - ------ - fn finished(&mut self, ctx: &mut {unknown}) - () - "#]], - ); - } - - #[test] - fn call_info_bad_offset() { - mark::check!(call_info_bad_offset); - check( - r#" -fn foo(x: u32, y: u32) -> u32 {x + y} -fn bar() { foo <|> (3, ); } -"#, - expect![[""]], - ); - } - - #[test] - fn test_nested_method_in_lambda() { - check( - r#" -struct Foo; -impl Foo { fn bar(&self, _: u32) { } } - -fn bar(_: u32) { } - -fn main() { - let foo = Foo; - std::thread::spawn(move || foo.bar(<|>)); -} -"#, - expect![[r#" - fn bar(&self, _: u32) - (<_: u32>) - "#]], - ); - } - - #[test] - fn works_for_tuple_structs() { - check( - r#" -/// A cool tuple struct -struct S(u32, i32); -fn main() { - let s = S(0, <|>); -} -"#, - expect![[r#" - A cool tuple struct - ------ - struct S(u32, i32) - (u32, ) - "#]], - ); - } - - #[test] - fn generic_struct() { - check( - r#" -struct S(T); -fn main() { - let s = S(<|>); -} -"#, - expect![[r#" - struct S({unknown}) - (<{unknown}>) - "#]], - ); - } - - #[test] - fn works_for_enum_variants() { - check( - r#" -enum E { - /// A Variant - A(i32), - /// Another - B, - /// And C - C { a: i32, b: i32 } -} - -fn main() { - let a = E::A(<|>); -} -"#, - expect![[r#" - A Variant - ------ - enum E::A(i32) - () - "#]], - ); - } - - #[test] - fn cant_call_struct_record() { - check( - r#" -struct S { x: u32, y: i32 } -fn main() { - let s = S(<|>); -} -"#, - expect![[""]], - ); - } - - #[test] - fn cant_call_enum_record() { - check( - r#" -enum E { - /// A Variant - A(i32), - /// Another - B, - /// And C - C { a: i32, b: i32 } -} - -fn main() { - let a = E::C(<|>); -} -"#, - expect![[""]], - ); - } - - #[test] - fn fn_signature_for_call_in_macro() { - check( - r#" -macro_rules! id { ($($tt:tt)*) => { $($tt)* } } -fn foo() { } -id! { - fn bar() { foo(<|>); } -} -"#, - expect![[r#" - fn foo() - () - "#]], - ); - } - - #[test] - fn call_info_for_lambdas() { - check( - r#" -struct S; -fn foo(s: S) -> i32 { 92 } -fn main() { - (|s| foo(s))(<|>) -} - "#, - expect![[r#" - (S) -> i32 - () - "#]], - ) - } - - #[test] - fn call_info_for_fn_ptr() { - check( - r#" -fn main(f: fn(i32, f64) -> char) { - f(0, <|>) -} - "#, - expect![[r#" - (i32, f64) -> char - (i32, ) - "#]], - ) - } -} diff --git a/crates/completion/Cargo.toml b/crates/completion/Cargo.toml index 8b6e80448..b79ee33f7 100644 --- a/crates/completion/Cargo.toml +++ b/crates/completion/Cargo.toml @@ -21,7 +21,6 @@ base_db = { path = "../base_db", version = "0.0.0" } ide_db = { path = "../ide_db", version = "0.0.0" } profile = { path = "../profile", version = "0.0.0" } test_utils = { path = "../test_utils", version = "0.0.0" } -call_info = { path = "../call_info", version = "0.0.0" } # completions crate should depend only on the top-level `hir` package. if you need # something from some `hir_xxx` subpackage, reexport the API via `hir`. diff --git a/crates/completion/src/completion_context.rs b/crates/completion/src/completion_context.rs index e4f86d0e0..97c5c04ba 100644 --- a/crates/completion/src/completion_context.rs +++ b/crates/completion/src/completion_context.rs @@ -1,9 +1,8 @@ //! See `CompletionContext` structure. use base_db::{FilePosition, SourceDatabase}; -use call_info::ActiveParameter; use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type}; -use ide_db::RootDatabase; +use ide_db::{call_info::ActiveParameter, RootDatabase}; use syntax::{ algo::{find_covering_element, find_node_at_offset}, ast, match_ast, AstNode, NodeOrToken, diff --git a/crates/ide/Cargo.toml b/crates/ide/Cargo.toml index 76b52fa04..145c6156c 100644 --- a/crates/ide/Cargo.toml +++ b/crates/ide/Cargo.toml @@ -30,7 +30,6 @@ profile = { path = "../profile", version = "0.0.0" } test_utils = { path = "../test_utils", version = "0.0.0" } assists = { path = "../assists", version = "0.0.0" } ssr = { path = "../ssr", version = "0.0.0" } -call_info = { path = "../call_info", version = "0.0.0" } completion = { path = "../completion", version = "0.0.0" } # ide should depend only on the top-level `hir` package. if you need diff --git a/crates/ide/src/call_hierarchy.rs b/crates/ide/src/call_hierarchy.rs index 9d6433fe0..a259d9849 100644 --- a/crates/ide/src/call_hierarchy.rs +++ b/crates/ide/src/call_hierarchy.rs @@ -2,8 +2,8 @@ use indexmap::IndexMap; -use call_info::FnCallNode; use hir::Semantics; +use ide_db::call_info::FnCallNode; use ide_db::RootDatabase; use syntax::{ast, match_ast, AstNode, TextRange}; diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index cecfae4c7..d84b970d4 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -80,10 +80,10 @@ pub use crate::{ Highlight, HighlightModifier, HighlightModifiers, HighlightTag, HighlightedRange, }, }; -pub use call_info::CallInfo; pub use completion::{ CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat, }; +pub use ide_db::call_info::CallInfo; pub use assists::{ utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist, @@ -396,7 +396,7 @@ impl Analysis { /// Computes parameter information for the given call expression. pub fn call_info(&self, position: FilePosition) -> Cancelable> { - self.with_db(|db| call_info::call_info(db, position)) + self.with_db(|db| ide_db::call_info::call_info(db, position)) } /// Computes call hierarchy candidates for the given file position. diff --git a/crates/ide/src/syntax_highlighting/injection.rs b/crates/ide/src/syntax_highlighting/injection.rs index acd91b26c..59a74bc02 100644 --- a/crates/ide/src/syntax_highlighting/injection.rs +++ b/crates/ide/src/syntax_highlighting/injection.rs @@ -3,8 +3,8 @@ use std::{collections::BTreeMap, convert::TryFrom}; use ast::{HasQuotes, HasStringValue}; -use call_info::ActiveParameter; use hir::Semantics; +use ide_db::call_info::ActiveParameter; use itertools::Itertools; use syntax::{ast, AstToken, SyntaxNode, SyntaxToken, TextRange, TextSize}; diff --git a/crates/ide_db/Cargo.toml b/crates/ide_db/Cargo.toml index 320fb15e5..3ff7a1a6a 100644 --- a/crates/ide_db/Cargo.toml +++ b/crates/ide_db/Cargo.toml @@ -29,3 +29,6 @@ test_utils = { path = "../test_utils", version = "0.0.0" } # ide should depend only on the top-level `hir` package. if you need # something from some `hir_xxx` subpackage, reexport the API via `hir`. hir = { path = "../hir", version = "0.0.0" } + +[dev-dependencies] +expect-test = "1.0" diff --git a/crates/ide_db/src/call_info.rs b/crates/ide_db/src/call_info.rs new file mode 100644 index 000000000..83a602b9a --- /dev/null +++ b/crates/ide_db/src/call_info.rs @@ -0,0 +1,756 @@ +//! 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}; +use stdx::format_to; +use syntax::{ + ast::{self, ArgListOwner}, + match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize, +}; +use test_utils::mark; + +use crate::RootDatabase; + +/// Contains information about a call site. Specifically the +/// `FunctionSignature`and current parameter. +#[derive(Debug)] +pub struct CallInfo { + pub doc: Option, + pub signature: String, + pub active_parameter: Option, + parameters: Vec, +} + +impl CallInfo { + pub fn parameter_labels(&self) -> impl Iterator + '_ { + 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)) + } +} + +/// Computes parameter information for the given call expression. +pub fn call_info(db: &RootDatabase, position: FilePosition) -> Option { + 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); + + let (callable, active_parameter) = call_info_impl(&sema, token)?; + + 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) + ); + } + hir::CallableKind::Closure => (), + } + + 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), + } + } + format_to!(buf, "{}", ty.display(db)); + res.push_param(&buf); + } + } + res.signature.push(')'); + + match callable.kind() { + hir::CallableKind::Function(_) | hir::CallableKind::Closure => { + 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) +} + +fn call_info_impl( + sema: &Semantics, + token: SyntaxToken, +) -> Option<(hir::Callable, Option)> { + // Find the calling expression and it's NameRef + let calling_node = FnCallNode::with_node(&token.parent())?; + + 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; + } + 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 + }; + Some((callable, active_param)) +} + +#[derive(Debug)] +pub struct ActiveParameter { + pub ty: Type, + pub name: String, +} + +impl ActiveParameter { + pub fn at(db: &RootDatabase, position: FilePosition) -> Option { + 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) + } + + pub fn at_token(sema: &Semantics, token: SyntaxToken) -> Option { + let (signature, active_parameter) = call_info_impl(&sema, token)?; + + let idx = active_parameter?; + let mut params = signature.params(sema.db); + if !(idx < params.len()) { + mark::hit!(too_many_arguments); + return None; + } + let (pat, ty) = params.swap_remove(idx); + let name = pat?.to_string(); + Some(ActiveParameter { ty, name }) + } +} + +#[derive(Debug)] +pub enum FnCallNode { + CallExpr(ast::CallExpr), + MethodCallExpr(ast::MethodCallExpr), +} + +impl FnCallNode { + fn with_node(syntax: &SyntaxNode) -> Option { + syntax.ancestors().find_map(|node| { + match_ast! { + match node { + ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)), + ast::MethodCallExpr(it) => { + let arg_list = it.arg_list()?; + if !arg_list.syntax().text_range().contains_range(syntax.text_range()) { + return None; + } + Some(FnCallNode::MethodCallExpr(it)) + }, + _ => None, + } + } + }) + } + + pub fn with_node_exact(node: &SyntaxNode) -> Option { + match_ast! { + match node { + ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)), + ast::MethodCallExpr(it) => Some(FnCallNode::MethodCallExpr(it)), + _ => None, + } + } + } + + pub fn name_ref(&self) -> Option { + match self { + FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? { + ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?, + _ => return None, + }), + + FnCallNode::MethodCallExpr(call_expr) => { + call_expr.syntax().children().filter_map(ast::NameRef::cast).next() + } + } + } + + fn arg_list(&self) -> Option { + match self { + FnCallNode::CallExpr(expr) => expr.arg_list(), + FnCallNode::MethodCallExpr(expr) => expr.arg_list(), + } + } +} + +#[cfg(test)] +mod tests { + use crate::RootDatabase; + use base_db::{fixture::ChangeFixture, FilePosition}; + use expect_test::{expect, Expect}; + use test_utils::{mark, RangeOrOffset}; + + /// Creates analysis from a multi-file fixture, returns positions marked with <|>. + pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) { + let change_fixture = ChangeFixture::parse(ra_fixture); + let mut database = RootDatabase::default(); + database.apply_change(change_fixture.change); + let (file_id, range_or_offset) = + change_fixture.file_position.expect("expected a marker (<|>)"); + let offset = match range_or_offset { + RangeOrOffset::Range(_) => panic!(), + RangeOrOffset::Offset(it) => it, + }; + (database, FilePosition { file_id, offset }) + } + + fn check(ra_fixture: &str, expect: Expect) { + let (db, position) = position(ra_fixture); + let call_info = crate::call_info::call_info(&db, position); + let actual = match call_info { + Some(call_info) => { + let docs = match &call_info.doc { + None => "".to_string(), + Some(docs) => format!("{}\n------\n", docs.as_str()), + }; + let params = call_info + .parameter_labels() + .enumerate() + .map(|(i, param)| { + if Some(i) == call_info.active_parameter { + format!("<{}>", param) + } else { + param.to_string() + } + }) + .collect::>() + .join(", "); + format!("{}{}\n({})\n", docs, call_info.signature, params) + } + None => String::new(), + }; + expect.assert_eq(&actual); + } + + #[test] + fn test_fn_signature_two_args() { + check( + r#" +fn foo(x: u32, y: u32) -> u32 {x + y} +fn bar() { foo(<|>3, ); } +"#, + expect![[r#" + fn foo(x: u32, y: u32) -> u32 + (, y: u32) + "#]], + ); + check( + r#" +fn foo(x: u32, y: u32) -> u32 {x + y} +fn bar() { foo(3<|>, ); } +"#, + expect![[r#" + fn foo(x: u32, y: u32) -> u32 + (, y: u32) + "#]], + ); + check( + r#" +fn foo(x: u32, y: u32) -> u32 {x + y} +fn bar() { foo(3,<|> ); } +"#, + expect![[r#" + fn foo(x: u32, y: u32) -> u32 + (x: u32, ) + "#]], + ); + check( + r#" +fn foo(x: u32, y: u32) -> u32 {x + y} +fn bar() { foo(3, <|>); } +"#, + expect![[r#" + fn foo(x: u32, y: u32) -> u32 + (x: u32, ) + "#]], + ); + } + + #[test] + fn test_fn_signature_two_args_empty() { + check( + r#" +fn foo(x: u32, y: u32) -> u32 {x + y} +fn bar() { foo(<|>); } +"#, + expect![[r#" + fn foo(x: u32, y: u32) -> u32 + (, y: u32) + "#]], + ); + } + + #[test] + fn test_fn_signature_two_args_first_generics() { + check( + r#" +fn foo(x: T, y: U) -> u32 + where T: Copy + Display, U: Debug +{ x + y } + +fn bar() { foo(<|>3, ); } +"#, + expect![[r#" + fn foo(x: i32, y: {unknown}) -> u32 + (, y: {unknown}) + "#]], + ); + } + + #[test] + fn test_fn_signature_no_params() { + check( + r#" +fn foo() -> T where T: Copy + Display {} +fn bar() { foo(<|>); } +"#, + expect![[r#" + fn foo() -> {unknown} + () + "#]], + ); + } + + #[test] + fn test_fn_signature_for_impl() { + check( + r#" +struct F; +impl F { pub fn new() { } } +fn bar() { + let _ : F = F::new(<|>); +} +"#, + expect![[r#" + fn new() + () + "#]], + ); + } + + #[test] + fn test_fn_signature_for_method_self() { + check( + r#" +struct S; +impl S { pub fn do_it(&self) {} } + +fn bar() { + let s: S = S; + s.do_it(<|>); +} +"#, + expect![[r#" + fn do_it(&self) + () + "#]], + ); + } + + #[test] + fn test_fn_signature_for_method_with_arg() { + check( + r#" +struct S; +impl S { + fn foo(&self, x: i32) {} +} + +fn main() { S.foo(<|>); } +"#, + expect![[r#" + fn foo(&self, x: i32) + () + "#]], + ); + } + + #[test] + fn test_fn_signature_for_method_with_arg_as_assoc_fn() { + check( + r#" +struct S; +impl S { + fn foo(&self, x: i32) {} +} + +fn main() { S::foo(<|>); } +"#, + expect![[r#" + fn foo(self: &S, x: i32) + (, x: i32) + "#]], + ); + } + + #[test] + fn test_fn_signature_with_docs_simple() { + check( + r#" +/// test +// non-doc-comment +fn foo(j: u32) -> u32 { + j +} + +fn bar() { + let _ = foo(<|>); +} +"#, + expect![[r#" + test + ------ + fn foo(j: u32) -> u32 + () + "#]], + ); + } + + #[test] + fn test_fn_signature_with_docs() { + check( + r#" +/// Adds one to the number given. +/// +/// # Examples +/// +/// ``` +/// let five = 5; +/// +/// assert_eq!(6, my_crate::add_one(5)); +/// ``` +pub fn add_one(x: i32) -> i32 { + x + 1 +} + +pub fn do() { + add_one(<|> +}"#, + expect![[r##" + Adds one to the number given. + + # Examples + + ``` + let five = 5; + + assert_eq!(6, my_crate::add_one(5)); + ``` + ------ + fn add_one(x: i32) -> i32 + () + "##]], + ); + } + + #[test] + fn test_fn_signature_with_docs_impl() { + check( + r#" +struct addr; +impl addr { + /// Adds one to the number given. + /// + /// # Examples + /// + /// ``` + /// let five = 5; + /// + /// assert_eq!(6, my_crate::add_one(5)); + /// ``` + pub fn add_one(x: i32) -> i32 { + x + 1 + } +} + +pub fn do_it() { + addr {}; + addr::add_one(<|>); +} +"#, + expect![[r##" + Adds one to the number given. + + # Examples + + ``` + let five = 5; + + assert_eq!(6, my_crate::add_one(5)); + ``` + ------ + fn add_one(x: i32) -> i32 + () + "##]], + ); + } + + #[test] + fn test_fn_signature_with_docs_from_actix() { + check( + r#" +struct WriteHandler; + +impl WriteHandler { + /// Method is called when writer emits error. + /// + /// If this method returns `ErrorAction::Continue` writer processing + /// continues otherwise stream processing stops. + fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running { + Running::Stop + } + + /// Method is called when writer finishes. + /// + /// By default this method stops actor's `Context`. + fn finished(&mut self, ctx: &mut Self::Context) { + ctx.stop() + } +} + +pub fn foo(mut r: WriteHandler<()>) { + r.finished(<|>); +} +"#, + expect![[r#" + Method is called when writer finishes. + + By default this method stops actor's `Context`. + ------ + fn finished(&mut self, ctx: &mut {unknown}) + () + "#]], + ); + } + + #[test] + fn call_info_bad_offset() { + mark::check!(call_info_bad_offset); + check( + r#" +fn foo(x: u32, y: u32) -> u32 {x + y} +fn bar() { foo <|> (3, ); } +"#, + expect![[""]], + ); + } + + #[test] + fn test_nested_method_in_lambda() { + check( + r#" +struct Foo; +impl Foo { fn bar(&self, _: u32) { } } + +fn bar(_: u32) { } + +fn main() { + let foo = Foo; + std::thread::spawn(move || foo.bar(<|>)); +} +"#, + expect![[r#" + fn bar(&self, _: u32) + (<_: u32>) + "#]], + ); + } + + #[test] + fn works_for_tuple_structs() { + check( + r#" +/// A cool tuple struct +struct S(u32, i32); +fn main() { + let s = S(0, <|>); +} +"#, + expect![[r#" + A cool tuple struct + ------ + struct S(u32, i32) + (u32, ) + "#]], + ); + } + + #[test] + fn generic_struct() { + check( + r#" +struct S(T); +fn main() { + let s = S(<|>); +} +"#, + expect![[r#" + struct S({unknown}) + (<{unknown}>) + "#]], + ); + } + + #[test] + fn works_for_enum_variants() { + check( + r#" +enum E { + /// A Variant + A(i32), + /// Another + B, + /// And C + C { a: i32, b: i32 } +} + +fn main() { + let a = E::A(<|>); +} +"#, + expect![[r#" + A Variant + ------ + enum E::A(i32) + () + "#]], + ); + } + + #[test] + fn cant_call_struct_record() { + check( + r#" +struct S { x: u32, y: i32 } +fn main() { + let s = S(<|>); +} +"#, + expect![[""]], + ); + } + + #[test] + fn cant_call_enum_record() { + check( + r#" +enum E { + /// A Variant + A(i32), + /// Another + B, + /// And C + C { a: i32, b: i32 } +} + +fn main() { + let a = E::C(<|>); +} +"#, + expect![[""]], + ); + } + + #[test] + fn fn_signature_for_call_in_macro() { + check( + r#" +macro_rules! id { ($($tt:tt)*) => { $($tt)* } } +fn foo() { } +id! { + fn bar() { foo(<|>); } +} +"#, + expect![[r#" + fn foo() + () + "#]], + ); + } + + #[test] + fn call_info_for_lambdas() { + check( + r#" +struct S; +fn foo(s: S) -> i32 { 92 } +fn main() { + (|s| foo(s))(<|>) +} + "#, + expect![[r#" + (S) -> i32 + () + "#]], + ) + } + + #[test] + fn call_info_for_fn_ptr() { + check( + r#" +fn main(f: fn(i32, f64) -> char) { + f(0, <|>) +} + "#, + expect![[r#" + (i32, f64) -> char + (i32, ) + "#]], + ) + } +} diff --git a/crates/ide_db/src/lib.rs b/crates/ide_db/src/lib.rs index 88f74265c..303f7c964 100644 --- a/crates/ide_db/src/lib.rs +++ b/crates/ide_db/src/lib.rs @@ -12,6 +12,7 @@ pub mod imports_locator; pub mod source_change; pub mod ty_filter; pub mod traits; +pub mod call_info; use std::{fmt, sync::Arc}; -- cgit v1.2.3