aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide')
-rw-r--r--crates/ra_ide/src/completion/complete_dot.rs125
-rw-r--r--crates/ra_ide/src/completion/completion_context.rs14
-rw-r--r--crates/ra_ide/src/completion/presentation.rs2
-rw-r--r--crates/ra_ide/src/completion/test_utils.rs11
-rw-r--r--crates/ra_ide/src/display/function_signature.rs57
-rw-r--r--crates/ra_ide/src/lib.rs15
6 files changed, 194 insertions, 30 deletions
diff --git a/crates/ra_ide/src/completion/complete_dot.rs b/crates/ra_ide/src/completion/complete_dot.rs
index f433faef3..358b041aa 100644
--- a/crates/ra_ide/src/completion/complete_dot.rs
+++ b/crates/ra_ide/src/completion/complete_dot.rs
@@ -1,6 +1,6 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2 2
3use hir::{HasVisibility, Type}; 3use hir::{HasVisibility, HirDisplay, Type};
4 4
5use crate::completion::completion_item::CompletionKind; 5use crate::completion::completion_item::CompletionKind;
6use crate::{ 6use crate::{
@@ -8,6 +8,7 @@ use crate::{
8 CompletionItem, 8 CompletionItem,
9}; 9};
10use rustc_hash::FxHashSet; 10use rustc_hash::FxHashSet;
11use std::cmp::Ordering;
11 12
12/// Complete dot accesses, i.e. fields or methods (and .await syntax). 13/// Complete dot accesses, i.e. fields or methods (and .await syntax).
13pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) { 14pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
@@ -37,7 +38,31 @@ pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
37 38
38fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: &Type) { 39fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: &Type) {
39 for receiver in receiver.autoderef(ctx.db) { 40 for receiver in receiver.autoderef(ctx.db) {
40 for (field, ty) in receiver.fields(ctx.db) { 41 let mut fields = receiver.fields(ctx.db);
42 if let Some(call_info) = &ctx.call_info {
43 if let Some(active_parameter_type) = call_info.active_parameter_type() {
44 let active_parameter_name = call_info.active_parameter_name().unwrap();
45 fields.sort_by(|a, b| {
46 // For the same type
47 if active_parameter_type == a.1.display(ctx.db).to_string() {
48 // If same type + same name then go top position
49 if active_parameter_name == a.0.name(ctx.db).to_string() {
50 Ordering::Less
51 } else {
52 if active_parameter_type == b.1.display(ctx.db).to_string() {
53 Ordering::Equal
54 } else {
55 Ordering::Less
56 }
57 }
58 } else {
59 Ordering::Greater
60 }
61 });
62 }
63 }
64
65 for (field, ty) in fields {
41 if ctx.scope().module().map_or(false, |m| !field.is_visible_from(ctx.db, m)) { 66 if ctx.scope().module().map_or(false, |m| !field.is_visible_from(ctx.db, m)) {
42 // Skip private field. FIXME: If the definition location of the 67 // Skip private field. FIXME: If the definition location of the
43 // field is editable, we should show the completion 68 // field is editable, we should show the completion
@@ -47,6 +72,7 @@ fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: &Ty
47 } 72 }
48 for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() { 73 for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() {
49 // FIXME: Handle visibility 74 // FIXME: Handle visibility
75 // TODO: add the same behavior with type ?
50 acc.add_tuple_field(ctx, i, &ty); 76 acc.add_tuple_field(ctx, i, &ty);
51 } 77 }
52 } 78 }
@@ -70,13 +96,20 @@ fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: &T
70 96
71#[cfg(test)] 97#[cfg(test)]
72mod tests { 98mod tests {
73 use crate::completion::{test_utils::do_completion, CompletionItem, CompletionKind}; 99 use crate::completion::{
100 test_utils::{do_completion, do_completion_without_sort},
101 CompletionItem, CompletionKind,
102 };
74 use insta::assert_debug_snapshot; 103 use insta::assert_debug_snapshot;
75 104
76 fn do_ref_completion(code: &str) -> Vec<CompletionItem> { 105 fn do_ref_completion(code: &str) -> Vec<CompletionItem> {
77 do_completion(code, CompletionKind::Reference) 106 do_completion(code, CompletionKind::Reference)
78 } 107 }
79 108
109 fn do_ref_completion_without_sort(code: &str) -> Vec<CompletionItem> {
110 do_completion_without_sort(code, CompletionKind::Reference)
111 }
112
80 #[test] 113 #[test]
81 fn test_struct_field_completion() { 114 fn test_struct_field_completion() {
82 assert_debug_snapshot!( 115 assert_debug_snapshot!(
@@ -104,6 +137,92 @@ mod tests {
104 } 137 }
105 138
106 #[test] 139 #[test]
140 fn test_struct_field_completion_in_func_call() {
141 assert_debug_snapshot!(
142 do_ref_completion_without_sort(
143 r"
144 struct A { another_field: i64, the_field: u32, my_string: String }
145 fn test(my_param: u32) -> u32 { my_param }
146 fn foo(a: A) {
147 test(a.<|>)
148 }
149 ",
150 ),
151 @r###"
152 [
153 CompletionItem {
154 label: "the_field",
155 source_range: [201; 201),
156 delete: [201; 201),
157 insert: "the_field",
158 kind: Field,
159 detail: "u32",
160 },
161 CompletionItem {
162 label: "another_field",
163 source_range: [201; 201),
164 delete: [201; 201),
165 insert: "another_field",
166 kind: Field,
167 detail: "i64",
168 },
169 CompletionItem {
170 label: "my_string",
171 source_range: [201; 201),
172 delete: [201; 201),
173 insert: "my_string",
174 kind: Field,
175 detail: "{unknown}",
176 },
177 ]
178 "###
179 );
180 }
181
182 #[test]
183 fn test_struct_field_completion_in_func_call_with_type_and_name() {
184 assert_debug_snapshot!(
185 do_ref_completion_without_sort(
186 r"
187 struct A { another_field: i64, another_good_type: u32, the_field: u32 }
188 fn test(the_field: u32) -> u32 { the_field }
189 fn foo(a: A) {
190 test(a.<|>)
191 }
192 ",
193 ),
194 @r###"
195 [
196 CompletionItem {
197 label: "the_field",
198 source_range: [208; 208),
199 delete: [208; 208),
200 insert: "the_field",
201 kind: Field,
202 detail: "u32",
203 },
204 CompletionItem {
205 label: "another_good_type",
206 source_range: [208; 208),
207 delete: [208; 208),
208 insert: "another_good_type",
209 kind: Field,
210 detail: "u32",
211 },
212 CompletionItem {
213 label: "another_field",
214 source_range: [208; 208),
215 delete: [208; 208),
216 insert: "another_field",
217 kind: Field,
218 detail: "i64",
219 },
220 ]
221 "###
222 );
223 }
224
225 #[test]
107 fn test_struct_field_completion_self() { 226 fn test_struct_field_completion_self() {
108 assert_debug_snapshot!( 227 assert_debug_snapshot!(
109 do_ref_completion( 228 do_ref_completion(
diff --git a/crates/ra_ide/src/completion/completion_context.rs b/crates/ra_ide/src/completion/completion_context.rs
index f833d2a9a..fddaf21e4 100644
--- a/crates/ra_ide/src/completion/completion_context.rs
+++ b/crates/ra_ide/src/completion/completion_context.rs
@@ -1,17 +1,19 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2 2
3use hir::{Semantics, SemanticsScope}; 3use hir::{db::HirDatabase, Semantics, SemanticsScope};
4use ra_db::SourceDatabase; 4use ra_db::SourceDatabase;
5use ra_ide_db::RootDatabase; 5use ra_ide_db::RootDatabase;
6use ra_syntax::{ 6use ra_syntax::{
7 algo::{find_covering_element, find_node_at_offset}, 7 algo::{find_covering_element, find_node_at_offset},
8 ast, AstNode, 8 ast,
9 ast::ArgListOwner,
10 AstNode,
9 SyntaxKind::*, 11 SyntaxKind::*,
10 SyntaxNode, SyntaxToken, TextRange, TextUnit, 12 SyntaxNode, SyntaxToken, TextRange, TextUnit,
11}; 13};
12use ra_text_edit::AtomTextEdit; 14use ra_text_edit::AtomTextEdit;
13 15
14use crate::{completion::CompletionConfig, FilePosition}; 16use crate::{call_info::call_info, completion::CompletionConfig, CallInfo, FilePosition};
15 17
16/// `CompletionContext` is created early during completion to figure out, where 18/// `CompletionContext` is created early during completion to figure out, where
17/// exactly is the cursor, syntax-wise. 19/// exactly is the cursor, syntax-wise.
@@ -21,6 +23,7 @@ pub(crate) struct CompletionContext<'a> {
21 pub(super) db: &'a RootDatabase, 23 pub(super) db: &'a RootDatabase,
22 pub(super) config: &'a CompletionConfig, 24 pub(super) config: &'a CompletionConfig,
23 pub(super) offset: TextUnit, 25 pub(super) offset: TextUnit,
26 pub(super) file_position: FilePosition,
24 /// The token before the cursor, in the original file. 27 /// The token before the cursor, in the original file.
25 pub(super) original_token: SyntaxToken, 28 pub(super) original_token: SyntaxToken,
26 /// The token before the cursor, in the macro-expanded file. 29 /// The token before the cursor, in the macro-expanded file.
@@ -32,6 +35,7 @@ pub(crate) struct CompletionContext<'a> {
32 pub(super) record_lit_syntax: Option<ast::RecordLit>, 35 pub(super) record_lit_syntax: Option<ast::RecordLit>,
33 pub(super) record_lit_pat: Option<ast::RecordPat>, 36 pub(super) record_lit_pat: Option<ast::RecordPat>,
34 pub(super) impl_def: Option<ast::ImplDef>, 37 pub(super) impl_def: Option<ast::ImplDef>,
38 pub(super) call_info: Option<CallInfo>,
35 pub(super) is_param: bool, 39 pub(super) is_param: bool,
36 /// If a name-binding or reference to a const in a pattern. 40 /// If a name-binding or reference to a const in a pattern.
37 /// Irrefutable patterns (like let) are excluded. 41 /// Irrefutable patterns (like let) are excluded.
@@ -88,9 +92,11 @@ impl<'a> CompletionContext<'a> {
88 original_token, 92 original_token,
89 token, 93 token,
90 offset: position.offset, 94 offset: position.offset,
95 file_position: position,
91 krate, 96 krate,
92 name_ref_syntax: None, 97 name_ref_syntax: None,
93 function_syntax: None, 98 function_syntax: None,
99 call_info: None,
94 use_item_syntax: None, 100 use_item_syntax: None,
95 record_lit_syntax: None, 101 record_lit_syntax: None,
96 record_lit_pat: None, 102 record_lit_pat: None,
@@ -253,6 +259,8 @@ impl<'a> CompletionContext<'a> {
253 self.use_item_syntax = 259 self.use_item_syntax =
254 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::UseItem::cast); 260 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::UseItem::cast);
255 261
262 self.call_info = call_info(self.db, self.file_position);
263
256 self.function_syntax = self 264 self.function_syntax = self
257 .sema 265 .sema
258 .ancestors_with_macros(self.token.parent()) 266 .ancestors_with_macros(self.token.parent())
diff --git a/crates/ra_ide/src/completion/presentation.rs b/crates/ra_ide/src/completion/presentation.rs
index 55f75b15a..8be2d02d0 100644
--- a/crates/ra_ide/src/completion/presentation.rs
+++ b/crates/ra_ide/src/completion/presentation.rs
@@ -367,7 +367,7 @@ mod tests {
367 ra_fixture: &str, 367 ra_fixture: &str,
368 options: CompletionConfig, 368 options: CompletionConfig,
369 ) -> Vec<CompletionItem> { 369 ) -> Vec<CompletionItem> {
370 do_completion_with_options(ra_fixture, CompletionKind::Reference, &options) 370 do_completion_with_options(ra_fixture, CompletionKind::Reference, &options, true)
371 } 371 }
372 372
373 #[test] 373 #[test]
diff --git a/crates/ra_ide/src/completion/test_utils.rs b/crates/ra_ide/src/completion/test_utils.rs
index eb90b5279..f54d15a90 100644
--- a/crates/ra_ide/src/completion/test_utils.rs
+++ b/crates/ra_ide/src/completion/test_utils.rs
@@ -7,13 +7,18 @@ use crate::{
7}; 7};
8 8
9pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> { 9pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
10 do_completion_with_options(code, kind, &CompletionConfig::default()) 10 do_completion_with_options(code, kind, &CompletionConfig::default(), true)
11}
12
13pub(crate) fn do_completion_without_sort(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
14 do_completion_with_options(code, kind, &CompletionConfig::default(), false)
11} 15}
12 16
13pub(crate) fn do_completion_with_options( 17pub(crate) fn do_completion_with_options(
14 code: &str, 18 code: &str,
15 kind: CompletionKind, 19 kind: CompletionKind,
16 options: &CompletionConfig, 20 options: &CompletionConfig,
21 sort_by_key: bool,
17) -> Vec<CompletionItem> { 22) -> Vec<CompletionItem> {
18 let (analysis, position) = if code.contains("//-") { 23 let (analysis, position) = if code.contains("//-") {
19 analysis_and_position(code) 24 analysis_and_position(code)
@@ -24,6 +29,8 @@ pub(crate) fn do_completion_with_options(
24 let completion_items: Vec<CompletionItem> = completions.into(); 29 let completion_items: Vec<CompletionItem> = completions.into();
25 let mut kind_completions: Vec<CompletionItem> = 30 let mut kind_completions: Vec<CompletionItem> =
26 completion_items.into_iter().filter(|c| c.completion_kind == kind).collect(); 31 completion_items.into_iter().filter(|c| c.completion_kind == kind).collect();
27 kind_completions.sort_by_key(|c| c.label().to_owned()); 32 if sort_by_key {
33 kind_completions.sort_by_key(|c| c.label().to_owned());
34 }
28 kind_completions 35 kind_completions
29} 36}
diff --git a/crates/ra_ide/src/display/function_signature.rs b/crates/ra_ide/src/display/function_signature.rs
index b967a6816..e58a78271 100644
--- a/crates/ra_ide/src/display/function_signature.rs
+++ b/crates/ra_ide/src/display/function_signature.rs
@@ -36,6 +36,8 @@ pub struct FunctionSignature {
36 pub parameters: Vec<String>, 36 pub parameters: Vec<String>,
37 /// Parameter names of the function 37 /// Parameter names of the function
38 pub parameter_names: Vec<String>, 38 pub parameter_names: Vec<String>,
39 /// Parameter types of the function
40 pub parameter_types: Vec<String>,
39 /// Optional return type 41 /// Optional return type
40 pub ret_type: Option<String>, 42 pub ret_type: Option<String>,
41 /// Where predicates 43 /// Where predicates
@@ -62,14 +64,14 @@ impl FunctionSignature {
62 return None; 64 return None;
63 }; 65 };
64 66
65 let params = st 67 let mut params = vec![];
66 .fields(db) 68 let mut parameter_types = vec![];
67 .into_iter() 69 for field in st.fields(db).into_iter() {
68 .map(|field: hir::StructField| { 70 let ty = field.signature_ty(db);
69 let ty = field.signature_ty(db); 71 let raw_param = format!("{}", ty.display(db));
70 format!("{}", ty.display(db)) 72 parameter_types.push(raw_param.split(':').nth(1).unwrap()[1..].to_string());
71 }) 73 params.push(raw_param);
72 .collect(); 74 }
73 75
74 Some( 76 Some(
75 FunctionSignature { 77 FunctionSignature {
@@ -79,6 +81,7 @@ impl FunctionSignature {
79 ret_type: node.name().map(|n| n.text().to_string()), 81 ret_type: node.name().map(|n| n.text().to_string()),
80 parameters: params, 82 parameters: params,
81 parameter_names: vec![], 83 parameter_names: vec![],
84 parameter_types,
82 generic_parameters: generic_parameters(&node), 85 generic_parameters: generic_parameters(&node),
83 where_predicates: where_predicates(&node), 86 where_predicates: where_predicates(&node),
84 doc: None, 87 doc: None,
@@ -99,15 +102,14 @@ impl FunctionSignature {
99 102
100 let name = format!("{}::{}", parent_name, variant.name(db)); 103 let name = format!("{}::{}", parent_name, variant.name(db));
101 104
102 let params = variant 105 let mut params = vec![];
103 .fields(db) 106 let mut parameter_types = vec![];
104 .into_iter() 107 for field in variant.fields(db).into_iter() {
105 .map(|field: hir::StructField| { 108 let ty = field.signature_ty(db);
106 let name = field.name(db); 109 let raw_param = format!("{}", ty.display(db));
107 let ty = field.signature_ty(db); 110 parameter_types.push(raw_param.split(':').nth(1).unwrap()[1..].to_string());
108 format!("{}: {}", name, ty.display(db)) 111 params.push(raw_param);
109 }) 112 }
110 .collect();
111 113
112 Some( 114 Some(
113 FunctionSignature { 115 FunctionSignature {
@@ -117,6 +119,7 @@ impl FunctionSignature {
117 ret_type: None, 119 ret_type: None,
118 parameters: params, 120 parameters: params,
119 parameter_names: vec![], 121 parameter_names: vec![],
122 parameter_types,
120 generic_parameters: vec![], 123 generic_parameters: vec![],
121 where_predicates: vec![], 124 where_predicates: vec![],
122 doc: None, 125 doc: None,
@@ -139,6 +142,7 @@ impl FunctionSignature {
139 ret_type: None, 142 ret_type: None,
140 parameters: params, 143 parameters: params,
141 parameter_names: vec![], 144 parameter_names: vec![],
145 parameter_types: vec![],
142 generic_parameters: vec![], 146 generic_parameters: vec![],
143 where_predicates: vec![], 147 where_predicates: vec![],
144 doc: None, 148 doc: None,
@@ -151,18 +155,28 @@ impl FunctionSignature {
151 155
152impl From<&'_ ast::FnDef> for FunctionSignature { 156impl From<&'_ ast::FnDef> for FunctionSignature {
153 fn from(node: &ast::FnDef) -> FunctionSignature { 157 fn from(node: &ast::FnDef) -> FunctionSignature {
154 fn param_list(node: &ast::FnDef) -> (bool, Vec<String>) { 158 fn param_list(node: &ast::FnDef) -> (bool, Vec<String>, Vec<String>) {
155 let mut res = vec![]; 159 let mut res = vec![];
160 let mut res_types = vec![];
156 let mut has_self_param = false; 161 let mut has_self_param = false;
157 if let Some(param_list) = node.param_list() { 162 if let Some(param_list) = node.param_list() {
158 if let Some(self_param) = param_list.self_param() { 163 if let Some(self_param) = param_list.self_param() {
159 has_self_param = true; 164 has_self_param = true;
160 res.push(self_param.syntax().text().to_string()) 165 let raw_param = self_param.syntax().text().to_string();
166
167 // TODO: better solution ?
168 res_types.push(
169 raw_param.split(':').nth(1).unwrap_or_else(|| " Self")[1..].to_string(),
170 );
171 res.push(raw_param);
161 } 172 }
162 173
163 res.extend(param_list.params().map(|param| param.syntax().text().to_string())); 174 res.extend(param_list.params().map(|param| param.syntax().text().to_string()));
175 res_types.extend(param_list.params().map(|param| {
176 param.syntax().text().to_string().split(':').nth(1).unwrap()[1..].to_string()
177 }));
164 } 178 }
165 (has_self_param, res) 179 (has_self_param, res, res_types)
166 } 180 }
167 181
168 fn param_name_list(node: &ast::FnDef) -> Vec<String> { 182 fn param_name_list(node: &ast::FnDef) -> Vec<String> {
@@ -192,7 +206,7 @@ impl From<&'_ ast::FnDef> for FunctionSignature {
192 res 206 res
193 } 207 }
194 208
195 let (has_self_param, parameters) = param_list(node); 209 let (has_self_param, parameters, parameter_types) = param_list(node);
196 210
197 FunctionSignature { 211 FunctionSignature {
198 kind: CallableKind::Function, 212 kind: CallableKind::Function,
@@ -204,6 +218,7 @@ impl From<&'_ ast::FnDef> for FunctionSignature {
204 .map(|n| n.syntax().text().to_string()), 218 .map(|n| n.syntax().text().to_string()),
205 parameters, 219 parameters,
206 parameter_names: param_name_list(node), 220 parameter_names: param_name_list(node),
221 parameter_types,
207 generic_parameters: generic_parameters(node), 222 generic_parameters: generic_parameters(node),
208 where_predicates: where_predicates(node), 223 where_predicates: where_predicates(node),
209 // docs are processed separately 224 // docs are processed separately
diff --git a/crates/ra_ide/src/lib.rs b/crates/ra_ide/src/lib.rs
index 5599f143f..357c01cdf 100644
--- a/crates/ra_ide/src/lib.rs
+++ b/crates/ra_ide/src/lib.rs
@@ -127,6 +127,21 @@ pub struct CallInfo {
127 pub active_parameter: Option<usize>, 127 pub active_parameter: Option<usize>,
128} 128}
129 129
130impl CallInfo {
131 pub fn active_parameter_type(&self) -> Option<String> {
132 if let Some(id) = self.active_parameter {
133 return self.signature.parameter_types.get(id).map(|param_ty| param_ty.clone());
134 }
135 None
136 }
137 pub fn active_parameter_name(&self) -> Option<String> {
138 if let Some(id) = self.active_parameter {
139 return self.signature.parameter_names.get(id).map(|param_ty| param_ty.clone());
140 }
141 None
142 }
143}
144
130/// `AnalysisHost` stores the current state of the world. 145/// `AnalysisHost` stores the current state of the world.
131#[derive(Debug)] 146#[derive(Debug)]
132pub struct AnalysisHost { 147pub struct AnalysisHost {