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.rs124
-rw-r--r--crates/ra_ide/src/completion/completion_context.rs8
-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.rs70
-rw-r--r--crates/ra_ide/src/lib.rs15
6 files changed, 202 insertions, 28 deletions
diff --git a/crates/ra_ide/src/completion/complete_dot.rs b/crates/ra_ide/src/completion/complete_dot.rs
index f433faef3..b5448af5c 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
@@ -70,13 +95,20 @@ fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: &T
70 95
71#[cfg(test)] 96#[cfg(test)]
72mod tests { 97mod tests {
73 use crate::completion::{test_utils::do_completion, CompletionItem, CompletionKind}; 98 use crate::completion::{
99 test_utils::{do_completion, do_completion_without_sort},
100 CompletionItem, CompletionKind,
101 };
74 use insta::assert_debug_snapshot; 102 use insta::assert_debug_snapshot;
75 103
76 fn do_ref_completion(code: &str) -> Vec<CompletionItem> { 104 fn do_ref_completion(code: &str) -> Vec<CompletionItem> {
77 do_completion(code, CompletionKind::Reference) 105 do_completion(code, CompletionKind::Reference)
78 } 106 }
79 107
108 fn do_ref_completion_without_sort(code: &str) -> Vec<CompletionItem> {
109 do_completion_without_sort(code, CompletionKind::Reference)
110 }
111
80 #[test] 112 #[test]
81 fn test_struct_field_completion() { 113 fn test_struct_field_completion() {
82 assert_debug_snapshot!( 114 assert_debug_snapshot!(
@@ -104,6 +136,92 @@ mod tests {
104 } 136 }
105 137
106 #[test] 138 #[test]
139 fn test_struct_field_completion_in_func_call() {
140 assert_debug_snapshot!(
141 do_ref_completion_without_sort(
142 r"
143 struct A { another_field: i64, the_field: u32, my_string: String }
144 fn test(my_param: u32) -> u32 { my_param }
145 fn foo(a: A) {
146 test(a.<|>)
147 }
148 ",
149 ),
150 @r###"
151 [
152 CompletionItem {
153 label: "the_field",
154 source_range: [201; 201),
155 delete: [201; 201),
156 insert: "the_field",
157 kind: Field,
158 detail: "u32",
159 },
160 CompletionItem {
161 label: "another_field",
162 source_range: [201; 201),
163 delete: [201; 201),
164 insert: "another_field",
165 kind: Field,
166 detail: "i64",
167 },
168 CompletionItem {
169 label: "my_string",
170 source_range: [201; 201),
171 delete: [201; 201),
172 insert: "my_string",
173 kind: Field,
174 detail: "{unknown}",
175 },
176 ]
177 "###
178 );
179 }
180
181 #[test]
182 fn test_struct_field_completion_in_func_call_with_type_and_name() {
183 assert_debug_snapshot!(
184 do_ref_completion_without_sort(
185 r"
186 struct A { another_field: i64, another_good_type: u32, the_field: u32 }
187 fn test(the_field: u32) -> u32 { the_field }
188 fn foo(a: A) {
189 test(a.<|>)
190 }
191 ",
192 ),
193 @r###"
194 [
195 CompletionItem {
196 label: "the_field",
197 source_range: [208; 208),
198 delete: [208; 208),
199 insert: "the_field",
200 kind: Field,
201 detail: "u32",
202 },
203 CompletionItem {
204 label: "another_good_type",
205 source_range: [208; 208),
206 delete: [208; 208),
207 insert: "another_good_type",
208 kind: Field,
209 detail: "u32",
210 },
211 CompletionItem {
212 label: "another_field",
213 source_range: [208; 208),
214 delete: [208; 208),
215 insert: "another_field",
216 kind: Field,
217 detail: "i64",
218 },
219 ]
220 "###
221 );
222 }
223
224 #[test]
107 fn test_struct_field_completion_self() { 225 fn test_struct_field_completion_self() {
108 assert_debug_snapshot!( 226 assert_debug_snapshot!(
109 do_ref_completion( 227 do_ref_completion(
diff --git a/crates/ra_ide/src/completion/completion_context.rs b/crates/ra_ide/src/completion/completion_context.rs
index 14a4a14d7..eb8016dd1 100644
--- a/crates/ra_ide/src/completion/completion_context.rs
+++ b/crates/ra_ide/src/completion/completion_context.rs
@@ -11,7 +11,7 @@ use ra_syntax::{
11}; 11};
12use ra_text_edit::AtomTextEdit; 12use ra_text_edit::AtomTextEdit;
13 13
14use crate::{completion::CompletionConfig, FilePosition}; 14use crate::{call_info::call_info, completion::CompletionConfig, CallInfo, FilePosition};
15 15
16/// `CompletionContext` is created early during completion to figure out, where 16/// `CompletionContext` is created early during completion to figure out, where
17/// exactly is the cursor, syntax-wise. 17/// exactly is the cursor, syntax-wise.
@@ -21,6 +21,7 @@ pub(crate) struct CompletionContext<'a> {
21 pub(super) db: &'a RootDatabase, 21 pub(super) db: &'a RootDatabase,
22 pub(super) config: &'a CompletionConfig, 22 pub(super) config: &'a CompletionConfig,
23 pub(super) offset: TextUnit, 23 pub(super) offset: TextUnit,
24 pub(super) file_position: FilePosition,
24 /// The token before the cursor, in the original file. 25 /// The token before the cursor, in the original file.
25 pub(super) original_token: SyntaxToken, 26 pub(super) original_token: SyntaxToken,
26 /// The token before the cursor, in the macro-expanded file. 27 /// The token before the cursor, in the macro-expanded file.
@@ -32,6 +33,7 @@ pub(crate) struct CompletionContext<'a> {
32 pub(super) record_lit_syntax: Option<ast::RecordLit>, 33 pub(super) record_lit_syntax: Option<ast::RecordLit>,
33 pub(super) record_lit_pat: Option<ast::RecordPat>, 34 pub(super) record_lit_pat: Option<ast::RecordPat>,
34 pub(super) impl_def: Option<ast::ImplDef>, 35 pub(super) impl_def: Option<ast::ImplDef>,
36 pub(super) call_info: Option<CallInfo>,
35 pub(super) is_param: bool, 37 pub(super) is_param: bool,
36 /// If a name-binding or reference to a const in a pattern. 38 /// If a name-binding or reference to a const in a pattern.
37 /// Irrefutable patterns (like let) are excluded. 39 /// Irrefutable patterns (like let) are excluded.
@@ -88,9 +90,11 @@ impl<'a> CompletionContext<'a> {
88 original_token, 90 original_token,
89 token, 91 token,
90 offset: position.offset, 92 offset: position.offset,
93 file_position: position,
91 krate, 94 krate,
92 name_ref_syntax: None, 95 name_ref_syntax: None,
93 function_syntax: None, 96 function_syntax: None,
97 call_info: None,
94 use_item_syntax: None, 98 use_item_syntax: None,
95 record_lit_syntax: None, 99 record_lit_syntax: None,
96 record_lit_pat: None, 100 record_lit_pat: None,
@@ -256,6 +260,8 @@ impl<'a> CompletionContext<'a> {
256 self.use_item_syntax = 260 self.use_item_syntax =
257 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::UseItem::cast); 261 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::UseItem::cast);
258 262
263 self.call_info = call_info(self.db, self.file_position);
264
259 self.function_syntax = self 265 self.function_syntax = self
260 .sema 266 .sema
261 .ancestors_with_macros(self.token.parent()) 267 .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..2d175882b 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,20 @@ 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
71 }) 73 if let Some(param_type) = raw_param.split(':').nth(1) {
72 .collect(); 74 parameter_types.push(param_type[1..].to_string());
75 } else {
76 // The unwrap_or_else is useful when you have tuple struct
77 parameter_types.push(raw_param.clone());
78 }
79 params.push(raw_param);
80 }
73 81
74 Some( 82 Some(
75 FunctionSignature { 83 FunctionSignature {
@@ -79,6 +87,7 @@ impl FunctionSignature {
79 ret_type: node.name().map(|n| n.text().to_string()), 87 ret_type: node.name().map(|n| n.text().to_string()),
80 parameters: params, 88 parameters: params,
81 parameter_names: vec![], 89 parameter_names: vec![],
90 parameter_types,
82 generic_parameters: generic_parameters(&node), 91 generic_parameters: generic_parameters(&node),
83 where_predicates: where_predicates(&node), 92 where_predicates: where_predicates(&node),
84 doc: None, 93 doc: None,
@@ -99,15 +108,21 @@ impl FunctionSignature {
99 108
100 let name = format!("{}::{}", parent_name, variant.name(db)); 109 let name = format!("{}::{}", parent_name, variant.name(db));
101 110
102 let params = variant 111 let mut params = vec![];
103 .fields(db) 112 let mut parameter_types = vec![];
104 .into_iter() 113 for field in variant.fields(db).into_iter() {
105 .map(|field: hir::StructField| { 114 let ty = field.signature_ty(db);
106 let name = field.name(db); 115 let raw_param = format!("{}", ty.display(db));
107 let ty = field.signature_ty(db); 116 if let Some(param_type) = raw_param.split(':').nth(1) {
108 format!("{}: {}", name, ty.display(db)) 117 parameter_types.push(param_type[1..].to_string());
109 }) 118 } else {
110 .collect(); 119 // The unwrap_or_else is useful when you have tuple
120 parameter_types.push(raw_param);
121 }
122 let name = field.name(db);
123
124 params.push(format!("{}: {}", name, ty.display(db)));
125 }
111 126
112 Some( 127 Some(
113 FunctionSignature { 128 FunctionSignature {
@@ -117,6 +132,7 @@ impl FunctionSignature {
117 ret_type: None, 132 ret_type: None,
118 parameters: params, 133 parameters: params,
119 parameter_names: vec![], 134 parameter_names: vec![],
135 parameter_types,
120 generic_parameters: vec![], 136 generic_parameters: vec![],
121 where_predicates: vec![], 137 where_predicates: vec![],
122 doc: None, 138 doc: None,
@@ -139,6 +155,7 @@ impl FunctionSignature {
139 ret_type: None, 155 ret_type: None,
140 parameters: params, 156 parameters: params,
141 parameter_names: vec![], 157 parameter_names: vec![],
158 parameter_types: vec![],
142 generic_parameters: vec![], 159 generic_parameters: vec![],
143 where_predicates: vec![], 160 where_predicates: vec![],
144 doc: None, 161 doc: None,
@@ -151,18 +168,28 @@ impl FunctionSignature {
151 168
152impl From<&'_ ast::FnDef> for FunctionSignature { 169impl From<&'_ ast::FnDef> for FunctionSignature {
153 fn from(node: &ast::FnDef) -> FunctionSignature { 170 fn from(node: &ast::FnDef) -> FunctionSignature {
154 fn param_list(node: &ast::FnDef) -> (bool, Vec<String>) { 171 fn param_list(node: &ast::FnDef) -> (bool, Vec<String>, Vec<String>) {
155 let mut res = vec![]; 172 let mut res = vec![];
173 let mut res_types = vec![];
156 let mut has_self_param = false; 174 let mut has_self_param = false;
157 if let Some(param_list) = node.param_list() { 175 if let Some(param_list) = node.param_list() {
158 if let Some(self_param) = param_list.self_param() { 176 if let Some(self_param) = param_list.self_param() {
159 has_self_param = true; 177 has_self_param = true;
160 res.push(self_param.syntax().text().to_string()) 178 let raw_param = self_param.syntax().text().to_string();
179
180 // FIXME: better solution ?
181 res_types.push(
182 raw_param.split(':').nth(1).unwrap_or_else(|| " Self")[1..].to_string(),
183 );
184 res.push(raw_param);
161 } 185 }
162 186
163 res.extend(param_list.params().map(|param| param.syntax().text().to_string())); 187 res.extend(param_list.params().map(|param| param.syntax().text().to_string()));
188 res_types.extend(param_list.params().map(|param| {
189 param.syntax().text().to_string().split(':').nth(1).unwrap()[1..].to_string()
190 }));
164 } 191 }
165 (has_self_param, res) 192 (has_self_param, res, res_types)
166 } 193 }
167 194
168 fn param_name_list(node: &ast::FnDef) -> Vec<String> { 195 fn param_name_list(node: &ast::FnDef) -> Vec<String> {
@@ -192,7 +219,7 @@ impl From<&'_ ast::FnDef> for FunctionSignature {
192 res 219 res
193 } 220 }
194 221
195 let (has_self_param, parameters) = param_list(node); 222 let (has_self_param, parameters, parameter_types) = param_list(node);
196 223
197 FunctionSignature { 224 FunctionSignature {
198 kind: CallableKind::Function, 225 kind: CallableKind::Function,
@@ -204,6 +231,7 @@ impl From<&'_ ast::FnDef> for FunctionSignature {
204 .map(|n| n.syntax().text().to_string()), 231 .map(|n| n.syntax().text().to_string()),
205 parameters, 232 parameters,
206 parameter_names: param_name_list(node), 233 parameter_names: param_name_list(node),
234 parameter_types,
207 generic_parameters: generic_parameters(node), 235 generic_parameters: generic_parameters(node),
208 where_predicates: where_predicates(node), 236 where_predicates: where_predicates(node),
209 // docs are processed separately 237 // 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 {