diff options
54 files changed, 2632 insertions, 412 deletions
diff --git a/.vscode/launch.json b/.vscode/launch.json index ca70fb209..3f74d7566 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json | |||
@@ -11,7 +11,7 @@ | |||
11 | "configurations": [ | 11 | "configurations": [ |
12 | { | 12 | { |
13 | // Used for testing the extension with the installed LSP server. | 13 | // Used for testing the extension with the installed LSP server. |
14 | "name": "Run Extension", | 14 | "name": "Run Installed Extension", |
15 | "type": "extensionHost", | 15 | "type": "extensionHost", |
16 | "request": "launch", | 16 | "request": "launch", |
17 | "runtimeExecutable": "${execPath}", | 17 | "runtimeExecutable": "${execPath}", |
@@ -30,7 +30,7 @@ | |||
30 | }, | 30 | }, |
31 | { | 31 | { |
32 | // Used for testing the extension with a local build of the LSP server (in `target/debug`). | 32 | // Used for testing the extension with a local build of the LSP server (in `target/debug`). |
33 | "name": "Run Extension (Dev Server)", | 33 | "name": "Run Extension (Debug Build)", |
34 | "type": "extensionHost", | 34 | "type": "extensionHost", |
35 | "request": "launch", | 35 | "request": "launch", |
36 | "runtimeExecutable": "${execPath}", | 36 | "runtimeExecutable": "${execPath}", |
@@ -50,6 +50,27 @@ | |||
50 | } | 50 | } |
51 | }, | 51 | }, |
52 | { | 52 | { |
53 | // Used for testing the extension with a local build of the LSP server (in `target/release`). | ||
54 | "name": "Run Extension (Release Build)", | ||
55 | "type": "extensionHost", | ||
56 | "request": "launch", | ||
57 | "runtimeExecutable": "${execPath}", | ||
58 | "args": [ | ||
59 | "--disable-extensions", | ||
60 | "--extensionDevelopmentPath=${workspaceFolder}/editors/code" | ||
61 | ], | ||
62 | "outFiles": [ | ||
63 | "${workspaceFolder}/editors/code/out/**/*.js" | ||
64 | ], | ||
65 | "preLaunchTask": "Build Extension", | ||
66 | "skipFiles": [ | ||
67 | "<node_internals>/**/*.js" | ||
68 | ], | ||
69 | "env": { | ||
70 | "__RA_LSP_SERVER_DEBUG": "${workspaceFolder}/target/release/rust-analyzer" | ||
71 | } | ||
72 | }, | ||
73 | { | ||
53 | // Used to attach LLDB to a running LSP server. | 74 | // Used to attach LLDB to a running LSP server. |
54 | // NOTE: Might require root permissions. For this run: | 75 | // NOTE: Might require root permissions. For this run: |
55 | // | 76 | // |
diff --git a/Cargo.lock b/Cargo.lock index 3738cfe8c..d966ebe61 100644 --- a/Cargo.lock +++ b/Cargo.lock | |||
@@ -58,9 +58,9 @@ dependencies = [ | |||
58 | 58 | ||
59 | [[package]] | 59 | [[package]] |
60 | name = "backtrace-sys" | 60 | name = "backtrace-sys" |
61 | version = "0.1.35" | 61 | version = "0.1.36" |
62 | source = "registry+https://github.com/rust-lang/crates.io-index" | 62 | source = "registry+https://github.com/rust-lang/crates.io-index" |
63 | checksum = "7de8aba10a69c8e8d7622c5710229485ec32e9d55fdad160ea559c086fdcd118" | 63 | checksum = "78848718ee1255a2485d1309ad9cdecfc2e7d0362dd11c6829364c6b35ae1bc7" |
64 | dependencies = [ | 64 | dependencies = [ |
65 | "cc", | 65 | "cc", |
66 | "libc", | 66 | "libc", |
@@ -101,9 +101,9 @@ dependencies = [ | |||
101 | 101 | ||
102 | [[package]] | 102 | [[package]] |
103 | name = "cc" | 103 | name = "cc" |
104 | version = "1.0.50" | 104 | version = "1.0.52" |
105 | source = "registry+https://github.com/rust-lang/crates.io-index" | 105 | source = "registry+https://github.com/rust-lang/crates.io-index" |
106 | checksum = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" | 106 | checksum = "c3d87b23d6a92cd03af510a5ade527033f6aa6fa92161e2d5863a907d4c5e31d" |
107 | 107 | ||
108 | [[package]] | 108 | [[package]] |
109 | name = "cfg-if" | 109 | name = "cfg-if" |
@@ -800,9 +800,9 @@ dependencies = [ | |||
800 | 800 | ||
801 | [[package]] | 801 | [[package]] |
802 | name = "parking_lot_core" | 802 | name = "parking_lot_core" |
803 | version = "0.7.1" | 803 | version = "0.7.2" |
804 | source = "registry+https://github.com/rust-lang/crates.io-index" | 804 | source = "registry+https://github.com/rust-lang/crates.io-index" |
805 | checksum = "0e136c1904604defe99ce5fd71a28d473fa60a12255d511aa78a9ddf11237aeb" | 805 | checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3" |
806 | dependencies = [ | 806 | dependencies = [ |
807 | "cfg-if", | 807 | "cfg-if", |
808 | "cloudabi", | 808 | "cloudabi", |
@@ -1394,9 +1394,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" | |||
1394 | 1394 | ||
1395 | [[package]] | 1395 | [[package]] |
1396 | name = "ryu" | 1396 | name = "ryu" |
1397 | version = "1.0.3" | 1397 | version = "1.0.4" |
1398 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1398 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1399 | checksum = "535622e6be132bccd223f4bb2b8ac8d53cda3c7a6394944d3b2b33fb974f9d76" | 1399 | checksum = "ed3d612bc64430efeb3f7ee6ef26d590dce0c43249217bddc62112540c7941e1" |
1400 | 1400 | ||
1401 | [[package]] | 1401 | [[package]] |
1402 | name = "salsa" | 1402 | name = "salsa" |
@@ -1545,9 +1545,9 @@ checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" | |||
1545 | 1545 | ||
1546 | [[package]] | 1546 | [[package]] |
1547 | name = "smallvec" | 1547 | name = "smallvec" |
1548 | version = "1.3.0" | 1548 | version = "1.4.0" |
1549 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1549 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1550 | checksum = "05720e22615919e4734f6a99ceae50d00226c3c5aca406e102ebc33298214e0a" | 1550 | checksum = "c7cb5678e1615754284ec264d9bb5b4c27d2018577fd90ac0ceb578591ed5ee4" |
1551 | 1551 | ||
1552 | [[package]] | 1552 | [[package]] |
1553 | name = "smol_str" | 1553 | name = "smol_str" |
@@ -1570,9 +1570,9 @@ checksum = "ab16ced94dbd8a46c82fd81e3ed9a8727dac2977ea869d217bcc4ea1f122e81f" | |||
1570 | 1570 | ||
1571 | [[package]] | 1571 | [[package]] |
1572 | name = "syn" | 1572 | name = "syn" |
1573 | version = "1.0.17" | 1573 | version = "1.0.18" |
1574 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1574 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1575 | checksum = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03" | 1575 | checksum = "410a7488c0a728c7ceb4ad59b9567eb4053d02e8cc7f5c0e0eeeb39518369213" |
1576 | dependencies = [ | 1576 | dependencies = [ |
1577 | "proc-macro2", | 1577 | "proc-macro2", |
1578 | "quote", | 1578 | "quote", |
@@ -1646,9 +1646,9 @@ dependencies = [ | |||
1646 | 1646 | ||
1647 | [[package]] | 1647 | [[package]] |
1648 | name = "threadpool" | 1648 | name = "threadpool" |
1649 | version = "1.7.1" | 1649 | version = "1.8.0" |
1650 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1650 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1651 | checksum = "e2f0c90a5f3459330ac8bc0d2f879c693bb7a2f59689c1083fc4ef83834da865" | 1651 | checksum = "e8dae184447c15d5a6916d973c642aec485105a13cd238192a6927ae3e077d66" |
1652 | dependencies = [ | 1652 | dependencies = [ |
1653 | "num_cpus", | 1653 | "num_cpus", |
1654 | ] | 1654 | ] |
@@ -1742,9 +1742,9 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" | |||
1742 | 1742 | ||
1743 | [[package]] | 1743 | [[package]] |
1744 | name = "winapi-util" | 1744 | name = "winapi-util" |
1745 | version = "0.1.4" | 1745 | version = "0.1.5" |
1746 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1746 | source = "registry+https://github.com/rust-lang/crates.io-index" |
1747 | checksum = "fa515c5163a99cc82bab70fd3bfdd36d827be85de63737b40fcef2ce084a436e" | 1747 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" |
1748 | dependencies = [ | 1748 | dependencies = [ |
1749 | "winapi 0.3.8", | 1749 | "winapi 0.3.8", |
1750 | ] | 1750 | ] |
diff --git a/crates/ra_hir_def/src/body/scope.rs b/crates/ra_hir_def/src/body/scope.rs index fe4137176..5b36a7cc1 100644 --- a/crates/ra_hir_def/src/body/scope.rs +++ b/crates/ra_hir_def/src/body/scope.rs | |||
@@ -325,8 +325,11 @@ mod tests { | |||
325 | let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap(); | 325 | let resolved = scopes.resolve_name_in_scope(expr_scope, &name_ref.as_name()).unwrap(); |
326 | let pat_src = source_map.pat_syntax(resolved.pat()).unwrap(); | 326 | let pat_src = source_map.pat_syntax(resolved.pat()).unwrap(); |
327 | 327 | ||
328 | let local_name = pat_src.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()); | 328 | let local_name = pat_src.value.either( |
329 | assert_eq!(local_name.range(), expected_name.syntax().text_range()); | 329 | |it| it.syntax_node_ptr().to_node(file.syntax()), |
330 | |it| it.syntax_node_ptr().to_node(file.syntax()), | ||
331 | ); | ||
332 | assert_eq!(local_name.text_range(), expected_name.syntax().text_range()); | ||
330 | } | 333 | } |
331 | 334 | ||
332 | #[test] | 335 | #[test] |
diff --git a/crates/ra_hir_def/src/nameres/raw.rs b/crates/ra_hir_def/src/nameres/raw.rs index afd538e4a..39b011ad7 100644 --- a/crates/ra_hir_def/src/nameres/raw.rs +++ b/crates/ra_hir_def/src/nameres/raw.rs | |||
@@ -266,8 +266,8 @@ impl RawItemsCollector { | |||
266 | self.add_macro(current_module, it); | 266 | self.add_macro(current_module, it); |
267 | return; | 267 | return; |
268 | } | 268 | } |
269 | ast::ModuleItem::ExternBlock(_) => { | 269 | ast::ModuleItem::ExternBlock(it) => { |
270 | // FIXME: add extern block | 270 | self.add_extern_block(current_module, it); |
271 | return; | 271 | return; |
272 | } | 272 | } |
273 | }; | 273 | }; |
@@ -278,6 +278,34 @@ impl RawItemsCollector { | |||
278 | } | 278 | } |
279 | } | 279 | } |
280 | 280 | ||
281 | fn add_extern_block( | ||
282 | &mut self, | ||
283 | current_module: Option<Idx<ModuleData>>, | ||
284 | block: ast::ExternBlock, | ||
285 | ) { | ||
286 | if let Some(items) = block.extern_item_list() { | ||
287 | for item in items.extern_items() { | ||
288 | let attrs = self.parse_attrs(&item); | ||
289 | let visibility = | ||
290 | RawVisibility::from_ast_with_hygiene(item.visibility(), &self.hygiene); | ||
291 | let (kind, name) = match item { | ||
292 | ast::ExternItem::FnDef(it) => { | ||
293 | (DefKind::Function(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
294 | } | ||
295 | ast::ExternItem::StaticDef(it) => { | ||
296 | (DefKind::Static(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
297 | } | ||
298 | }; | ||
299 | |||
300 | if let Some(name) = name { | ||
301 | let name = name.as_name(); | ||
302 | let def = self.raw_items.defs.alloc(DefData { name, kind, visibility }); | ||
303 | self.push_item(current_module, attrs, RawItemKind::Def(def)); | ||
304 | } | ||
305 | } | ||
306 | } | ||
307 | } | ||
308 | |||
281 | fn add_module(&mut self, current_module: Option<Idx<ModuleData>>, module: ast::Module) { | 309 | fn add_module(&mut self, current_module: Option<Idx<ModuleData>>, module: ast::Module) { |
282 | let name = match module.name() { | 310 | let name = match module.name() { |
283 | Some(it) => it.as_name(), | 311 | Some(it) => it.as_name(), |
diff --git a/crates/ra_hir_def/src/nameres/tests.rs b/crates/ra_hir_def/src/nameres/tests.rs index 949ca7595..83120fa36 100644 --- a/crates/ra_hir_def/src/nameres/tests.rs +++ b/crates/ra_hir_def/src/nameres/tests.rs | |||
@@ -25,7 +25,7 @@ fn compute_crate_def_map(fixture: &str) -> Arc<CrateDefMap> { | |||
25 | #[test] | 25 | #[test] |
26 | fn crate_def_map_smoke_test() { | 26 | fn crate_def_map_smoke_test() { |
27 | let map = def_map( | 27 | let map = def_map( |
28 | " | 28 | r" |
29 | //- /lib.rs | 29 | //- /lib.rs |
30 | mod foo; | 30 | mod foo; |
31 | struct S; | 31 | struct S; |
@@ -45,6 +45,11 @@ fn crate_def_map_smoke_test() { | |||
45 | } | 45 | } |
46 | 46 | ||
47 | enum E { V } | 47 | enum E { V } |
48 | |||
49 | extern { | ||
50 | static EXT: u8; | ||
51 | fn ext(); | ||
52 | } | ||
48 | ", | 53 | ", |
49 | ); | 54 | ); |
50 | assert_snapshot!(map, @r###" | 55 | assert_snapshot!(map, @r###" |
@@ -61,7 +66,9 @@ fn crate_def_map_smoke_test() { | |||
61 | ⋮crate::foo::bar | 66 | ⋮crate::foo::bar |
62 | ⋮Baz: t v | 67 | ⋮Baz: t v |
63 | ⋮E: t | 68 | ⋮E: t |
69 | ⋮EXT: v | ||
64 | ⋮U: t v | 70 | ⋮U: t v |
71 | ⋮ext: v | ||
65 | "###) | 72 | "###) |
66 | } | 73 | } |
67 | 74 | ||
diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index a4b8d6683..279c06d65 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs | |||
@@ -863,7 +863,7 @@ pub trait TypeWalk { | |||
863 | &mut |ty, binders| { | 863 | &mut |ty, binders| { |
864 | if let &mut Ty::Bound(bound) = ty { | 864 | if let &mut Ty::Bound(bound) = ty { |
865 | if bound.debruijn >= binders { | 865 | if bound.debruijn >= binders { |
866 | *ty = substs.0[bound.index].clone(); | 866 | *ty = substs.0[bound.index].clone().shift_bound_vars(binders); |
867 | } | 867 | } |
868 | } | 868 | } |
869 | }, | 869 | }, |
diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs index 81fc0f63a..846005baa 100644 --- a/crates/ra_hir_ty/src/tests.rs +++ b/crates/ra_hir_ty/src/tests.rs | |||
@@ -18,16 +18,19 @@ use hir_def::{ | |||
18 | nameres::CrateDefMap, | 18 | nameres::CrateDefMap, |
19 | AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId, | 19 | AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId, |
20 | }; | 20 | }; |
21 | use hir_expand::InFile; | 21 | use hir_expand::{db::AstDatabase, InFile}; |
22 | use insta::assert_snapshot; | 22 | use insta::assert_snapshot; |
23 | use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; | 23 | use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; |
24 | use ra_syntax::{ | 24 | use ra_syntax::{ |
25 | algo, | 25 | algo, |
26 | ast::{self, AstNode}, | 26 | ast::{self, AstNode}, |
27 | SyntaxNode, | ||
27 | }; | 28 | }; |
28 | use stdx::format_to; | 29 | use stdx::format_to; |
29 | 30 | ||
30 | use crate::{db::HirDatabase, display::HirDisplay, test_db::TestDB, InferenceResult}; | 31 | use crate::{ |
32 | db::HirDatabase, display::HirDisplay, infer::TypeMismatch, test_db::TestDB, InferenceResult, Ty, | ||
33 | }; | ||
31 | 34 | ||
32 | // These tests compare the inference results for all expressions in a file | 35 | // These tests compare the inference results for all expressions in a file |
33 | // against snapshots of the expected results using insta. Use cargo-insta to | 36 | // against snapshots of the expected results using insta. Use cargo-insta to |
@@ -67,13 +70,19 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { | |||
67 | 70 | ||
68 | let mut infer_def = |inference_result: Arc<InferenceResult>, | 71 | let mut infer_def = |inference_result: Arc<InferenceResult>, |
69 | body_source_map: Arc<BodySourceMap>| { | 72 | body_source_map: Arc<BodySourceMap>| { |
70 | let mut types = Vec::new(); | 73 | let mut types: Vec<(InFile<SyntaxNode>, &Ty)> = Vec::new(); |
71 | let mut mismatches = Vec::new(); | 74 | let mut mismatches: Vec<(InFile<SyntaxNode>, &TypeMismatch)> = Vec::new(); |
72 | 75 | ||
73 | for (pat, ty) in inference_result.type_of_pat.iter() { | 76 | for (pat, ty) in inference_result.type_of_pat.iter() { |
74 | let syntax_ptr = match body_source_map.pat_syntax(pat) { | 77 | let syntax_ptr = match body_source_map.pat_syntax(pat) { |
75 | Ok(sp) => { | 78 | Ok(sp) => { |
76 | sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr())) | 79 | let root = db.parse_or_expand(sp.file_id).unwrap(); |
80 | sp.map(|ptr| { | ||
81 | ptr.either( | ||
82 | |it| it.to_node(&root).syntax().clone(), | ||
83 | |it| it.to_node(&root).syntax().clone(), | ||
84 | ) | ||
85 | }) | ||
77 | } | 86 | } |
78 | Err(SyntheticSyntax) => continue, | 87 | Err(SyntheticSyntax) => continue, |
79 | }; | 88 | }; |
@@ -81,29 +90,31 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { | |||
81 | } | 90 | } |
82 | 91 | ||
83 | for (expr, ty) in inference_result.type_of_expr.iter() { | 92 | for (expr, ty) in inference_result.type_of_expr.iter() { |
84 | let syntax_ptr = match body_source_map.expr_syntax(expr) { | 93 | let node = match body_source_map.expr_syntax(expr) { |
85 | Ok(sp) => sp.map(|ast| ast.syntax_node_ptr()), | 94 | Ok(sp) => { |
95 | let root = db.parse_or_expand(sp.file_id).unwrap(); | ||
96 | sp.map(|ptr| ptr.to_node(&root).syntax().clone()) | ||
97 | } | ||
86 | Err(SyntheticSyntax) => continue, | 98 | Err(SyntheticSyntax) => continue, |
87 | }; | 99 | }; |
88 | types.push((syntax_ptr.clone(), ty)); | 100 | types.push((node.clone(), ty)); |
89 | if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) { | 101 | if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) { |
90 | mismatches.push((syntax_ptr, mismatch)); | 102 | mismatches.push((node, mismatch)); |
91 | } | 103 | } |
92 | } | 104 | } |
93 | 105 | ||
94 | // sort ranges for consistency | 106 | // sort ranges for consistency |
95 | types.sort_by_key(|(src_ptr, _)| { | 107 | types.sort_by_key(|(node, _)| { |
96 | (src_ptr.value.range().start(), src_ptr.value.range().end()) | 108 | let range = node.value.text_range(); |
109 | (range.start(), range.end()) | ||
97 | }); | 110 | }); |
98 | for (src_ptr, ty) in &types { | 111 | for (node, ty) in &types { |
99 | let node = src_ptr.value.to_node(&src_ptr.file_syntax(&db)); | 112 | let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) { |
100 | |||
101 | let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.clone()) { | ||
102 | (self_param.self_token().unwrap().text_range(), "self".to_string()) | 113 | (self_param.self_token().unwrap().text_range(), "self".to_string()) |
103 | } else { | 114 | } else { |
104 | (src_ptr.value.range(), node.text().to_string().replace("\n", " ")) | 115 | (node.value.text_range(), node.value.text().to_string().replace("\n", " ")) |
105 | }; | 116 | }; |
106 | let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; | 117 | let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" }; |
107 | format_to!( | 118 | format_to!( |
108 | buf, | 119 | buf, |
109 | "{}{} '{}': {}\n", | 120 | "{}{} '{}': {}\n", |
@@ -114,11 +125,12 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { | |||
114 | ); | 125 | ); |
115 | } | 126 | } |
116 | if include_mismatches { | 127 | if include_mismatches { |
117 | mismatches.sort_by_key(|(src_ptr, _)| { | 128 | mismatches.sort_by_key(|(node, _)| { |
118 | (src_ptr.value.range().start(), src_ptr.value.range().end()) | 129 | let range = node.value.text_range(); |
130 | (range.start(), range.end()) | ||
119 | }); | 131 | }); |
120 | for (src_ptr, mismatch) in &mismatches { | 132 | for (src_ptr, mismatch) in &mismatches { |
121 | let range = src_ptr.value.range(); | 133 | let range = src_ptr.value.text_range(); |
122 | let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; | 134 | let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; |
123 | format_to!( | 135 | format_to!( |
124 | buf, | 136 | buf, |
diff --git a/crates/ra_hir_ty/src/tests/regression.rs b/crates/ra_hir_ty/src/tests/regression.rs index 61284d672..61a6801fc 100644 --- a/crates/ra_hir_ty/src/tests/regression.rs +++ b/crates/ra_hir_ty/src/tests/regression.rs | |||
@@ -533,3 +533,44 @@ fn foo(b: Bar) { | |||
533 | "### | 533 | "### |
534 | ); | 534 | ); |
535 | } | 535 | } |
536 | |||
537 | #[test] | ||
538 | fn issue_4053_diesel_where_clauses() { | ||
539 | assert_snapshot!( | ||
540 | infer(r#" | ||
541 | trait BoxedDsl<DB> { | ||
542 | type Output; | ||
543 | fn internal_into_boxed(self) -> Self::Output; | ||
544 | } | ||
545 | |||
546 | struct SelectStatement<From, Select, Distinct, Where, Order, LimitOffset, GroupBy, Locking> { | ||
547 | order: Order, | ||
548 | } | ||
549 | |||
550 | trait QueryFragment<DB: Backend> {} | ||
551 | |||
552 | trait Into<T> { fn into(self) -> T; } | ||
553 | |||
554 | impl<F, S, D, W, O, LOf, DB> BoxedDsl<DB> | ||
555 | for SelectStatement<F, S, D, W, O, LOf, G> | ||
556 | where | ||
557 | O: Into<dyn QueryFragment<DB>>, | ||
558 | { | ||
559 | type Output = XXX; | ||
560 | |||
561 | fn internal_into_boxed(self) -> Self::Output { | ||
562 | self.order.into(); | ||
563 | } | ||
564 | } | ||
565 | "#), | ||
566 | @r###" | ||
567 | [66; 70) 'self': Self | ||
568 | [268; 272) 'self': Self | ||
569 | [467; 471) 'self': SelectStatement<F, S, D, W, O, LOf, {unknown}, {unknown}> | ||
570 | [489; 523) '{ ... }': () | ||
571 | [499; 503) 'self': SelectStatement<F, S, D, W, O, LOf, {unknown}, {unknown}> | ||
572 | [499; 509) 'self.order': O | ||
573 | [499; 516) 'self.o...into()': dyn QueryFragment<DB> | ||
574 | "### | ||
575 | ); | ||
576 | } | ||
diff --git a/crates/ra_ide/src/call_info.rs b/crates/ra_ide/src/call_info.rs index f95b6baf3..5da254a6e 100644 --- a/crates/ra_ide/src/call_info.rs +++ b/crates/ra_ide/src/call_info.rs | |||
@@ -19,10 +19,24 @@ pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<Cal | |||
19 | call_info_for_token(&sema, token) | 19 | call_info_for_token(&sema, token) |
20 | } | 20 | } |
21 | 21 | ||
22 | pub(crate) fn call_info_for_token( | 22 | #[derive(Debug)] |
23 | sema: &Semantics<RootDatabase>, | 23 | pub(crate) struct ActiveParameter { |
24 | token: SyntaxToken, | 24 | /// FIXME: should be `Type` and `Name |
25 | ) -> Option<CallInfo> { | 25 | pub(crate) ty: String, |
26 | pub(crate) name: String, | ||
27 | } | ||
28 | |||
29 | impl ActiveParameter { | ||
30 | pub(crate) fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> { | ||
31 | call_info(db, position)?.into_active_parameter() | ||
32 | } | ||
33 | |||
34 | pub(crate) fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> { | ||
35 | call_info_for_token(sema, token)?.into_active_parameter() | ||
36 | } | ||
37 | } | ||
38 | |||
39 | fn call_info_for_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<CallInfo> { | ||
26 | // Find the calling expression and it's NameRef | 40 | // Find the calling expression and it's NameRef |
27 | let calling_node = FnCallNode::with_node(&token.parent())?; | 41 | let calling_node = FnCallNode::with_node(&token.parent())?; |
28 | 42 | ||
@@ -160,6 +174,14 @@ impl FnCallNode { | |||
160 | } | 174 | } |
161 | 175 | ||
162 | impl CallInfo { | 176 | impl CallInfo { |
177 | fn into_active_parameter(self) -> Option<ActiveParameter> { | ||
178 | let idx = self.active_parameter?; | ||
179 | let ty = self.signature.parameter_types.get(idx)?.clone(); | ||
180 | let name = self.signature.parameter_names.get(idx)?.clone(); | ||
181 | let res = ActiveParameter { ty, name }; | ||
182 | Some(res) | ||
183 | } | ||
184 | |||
163 | fn with_fn(db: &RootDatabase, function: hir::Function) -> Self { | 185 | fn with_fn(db: &RootDatabase, function: hir::Function) -> Self { |
164 | let signature = FunctionSignature::from_hir(db, function); | 186 | let signature = FunctionSignature::from_hir(db, function); |
165 | 187 | ||
diff --git a/crates/ra_ide/src/completion.rs b/crates/ra_ide/src/completion.rs index 4a1a2a04a..4ca0fdf4f 100644 --- a/crates/ra_ide/src/completion.rs +++ b/crates/ra_ide/src/completion.rs | |||
@@ -1,9 +1,11 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | mod completion_config; | ||
3 | mod completion_item; | 4 | mod completion_item; |
4 | mod completion_context; | 5 | mod completion_context; |
5 | mod presentation; | 6 | mod presentation; |
6 | 7 | ||
8 | mod complete_attribute; | ||
7 | mod complete_dot; | 9 | mod complete_dot; |
8 | mod complete_record; | 10 | mod complete_record; |
9 | mod complete_pattern; | 11 | mod complete_pattern; |
@@ -28,27 +30,11 @@ use crate::{ | |||
28 | FilePosition, | 30 | FilePosition, |
29 | }; | 31 | }; |
30 | 32 | ||
31 | pub use crate::completion::completion_item::{ | 33 | pub use crate::completion::{ |
32 | CompletionItem, CompletionItemKind, InsertTextFormat, | 34 | completion_config::CompletionConfig, |
35 | completion_item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat}, | ||
33 | }; | 36 | }; |
34 | 37 | ||
35 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
36 | pub struct CompletionConfig { | ||
37 | pub enable_postfix_completions: bool, | ||
38 | pub add_call_parenthesis: bool, | ||
39 | pub add_call_argument_snippets: bool, | ||
40 | } | ||
41 | |||
42 | impl Default for CompletionConfig { | ||
43 | fn default() -> Self { | ||
44 | CompletionConfig { | ||
45 | enable_postfix_completions: true, | ||
46 | add_call_parenthesis: true, | ||
47 | add_call_argument_snippets: true, | ||
48 | } | ||
49 | } | ||
50 | } | ||
51 | |||
52 | /// Main entry point for completion. We run completion as a two-phase process. | 38 | /// Main entry point for completion. We run completion as a two-phase process. |
53 | /// | 39 | /// |
54 | /// First, we look at the position and collect a so-called `CompletionContext. | 40 | /// First, we look at the position and collect a so-called `CompletionContext. |
@@ -93,6 +79,7 @@ pub(crate) fn completions( | |||
93 | complete_postfix::complete_postfix(&mut acc, &ctx); | 79 | complete_postfix::complete_postfix(&mut acc, &ctx); |
94 | complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx); | 80 | complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx); |
95 | complete_trait_impl::complete_trait_impl(&mut acc, &ctx); | 81 | complete_trait_impl::complete_trait_impl(&mut acc, &ctx); |
82 | complete_attribute::complete_attribute(&mut acc, &ctx); | ||
96 | 83 | ||
97 | Some(acc) | 84 | Some(acc) |
98 | } | 85 | } |
diff --git a/crates/ra_ide/src/completion/complete_attribute.rs b/crates/ra_ide/src/completion/complete_attribute.rs new file mode 100644 index 000000000..b405042e8 --- /dev/null +++ b/crates/ra_ide/src/completion/complete_attribute.rs | |||
@@ -0,0 +1,587 @@ | |||
1 | //! Completion for attributes | ||
2 | //! | ||
3 | //! This module uses a bit of static metadata to provide completions | ||
4 | //! for built-in attributes. | ||
5 | |||
6 | use super::completion_context::CompletionContext; | ||
7 | use super::completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions}; | ||
8 | use ra_syntax::{ | ||
9 | ast::{Attr, AttrKind}, | ||
10 | AstNode, | ||
11 | }; | ||
12 | |||
13 | pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) { | ||
14 | if !ctx.is_attribute { | ||
15 | return; | ||
16 | } | ||
17 | |||
18 | let is_inner = ctx | ||
19 | .original_token | ||
20 | .ancestors() | ||
21 | .find_map(Attr::cast) | ||
22 | .map(|attr| attr.kind() == AttrKind::Inner) | ||
23 | .unwrap_or(false); | ||
24 | |||
25 | for attr_completion in ATTRIBUTES { | ||
26 | let mut item = CompletionItem::new( | ||
27 | CompletionKind::Attribute, | ||
28 | ctx.source_range(), | ||
29 | attr_completion.label, | ||
30 | ) | ||
31 | .kind(CompletionItemKind::Attribute); | ||
32 | |||
33 | match (attr_completion.snippet, ctx.config.snippet_cap) { | ||
34 | (Some(snippet), Some(cap)) => { | ||
35 | item = item.insert_snippet(cap, snippet); | ||
36 | } | ||
37 | _ => {} | ||
38 | } | ||
39 | |||
40 | if is_inner || !attr_completion.should_be_inner { | ||
41 | acc.add(item); | ||
42 | } | ||
43 | } | ||
44 | } | ||
45 | |||
46 | struct AttrCompletion { | ||
47 | label: &'static str, | ||
48 | snippet: Option<&'static str>, | ||
49 | should_be_inner: bool, | ||
50 | } | ||
51 | |||
52 | const ATTRIBUTES: &[AttrCompletion] = &[ | ||
53 | AttrCompletion { label: "allow", snippet: Some("allow(${0:lint})"), should_be_inner: false }, | ||
54 | AttrCompletion { | ||
55 | label: "cfg_attr", | ||
56 | snippet: Some("cfg_attr(${1:predicate}, ${0:attr})"), | ||
57 | should_be_inner: false, | ||
58 | }, | ||
59 | AttrCompletion { label: "cfg", snippet: Some("cfg(${0:predicate})"), should_be_inner: false }, | ||
60 | AttrCompletion { label: "deny", snippet: Some("deny(${0:lint})"), should_be_inner: false }, | ||
61 | AttrCompletion { | ||
62 | label: "deprecated", | ||
63 | snippet: Some(r#"deprecated = "${0:reason}""#), | ||
64 | should_be_inner: false, | ||
65 | }, | ||
66 | AttrCompletion { | ||
67 | label: "derive", | ||
68 | snippet: Some(r#"derive(${0:Debug})"#), | ||
69 | should_be_inner: false, | ||
70 | }, | ||
71 | AttrCompletion { label: "doc", snippet: Some(r#"doc = "${0:docs}""#), should_be_inner: false }, | ||
72 | AttrCompletion { label: "feature", snippet: Some("feature(${0:flag})"), should_be_inner: true }, | ||
73 | AttrCompletion { label: "forbid", snippet: Some("forbid(${0:lint})"), should_be_inner: false }, | ||
74 | // FIXME: resolve through macro resolution? | ||
75 | AttrCompletion { label: "global_allocator", snippet: None, should_be_inner: true }, | ||
76 | AttrCompletion { label: "ignore", snippet: Some("ignore(${0:lint})"), should_be_inner: false }, | ||
77 | AttrCompletion { label: "inline", snippet: Some("inline(${0:lint})"), should_be_inner: false }, | ||
78 | AttrCompletion { | ||
79 | label: "link_name", | ||
80 | snippet: Some(r#"link_name = "${0:symbol_name}""#), | ||
81 | should_be_inner: false, | ||
82 | }, | ||
83 | AttrCompletion { label: "link", snippet: None, should_be_inner: false }, | ||
84 | AttrCompletion { label: "macro_export", snippet: None, should_be_inner: false }, | ||
85 | AttrCompletion { label: "macro_use", snippet: None, should_be_inner: false }, | ||
86 | AttrCompletion { | ||
87 | label: "must_use", | ||
88 | snippet: Some(r#"must_use = "${0:reason}""#), | ||
89 | should_be_inner: false, | ||
90 | }, | ||
91 | AttrCompletion { label: "no_mangle", snippet: None, should_be_inner: false }, | ||
92 | AttrCompletion { label: "no_std", snippet: None, should_be_inner: true }, | ||
93 | AttrCompletion { label: "non_exhaustive", snippet: None, should_be_inner: false }, | ||
94 | AttrCompletion { label: "panic_handler", snippet: None, should_be_inner: true }, | ||
95 | AttrCompletion { label: "path", snippet: Some("path =\"${0:path}\""), should_be_inner: false }, | ||
96 | AttrCompletion { label: "proc_macro", snippet: None, should_be_inner: false }, | ||
97 | AttrCompletion { label: "proc_macro_attribute", snippet: None, should_be_inner: false }, | ||
98 | AttrCompletion { | ||
99 | label: "proc_macro_derive", | ||
100 | snippet: Some("proc_macro_derive(${0:Trait})"), | ||
101 | should_be_inner: false, | ||
102 | }, | ||
103 | AttrCompletion { | ||
104 | label: "recursion_limit", | ||
105 | snippet: Some("recursion_limit = ${0:128}"), | ||
106 | should_be_inner: true, | ||
107 | }, | ||
108 | AttrCompletion { label: "repr", snippet: Some("repr(${0:C})"), should_be_inner: false }, | ||
109 | AttrCompletion { | ||
110 | label: "should_panic", | ||
111 | snippet: Some(r#"expected = "${0:reason}""#), | ||
112 | should_be_inner: false, | ||
113 | }, | ||
114 | AttrCompletion { | ||
115 | label: "target_feature", | ||
116 | snippet: Some("target_feature = \"${0:feature}\""), | ||
117 | should_be_inner: false, | ||
118 | }, | ||
119 | AttrCompletion { label: "test", snippet: None, should_be_inner: false }, | ||
120 | AttrCompletion { label: "used", snippet: None, should_be_inner: false }, | ||
121 | AttrCompletion { label: "warn", snippet: Some("warn(${0:lint})"), should_be_inner: false }, | ||
122 | AttrCompletion { | ||
123 | label: "windows_subsystem", | ||
124 | snippet: Some(r#"windows_subsystem = "${0:subsystem}""#), | ||
125 | should_be_inner: true, | ||
126 | }, | ||
127 | ]; | ||
128 | |||
129 | #[cfg(test)] | ||
130 | mod tests { | ||
131 | use crate::completion::{test_utils::do_completion, CompletionItem, CompletionKind}; | ||
132 | use insta::assert_debug_snapshot; | ||
133 | |||
134 | fn do_attr_completion(code: &str) -> Vec<CompletionItem> { | ||
135 | do_completion(code, CompletionKind::Attribute) | ||
136 | } | ||
137 | |||
138 | #[test] | ||
139 | fn test_attribute_completion() { | ||
140 | assert_debug_snapshot!( | ||
141 | do_attr_completion( | ||
142 | r" | ||
143 | #[<|>] | ||
144 | ", | ||
145 | ), | ||
146 | @r###" | ||
147 | [ | ||
148 | CompletionItem { | ||
149 | label: "allow", | ||
150 | source_range: [19; 19), | ||
151 | delete: [19; 19), | ||
152 | insert: "allow(${0:lint})", | ||
153 | kind: Attribute, | ||
154 | }, | ||
155 | CompletionItem { | ||
156 | label: "cfg", | ||
157 | source_range: [19; 19), | ||
158 | delete: [19; 19), | ||
159 | insert: "cfg(${0:predicate})", | ||
160 | kind: Attribute, | ||
161 | }, | ||
162 | CompletionItem { | ||
163 | label: "cfg_attr", | ||
164 | source_range: [19; 19), | ||
165 | delete: [19; 19), | ||
166 | insert: "cfg_attr(${1:predicate}, ${0:attr})", | ||
167 | kind: Attribute, | ||
168 | }, | ||
169 | CompletionItem { | ||
170 | label: "deny", | ||
171 | source_range: [19; 19), | ||
172 | delete: [19; 19), | ||
173 | insert: "deny(${0:lint})", | ||
174 | kind: Attribute, | ||
175 | }, | ||
176 | CompletionItem { | ||
177 | label: "deprecated", | ||
178 | source_range: [19; 19), | ||
179 | delete: [19; 19), | ||
180 | insert: "deprecated = \"${0:reason}\"", | ||
181 | kind: Attribute, | ||
182 | }, | ||
183 | CompletionItem { | ||
184 | label: "derive", | ||
185 | source_range: [19; 19), | ||
186 | delete: [19; 19), | ||
187 | insert: "derive(${0:Debug})", | ||
188 | kind: Attribute, | ||
189 | }, | ||
190 | CompletionItem { | ||
191 | label: "doc", | ||
192 | source_range: [19; 19), | ||
193 | delete: [19; 19), | ||
194 | insert: "doc = \"${0:docs}\"", | ||
195 | kind: Attribute, | ||
196 | }, | ||
197 | CompletionItem { | ||
198 | label: "forbid", | ||
199 | source_range: [19; 19), | ||
200 | delete: [19; 19), | ||
201 | insert: "forbid(${0:lint})", | ||
202 | kind: Attribute, | ||
203 | }, | ||
204 | CompletionItem { | ||
205 | label: "ignore", | ||
206 | source_range: [19; 19), | ||
207 | delete: [19; 19), | ||
208 | insert: "ignore(${0:lint})", | ||
209 | kind: Attribute, | ||
210 | }, | ||
211 | CompletionItem { | ||
212 | label: "inline", | ||
213 | source_range: [19; 19), | ||
214 | delete: [19; 19), | ||
215 | insert: "inline(${0:lint})", | ||
216 | kind: Attribute, | ||
217 | }, | ||
218 | CompletionItem { | ||
219 | label: "link", | ||
220 | source_range: [19; 19), | ||
221 | delete: [19; 19), | ||
222 | insert: "link", | ||
223 | kind: Attribute, | ||
224 | }, | ||
225 | CompletionItem { | ||
226 | label: "link_name", | ||
227 | source_range: [19; 19), | ||
228 | delete: [19; 19), | ||
229 | insert: "link_name = \"${0:symbol_name}\"", | ||
230 | kind: Attribute, | ||
231 | }, | ||
232 | CompletionItem { | ||
233 | label: "macro_export", | ||
234 | source_range: [19; 19), | ||
235 | delete: [19; 19), | ||
236 | insert: "macro_export", | ||
237 | kind: Attribute, | ||
238 | }, | ||
239 | CompletionItem { | ||
240 | label: "macro_use", | ||
241 | source_range: [19; 19), | ||
242 | delete: [19; 19), | ||
243 | insert: "macro_use", | ||
244 | kind: Attribute, | ||
245 | }, | ||
246 | CompletionItem { | ||
247 | label: "must_use", | ||
248 | source_range: [19; 19), | ||
249 | delete: [19; 19), | ||
250 | insert: "must_use = \"${0:reason}\"", | ||
251 | kind: Attribute, | ||
252 | }, | ||
253 | CompletionItem { | ||
254 | label: "no_mangle", | ||
255 | source_range: [19; 19), | ||
256 | delete: [19; 19), | ||
257 | insert: "no_mangle", | ||
258 | kind: Attribute, | ||
259 | }, | ||
260 | CompletionItem { | ||
261 | label: "non_exhaustive", | ||
262 | source_range: [19; 19), | ||
263 | delete: [19; 19), | ||
264 | insert: "non_exhaustive", | ||
265 | kind: Attribute, | ||
266 | }, | ||
267 | CompletionItem { | ||
268 | label: "path", | ||
269 | source_range: [19; 19), | ||
270 | delete: [19; 19), | ||
271 | insert: "path =\"${0:path}\"", | ||
272 | kind: Attribute, | ||
273 | }, | ||
274 | CompletionItem { | ||
275 | label: "proc_macro", | ||
276 | source_range: [19; 19), | ||
277 | delete: [19; 19), | ||
278 | insert: "proc_macro", | ||
279 | kind: Attribute, | ||
280 | }, | ||
281 | CompletionItem { | ||
282 | label: "proc_macro_attribute", | ||
283 | source_range: [19; 19), | ||
284 | delete: [19; 19), | ||
285 | insert: "proc_macro_attribute", | ||
286 | kind: Attribute, | ||
287 | }, | ||
288 | CompletionItem { | ||
289 | label: "proc_macro_derive", | ||
290 | source_range: [19; 19), | ||
291 | delete: [19; 19), | ||
292 | insert: "proc_macro_derive(${0:Trait})", | ||
293 | kind: Attribute, | ||
294 | }, | ||
295 | CompletionItem { | ||
296 | label: "repr", | ||
297 | source_range: [19; 19), | ||
298 | delete: [19; 19), | ||
299 | insert: "repr(${0:C})", | ||
300 | kind: Attribute, | ||
301 | }, | ||
302 | CompletionItem { | ||
303 | label: "should_panic", | ||
304 | source_range: [19; 19), | ||
305 | delete: [19; 19), | ||
306 | insert: "expected = \"${0:reason}\"", | ||
307 | kind: Attribute, | ||
308 | }, | ||
309 | CompletionItem { | ||
310 | label: "target_feature", | ||
311 | source_range: [19; 19), | ||
312 | delete: [19; 19), | ||
313 | insert: "target_feature = \"${0:feature}\"", | ||
314 | kind: Attribute, | ||
315 | }, | ||
316 | CompletionItem { | ||
317 | label: "test", | ||
318 | source_range: [19; 19), | ||
319 | delete: [19; 19), | ||
320 | insert: "test", | ||
321 | kind: Attribute, | ||
322 | }, | ||
323 | CompletionItem { | ||
324 | label: "used", | ||
325 | source_range: [19; 19), | ||
326 | delete: [19; 19), | ||
327 | insert: "used", | ||
328 | kind: Attribute, | ||
329 | }, | ||
330 | CompletionItem { | ||
331 | label: "warn", | ||
332 | source_range: [19; 19), | ||
333 | delete: [19; 19), | ||
334 | insert: "warn(${0:lint})", | ||
335 | kind: Attribute, | ||
336 | }, | ||
337 | ] | ||
338 | "### | ||
339 | ); | ||
340 | } | ||
341 | |||
342 | #[test] | ||
343 | fn test_inner_attribute_completion() { | ||
344 | assert_debug_snapshot!( | ||
345 | do_attr_completion( | ||
346 | r" | ||
347 | #![<|>] | ||
348 | ", | ||
349 | ), | ||
350 | @r###" | ||
351 | [ | ||
352 | CompletionItem { | ||
353 | label: "allow", | ||
354 | source_range: [20; 20), | ||
355 | delete: [20; 20), | ||
356 | insert: "allow(${0:lint})", | ||
357 | kind: Attribute, | ||
358 | }, | ||
359 | CompletionItem { | ||
360 | label: "cfg", | ||
361 | source_range: [20; 20), | ||
362 | delete: [20; 20), | ||
363 | insert: "cfg(${0:predicate})", | ||
364 | kind: Attribute, | ||
365 | }, | ||
366 | CompletionItem { | ||
367 | label: "cfg_attr", | ||
368 | source_range: [20; 20), | ||
369 | delete: [20; 20), | ||
370 | insert: "cfg_attr(${1:predicate}, ${0:attr})", | ||
371 | kind: Attribute, | ||
372 | }, | ||
373 | CompletionItem { | ||
374 | label: "deny", | ||
375 | source_range: [20; 20), | ||
376 | delete: [20; 20), | ||
377 | insert: "deny(${0:lint})", | ||
378 | kind: Attribute, | ||
379 | }, | ||
380 | CompletionItem { | ||
381 | label: "deprecated", | ||
382 | source_range: [20; 20), | ||
383 | delete: [20; 20), | ||
384 | insert: "deprecated = \"${0:reason}\"", | ||
385 | kind: Attribute, | ||
386 | }, | ||
387 | CompletionItem { | ||
388 | label: "derive", | ||
389 | source_range: [20; 20), | ||
390 | delete: [20; 20), | ||
391 | insert: "derive(${0:Debug})", | ||
392 | kind: Attribute, | ||
393 | }, | ||
394 | CompletionItem { | ||
395 | label: "doc", | ||
396 | source_range: [20; 20), | ||
397 | delete: [20; 20), | ||
398 | insert: "doc = \"${0:docs}\"", | ||
399 | kind: Attribute, | ||
400 | }, | ||
401 | CompletionItem { | ||
402 | label: "feature", | ||
403 | source_range: [20; 20), | ||
404 | delete: [20; 20), | ||
405 | insert: "feature(${0:flag})", | ||
406 | kind: Attribute, | ||
407 | }, | ||
408 | CompletionItem { | ||
409 | label: "forbid", | ||
410 | source_range: [20; 20), | ||
411 | delete: [20; 20), | ||
412 | insert: "forbid(${0:lint})", | ||
413 | kind: Attribute, | ||
414 | }, | ||
415 | CompletionItem { | ||
416 | label: "global_allocator", | ||
417 | source_range: [20; 20), | ||
418 | delete: [20; 20), | ||
419 | insert: "global_allocator", | ||
420 | kind: Attribute, | ||
421 | }, | ||
422 | CompletionItem { | ||
423 | label: "ignore", | ||
424 | source_range: [20; 20), | ||
425 | delete: [20; 20), | ||
426 | insert: "ignore(${0:lint})", | ||
427 | kind: Attribute, | ||
428 | }, | ||
429 | CompletionItem { | ||
430 | label: "inline", | ||
431 | source_range: [20; 20), | ||
432 | delete: [20; 20), | ||
433 | insert: "inline(${0:lint})", | ||
434 | kind: Attribute, | ||
435 | }, | ||
436 | CompletionItem { | ||
437 | label: "link", | ||
438 | source_range: [20; 20), | ||
439 | delete: [20; 20), | ||
440 | insert: "link", | ||
441 | kind: Attribute, | ||
442 | }, | ||
443 | CompletionItem { | ||
444 | label: "link_name", | ||
445 | source_range: [20; 20), | ||
446 | delete: [20; 20), | ||
447 | insert: "link_name = \"${0:symbol_name}\"", | ||
448 | kind: Attribute, | ||
449 | }, | ||
450 | CompletionItem { | ||
451 | label: "macro_export", | ||
452 | source_range: [20; 20), | ||
453 | delete: [20; 20), | ||
454 | insert: "macro_export", | ||
455 | kind: Attribute, | ||
456 | }, | ||
457 | CompletionItem { | ||
458 | label: "macro_use", | ||
459 | source_range: [20; 20), | ||
460 | delete: [20; 20), | ||
461 | insert: "macro_use", | ||
462 | kind: Attribute, | ||
463 | }, | ||
464 | CompletionItem { | ||
465 | label: "must_use", | ||
466 | source_range: [20; 20), | ||
467 | delete: [20; 20), | ||
468 | insert: "must_use = \"${0:reason}\"", | ||
469 | kind: Attribute, | ||
470 | }, | ||
471 | CompletionItem { | ||
472 | label: "no_mangle", | ||
473 | source_range: [20; 20), | ||
474 | delete: [20; 20), | ||
475 | insert: "no_mangle", | ||
476 | kind: Attribute, | ||
477 | }, | ||
478 | CompletionItem { | ||
479 | label: "no_std", | ||
480 | source_range: [20; 20), | ||
481 | delete: [20; 20), | ||
482 | insert: "no_std", | ||
483 | kind: Attribute, | ||
484 | }, | ||
485 | CompletionItem { | ||
486 | label: "non_exhaustive", | ||
487 | source_range: [20; 20), | ||
488 | delete: [20; 20), | ||
489 | insert: "non_exhaustive", | ||
490 | kind: Attribute, | ||
491 | }, | ||
492 | CompletionItem { | ||
493 | label: "panic_handler", | ||
494 | source_range: [20; 20), | ||
495 | delete: [20; 20), | ||
496 | insert: "panic_handler", | ||
497 | kind: Attribute, | ||
498 | }, | ||
499 | CompletionItem { | ||
500 | label: "path", | ||
501 | source_range: [20; 20), | ||
502 | delete: [20; 20), | ||
503 | insert: "path =\"${0:path}\"", | ||
504 | kind: Attribute, | ||
505 | }, | ||
506 | CompletionItem { | ||
507 | label: "proc_macro", | ||
508 | source_range: [20; 20), | ||
509 | delete: [20; 20), | ||
510 | insert: "proc_macro", | ||
511 | kind: Attribute, | ||
512 | }, | ||
513 | CompletionItem { | ||
514 | label: "proc_macro_attribute", | ||
515 | source_range: [20; 20), | ||
516 | delete: [20; 20), | ||
517 | insert: "proc_macro_attribute", | ||
518 | kind: Attribute, | ||
519 | }, | ||
520 | CompletionItem { | ||
521 | label: "proc_macro_derive", | ||
522 | source_range: [20; 20), | ||
523 | delete: [20; 20), | ||
524 | insert: "proc_macro_derive(${0:Trait})", | ||
525 | kind: Attribute, | ||
526 | }, | ||
527 | CompletionItem { | ||
528 | label: "recursion_limit", | ||
529 | source_range: [20; 20), | ||
530 | delete: [20; 20), | ||
531 | insert: "recursion_limit = ${0:128}", | ||
532 | kind: Attribute, | ||
533 | }, | ||
534 | CompletionItem { | ||
535 | label: "repr", | ||
536 | source_range: [20; 20), | ||
537 | delete: [20; 20), | ||
538 | insert: "repr(${0:C})", | ||
539 | kind: Attribute, | ||
540 | }, | ||
541 | CompletionItem { | ||
542 | label: "should_panic", | ||
543 | source_range: [20; 20), | ||
544 | delete: [20; 20), | ||
545 | insert: "expected = \"${0:reason}\"", | ||
546 | kind: Attribute, | ||
547 | }, | ||
548 | CompletionItem { | ||
549 | label: "target_feature", | ||
550 | source_range: [20; 20), | ||
551 | delete: [20; 20), | ||
552 | insert: "target_feature = \"${0:feature}\"", | ||
553 | kind: Attribute, | ||
554 | }, | ||
555 | CompletionItem { | ||
556 | label: "test", | ||
557 | source_range: [20; 20), | ||
558 | delete: [20; 20), | ||
559 | insert: "test", | ||
560 | kind: Attribute, | ||
561 | }, | ||
562 | CompletionItem { | ||
563 | label: "used", | ||
564 | source_range: [20; 20), | ||
565 | delete: [20; 20), | ||
566 | insert: "used", | ||
567 | kind: Attribute, | ||
568 | }, | ||
569 | CompletionItem { | ||
570 | label: "warn", | ||
571 | source_range: [20; 20), | ||
572 | delete: [20; 20), | ||
573 | insert: "warn(${0:lint})", | ||
574 | kind: Attribute, | ||
575 | }, | ||
576 | CompletionItem { | ||
577 | label: "windows_subsystem", | ||
578 | source_range: [20; 20), | ||
579 | delete: [20; 20), | ||
580 | insert: "windows_subsystem = \"${0:subsystem}\"", | ||
581 | kind: Attribute, | ||
582 | }, | ||
583 | ] | ||
584 | "### | ||
585 | ); | ||
586 | } | ||
587 | } | ||
diff --git a/crates/ra_ide/src/completion/complete_dot.rs b/crates/ra_ide/src/completion/complete_dot.rs index f433faef3..b93153b48 100644 --- a/crates/ra_ide/src/completion/complete_dot.rs +++ b/crates/ra_ide/src/completion/complete_dot.rs | |||
@@ -2,9 +2,11 @@ | |||
2 | 2 | ||
3 | use hir::{HasVisibility, Type}; | 3 | use hir::{HasVisibility, Type}; |
4 | 4 | ||
5 | use crate::completion::completion_item::CompletionKind; | ||
6 | use crate::{ | 5 | use crate::{ |
7 | completion::{completion_context::CompletionContext, completion_item::Completions}, | 6 | completion::{ |
7 | completion_context::CompletionContext, | ||
8 | completion_item::{CompletionKind, Completions}, | ||
9 | }, | ||
8 | CompletionItem, | 10 | CompletionItem, |
9 | }; | 11 | }; |
10 | use rustc_hash::FxHashSet; | 12 | use rustc_hash::FxHashSet; |
diff --git a/crates/ra_ide/src/completion/complete_keyword.rs b/crates/ra_ide/src/completion/complete_keyword.rs index 38f9c34e7..adefb290e 100644 --- a/crates/ra_ide/src/completion/complete_keyword.rs +++ b/crates/ra_ide/src/completion/complete_keyword.rs | |||
@@ -42,10 +42,14 @@ pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionC | |||
42 | } | 42 | } |
43 | 43 | ||
44 | fn keyword(ctx: &CompletionContext, kw: &str, snippet: &str) -> CompletionItem { | 44 | fn keyword(ctx: &CompletionContext, kw: &str, snippet: &str) -> CompletionItem { |
45 | CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), kw) | 45 | let res = CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), kw) |
46 | .kind(CompletionItemKind::Keyword) | 46 | .kind(CompletionItemKind::Keyword); |
47 | .insert_snippet(snippet) | 47 | |
48 | .build() | 48 | match ctx.config.snippet_cap { |
49 | Some(cap) => res.insert_snippet(cap, snippet), | ||
50 | _ => res.insert_text(if snippet.contains('$') { kw } else { snippet }), | ||
51 | } | ||
52 | .build() | ||
49 | } | 53 | } |
50 | 54 | ||
51 | pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) { | 55 | pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) { |
diff --git a/crates/ra_ide/src/completion/complete_macro_in_item_position.rs b/crates/ra_ide/src/completion/complete_macro_in_item_position.rs index 270e96df0..6000106d0 100644 --- a/crates/ra_ide/src/completion/complete_macro_in_item_position.rs +++ b/crates/ra_ide/src/completion/complete_macro_in_item_position.rs | |||
@@ -41,7 +41,7 @@ mod tests { | |||
41 | @r###" | 41 | @r###" |
42 | [ | 42 | [ |
43 | CompletionItem { | 43 | CompletionItem { |
44 | label: "foo!", | 44 | label: "foo!(…)", |
45 | source_range: [46; 46), | 45 | source_range: [46; 46), |
46 | delete: [46; 46), | 46 | delete: [46; 46), |
47 | insert: "foo!($0)", | 47 | insert: "foo!($0)", |
@@ -81,7 +81,7 @@ mod tests { | |||
81 | @r###" | 81 | @r###" |
82 | [ | 82 | [ |
83 | CompletionItem { | 83 | CompletionItem { |
84 | label: "vec!", | 84 | label: "vec![…]", |
85 | source_range: [280; 280), | 85 | source_range: [280; 280), |
86 | delete: [280; 280), | 86 | delete: [280; 280), |
87 | insert: "vec![$0]", | 87 | insert: "vec![$0]", |
@@ -118,7 +118,7 @@ mod tests { | |||
118 | @r###" | 118 | @r###" |
119 | [ | 119 | [ |
120 | CompletionItem { | 120 | CompletionItem { |
121 | label: "foo!", | 121 | label: "foo! {…}", |
122 | source_range: [163; 163), | 122 | source_range: [163; 163), |
123 | delete: [163; 163), | 123 | delete: [163; 163), |
124 | insert: "foo! {$0}", | 124 | insert: "foo! {$0}", |
diff --git a/crates/ra_ide/src/completion/complete_pattern.rs b/crates/ra_ide/src/completion/complete_pattern.rs index a8b4ce114..218829b10 100644 --- a/crates/ra_ide/src/completion/complete_pattern.rs +++ b/crates/ra_ide/src/completion/complete_pattern.rs | |||
@@ -125,7 +125,7 @@ mod tests { | |||
125 | kind: Enum, | 125 | kind: Enum, |
126 | }, | 126 | }, |
127 | CompletionItem { | 127 | CompletionItem { |
128 | label: "m!", | 128 | label: "m!(…)", |
129 | source_range: [151; 151), | 129 | source_range: [151; 151), |
130 | delete: [151; 151), | 130 | delete: [151; 151), |
131 | insert: "m!($0)", | 131 | insert: "m!($0)", |
diff --git a/crates/ra_ide/src/completion/complete_postfix.rs b/crates/ra_ide/src/completion/complete_postfix.rs index 29c2881c6..8d397b0fe 100644 --- a/crates/ra_ide/src/completion/complete_postfix.rs +++ b/crates/ra_ide/src/completion/complete_postfix.rs | |||
@@ -6,6 +6,7 @@ use ra_syntax::{ | |||
6 | }; | 6 | }; |
7 | use ra_text_edit::TextEdit; | 7 | use ra_text_edit::TextEdit; |
8 | 8 | ||
9 | use super::completion_config::SnippetCap; | ||
9 | use crate::{ | 10 | use crate::{ |
10 | completion::{ | 11 | completion::{ |
11 | completion_context::CompletionContext, | 12 | completion_context::CompletionContext, |
@@ -32,9 +33,15 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | |||
32 | None => return, | 33 | None => return, |
33 | }; | 34 | }; |
34 | 35 | ||
36 | let cap = match ctx.config.snippet_cap { | ||
37 | Some(it) => it, | ||
38 | None => return, | ||
39 | }; | ||
40 | |||
35 | if receiver_ty.is_bool() || receiver_ty.is_unknown() { | 41 | if receiver_ty.is_bool() || receiver_ty.is_unknown() { |
36 | postfix_snippet( | 42 | postfix_snippet( |
37 | ctx, | 43 | ctx, |
44 | cap, | ||
38 | &dot_receiver, | 45 | &dot_receiver, |
39 | "if", | 46 | "if", |
40 | "if expr {}", | 47 | "if expr {}", |
@@ -43,6 +50,7 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | |||
43 | .add_to(acc); | 50 | .add_to(acc); |
44 | postfix_snippet( | 51 | postfix_snippet( |
45 | ctx, | 52 | ctx, |
53 | cap, | ||
46 | &dot_receiver, | 54 | &dot_receiver, |
47 | "while", | 55 | "while", |
48 | "while expr {}", | 56 | "while expr {}", |
@@ -52,11 +60,20 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | |||
52 | } | 60 | } |
53 | 61 | ||
54 | // !&&&42 is a compiler error, ergo process it before considering the references | 62 | // !&&&42 is a compiler error, ergo process it before considering the references |
55 | postfix_snippet(ctx, &dot_receiver, "not", "!expr", &format!("!{}", receiver_text)).add_to(acc); | 63 | postfix_snippet(ctx, cap, &dot_receiver, "not", "!expr", &format!("!{}", receiver_text)) |
64 | .add_to(acc); | ||
56 | 65 | ||
57 | postfix_snippet(ctx, &dot_receiver, "ref", "&expr", &format!("&{}", receiver_text)).add_to(acc); | 66 | postfix_snippet(ctx, cap, &dot_receiver, "ref", "&expr", &format!("&{}", receiver_text)) |
58 | postfix_snippet(ctx, &dot_receiver, "refm", "&mut expr", &format!("&mut {}", receiver_text)) | ||
59 | .add_to(acc); | 67 | .add_to(acc); |
68 | postfix_snippet( | ||
69 | ctx, | ||
70 | cap, | ||
71 | &dot_receiver, | ||
72 | "refm", | ||
73 | "&mut expr", | ||
74 | &format!("&mut {}", receiver_text), | ||
75 | ) | ||
76 | .add_to(acc); | ||
60 | 77 | ||
61 | // The rest of the postfix completions create an expression that moves an argument, | 78 | // The rest of the postfix completions create an expression that moves an argument, |
62 | // so it's better to consider references now to avoid breaking the compilation | 79 | // so it's better to consider references now to avoid breaking the compilation |
@@ -66,6 +83,7 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | |||
66 | 83 | ||
67 | postfix_snippet( | 84 | postfix_snippet( |
68 | ctx, | 85 | ctx, |
86 | cap, | ||
69 | &dot_receiver, | 87 | &dot_receiver, |
70 | "match", | 88 | "match", |
71 | "match expr {}", | 89 | "match expr {}", |
@@ -75,6 +93,7 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | |||
75 | 93 | ||
76 | postfix_snippet( | 94 | postfix_snippet( |
77 | ctx, | 95 | ctx, |
96 | cap, | ||
78 | &dot_receiver, | 97 | &dot_receiver, |
79 | "box", | 98 | "box", |
80 | "Box::new(expr)", | 99 | "Box::new(expr)", |
@@ -82,8 +101,15 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { | |||
82 | ) | 101 | ) |
83 | .add_to(acc); | 102 | .add_to(acc); |
84 | 103 | ||
85 | postfix_snippet(ctx, &dot_receiver, "dbg", "dbg!(expr)", &format!("dbg!({})", receiver_text)) | 104 | postfix_snippet( |
86 | .add_to(acc); | 105 | ctx, |
106 | cap, | ||
107 | &dot_receiver, | ||
108 | "dbg", | ||
109 | "dbg!(expr)", | ||
110 | &format!("dbg!({})", receiver_text), | ||
111 | ) | ||
112 | .add_to(acc); | ||
87 | } | 113 | } |
88 | 114 | ||
89 | fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String { | 115 | fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String { |
@@ -108,6 +134,7 @@ fn include_references(initial_element: &ast::Expr) -> ast::Expr { | |||
108 | 134 | ||
109 | fn postfix_snippet( | 135 | fn postfix_snippet( |
110 | ctx: &CompletionContext, | 136 | ctx: &CompletionContext, |
137 | cap: SnippetCap, | ||
111 | receiver: &ast::Expr, | 138 | receiver: &ast::Expr, |
112 | label: &str, | 139 | label: &str, |
113 | detail: &str, | 140 | detail: &str, |
@@ -121,7 +148,7 @@ fn postfix_snippet( | |||
121 | }; | 148 | }; |
122 | CompletionItem::new(CompletionKind::Postfix, ctx.source_range(), label) | 149 | CompletionItem::new(CompletionKind::Postfix, ctx.source_range(), label) |
123 | .detail(detail) | 150 | .detail(detail) |
124 | .snippet_edit(edit) | 151 | .snippet_edit(cap, edit) |
125 | } | 152 | } |
126 | 153 | ||
127 | #[cfg(test)] | 154 | #[cfg(test)] |
diff --git a/crates/ra_ide/src/completion/complete_qualified_path.rs b/crates/ra_ide/src/completion/complete_qualified_path.rs index d98523406..5a5139e14 100644 --- a/crates/ra_ide/src/completion/complete_qualified_path.rs +++ b/crates/ra_ide/src/completion/complete_qualified_path.rs | |||
@@ -57,9 +57,7 @@ pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionCon | |||
57 | } | 57 | } |
58 | match item { | 58 | match item { |
59 | hir::AssocItem::Function(func) => { | 59 | hir::AssocItem::Function(func) => { |
60 | if !func.has_self_param(ctx.db) { | 60 | acc.add_function(ctx, func, None); |
61 | acc.add_function(ctx, func, None); | ||
62 | } | ||
63 | } | 61 | } |
64 | hir::AssocItem::Const(ct) => acc.add_const(ctx, ct), | 62 | hir::AssocItem::Const(ct) => acc.add_const(ctx, ct), |
65 | hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty), | 63 | hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty), |
@@ -86,9 +84,7 @@ pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionCon | |||
86 | } | 84 | } |
87 | match item { | 85 | match item { |
88 | hir::AssocItem::Function(func) => { | 86 | hir::AssocItem::Function(func) => { |
89 | if !func.has_self_param(ctx.db) { | 87 | acc.add_function(ctx, func, None); |
90 | acc.add_function(ctx, func, None); | ||
91 | } | ||
92 | } | 88 | } |
93 | hir::AssocItem::Const(ct) => acc.add_const(ctx, ct), | 89 | hir::AssocItem::Const(ct) => acc.add_const(ctx, ct), |
94 | hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty), | 90 | hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty), |
@@ -483,6 +479,42 @@ mod tests { | |||
483 | } | 479 | } |
484 | 480 | ||
485 | #[test] | 481 | #[test] |
482 | fn completes_struct_associated_method_with_self() { | ||
483 | assert_debug_snapshot!( | ||
484 | do_reference_completion( | ||
485 | " | ||
486 | //- /lib.rs | ||
487 | /// A Struct | ||
488 | struct S; | ||
489 | |||
490 | impl S { | ||
491 | /// An associated method | ||
492 | fn m(&self) { } | ||
493 | } | ||
494 | |||
495 | fn foo() { let _ = S::<|> } | ||
496 | " | ||
497 | ), | ||
498 | @r###" | ||
499 | [ | ||
500 | CompletionItem { | ||
501 | label: "m()", | ||
502 | source_range: [105; 105), | ||
503 | delete: [105; 105), | ||
504 | insert: "m()$0", | ||
505 | kind: Method, | ||
506 | lookup: "m", | ||
507 | detail: "fn m(&self)", | ||
508 | documentation: Documentation( | ||
509 | "An associated method", | ||
510 | ), | ||
511 | }, | ||
512 | ] | ||
513 | "### | ||
514 | ); | ||
515 | } | ||
516 | |||
517 | #[test] | ||
486 | fn completes_struct_associated_const() { | 518 | fn completes_struct_associated_const() { |
487 | assert_debug_snapshot!( | 519 | assert_debug_snapshot!( |
488 | do_reference_completion( | 520 | do_reference_completion( |
@@ -869,7 +901,7 @@ mod tests { | |||
869 | @r###" | 901 | @r###" |
870 | [ | 902 | [ |
871 | CompletionItem { | 903 | CompletionItem { |
872 | label: "foo!", | 904 | label: "foo!(…)", |
873 | source_range: [179; 179), | 905 | source_range: [179; 179), |
874 | delete: [179; 179), | 906 | delete: [179; 179), |
875 | insert: "foo!($0)", | 907 | insert: "foo!($0)", |
diff --git a/crates/ra_ide/src/completion/complete_snippet.rs b/crates/ra_ide/src/completion/complete_snippet.rs index f731e9b9a..4bccfbfed 100644 --- a/crates/ra_ide/src/completion/complete_snippet.rs +++ b/crates/ra_ide/src/completion/complete_snippet.rs | |||
@@ -1,13 +1,13 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use crate::completion::{ | 3 | use crate::completion::{ |
4 | completion_item::Builder, CompletionContext, CompletionItem, CompletionItemKind, | 4 | completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem, |
5 | CompletionKind, Completions, | 5 | CompletionItemKind, CompletionKind, Completions, |
6 | }; | 6 | }; |
7 | 7 | ||
8 | fn snippet(ctx: &CompletionContext, label: &str, snippet: &str) -> Builder { | 8 | fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder { |
9 | CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label) | 9 | CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label) |
10 | .insert_snippet(snippet) | 10 | .insert_snippet(cap, snippet) |
11 | .kind(CompletionItemKind::Snippet) | 11 | .kind(CompletionItemKind::Snippet) |
12 | } | 12 | } |
13 | 13 | ||
@@ -15,17 +15,27 @@ pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionConte | |||
15 | if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) { | 15 | if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) { |
16 | return; | 16 | return; |
17 | } | 17 | } |
18 | let cap = match ctx.config.snippet_cap { | ||
19 | Some(it) => it, | ||
20 | None => return, | ||
21 | }; | ||
18 | 22 | ||
19 | snippet(ctx, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc); | 23 | snippet(ctx, cap, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc); |
20 | snippet(ctx, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc); | 24 | snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc); |
21 | } | 25 | } |
22 | 26 | ||
23 | pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) { | 27 | pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) { |
24 | if !ctx.is_new_item { | 28 | if !ctx.is_new_item { |
25 | return; | 29 | return; |
26 | } | 30 | } |
31 | let cap = match ctx.config.snippet_cap { | ||
32 | Some(it) => it, | ||
33 | None => return, | ||
34 | }; | ||
35 | |||
27 | snippet( | 36 | snippet( |
28 | ctx, | 37 | ctx, |
38 | cap, | ||
29 | "Test function", | 39 | "Test function", |
30 | "\ | 40 | "\ |
31 | #[test] | 41 | #[test] |
@@ -36,8 +46,8 @@ fn ${1:feature}() { | |||
36 | .lookup_by("tfn") | 46 | .lookup_by("tfn") |
37 | .add_to(acc); | 47 | .add_to(acc); |
38 | 48 | ||
39 | snippet(ctx, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc); | 49 | snippet(ctx, cap, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc); |
40 | snippet(ctx, "pub(crate)", "pub(crate) $0").add_to(acc); | 50 | snippet(ctx, cap, "pub(crate)", "pub(crate) $0").add_to(acc); |
41 | } | 51 | } |
42 | 52 | ||
43 | #[cfg(test)] | 53 | #[cfg(test)] |
diff --git a/crates/ra_ide/src/completion/complete_trait_impl.rs b/crates/ra_ide/src/completion/complete_trait_impl.rs index 2ec0e7ce9..c39943252 100644 --- a/crates/ra_ide/src/completion/complete_trait_impl.rs +++ b/crates/ra_ide/src/completion/complete_trait_impl.rs | |||
@@ -122,7 +122,7 @@ fn add_function_impl( | |||
122 | ctx: &CompletionContext, | 122 | ctx: &CompletionContext, |
123 | func: &hir::Function, | 123 | func: &hir::Function, |
124 | ) { | 124 | ) { |
125 | let display = FunctionSignature::from_hir(ctx.db, *func); | 125 | let signature = FunctionSignature::from_hir(ctx.db, *func); |
126 | 126 | ||
127 | let fn_name = func.name(ctx.db).to_string(); | 127 | let fn_name = func.name(ctx.db).to_string(); |
128 | 128 | ||
@@ -141,12 +141,20 @@ fn add_function_impl( | |||
141 | } else { | 141 | } else { |
142 | CompletionItemKind::Function | 142 | CompletionItemKind::Function |
143 | }; | 143 | }; |
144 | |||
145 | let snippet = format!("{} {{\n $0\n}}", display); | ||
146 | |||
147 | let range = TextRange::from_to(fn_def_node.text_range().start(), ctx.source_range().end()); | 144 | let range = TextRange::from_to(fn_def_node.text_range().start(), ctx.source_range().end()); |
148 | 145 | ||
149 | builder.snippet_edit(TextEdit::replace(range, snippet)).kind(completion_kind).add_to(acc); | 146 | match ctx.config.snippet_cap { |
147 | Some(cap) => { | ||
148 | let snippet = format!("{} {{\n $0\n}}", signature); | ||
149 | builder.snippet_edit(cap, TextEdit::replace(range, snippet)) | ||
150 | } | ||
151 | None => { | ||
152 | let header = format!("{} {{", signature); | ||
153 | builder.text_edit(TextEdit::replace(range, header)) | ||
154 | } | ||
155 | } | ||
156 | .kind(completion_kind) | ||
157 | .add_to(acc); | ||
150 | } | 158 | } |
151 | 159 | ||
152 | fn add_type_alias_impl( | 160 | fn add_type_alias_impl( |
diff --git a/crates/ra_ide/src/completion/complete_unqualified_path.rs b/crates/ra_ide/src/completion/complete_unqualified_path.rs index ad5fdcc4e..638f86eda 100644 --- a/crates/ra_ide/src/completion/complete_unqualified_path.rs +++ b/crates/ra_ide/src/completion/complete_unqualified_path.rs | |||
@@ -4,20 +4,23 @@ use hir::ScopeDef; | |||
4 | use test_utils::tested_by; | 4 | use test_utils::tested_by; |
5 | 5 | ||
6 | use crate::completion::{CompletionContext, Completions}; | 6 | use crate::completion::{CompletionContext, Completions}; |
7 | use hir::{Adt, ModuleDef}; | ||
7 | use ra_syntax::AstNode; | 8 | use ra_syntax::AstNode; |
8 | 9 | ||
9 | pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) { | 10 | pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) { |
10 | if !ctx.is_trivial_path { | 11 | if (!ctx.is_trivial_path && !ctx.is_pat_binding_or_const) |
11 | return; | ||
12 | } | ||
13 | |||
14 | if ctx.is_pat_binding_or_const | ||
15 | || ctx.record_lit_syntax.is_some() | 12 | || ctx.record_lit_syntax.is_some() |
16 | || ctx.record_pat_syntax.is_some() | 13 | || ctx.record_pat_syntax.is_some() |
17 | { | 14 | { |
18 | return; | 15 | return; |
19 | } | 16 | } |
20 | 17 | ||
18 | complete_enum_variants(acc, ctx); | ||
19 | |||
20 | if ctx.is_pat_binding_or_const { | ||
21 | return; | ||
22 | } | ||
23 | |||
21 | ctx.scope().process_all_names(&mut |name, res| { | 24 | ctx.scope().process_all_names(&mut |name, res| { |
22 | if ctx.use_item_syntax.is_some() { | 25 | if ctx.use_item_syntax.is_some() { |
23 | if let (ScopeDef::Unknown, Some(name_ref)) = (&res, &ctx.name_ref_syntax) { | 26 | if let (ScopeDef::Unknown, Some(name_ref)) = (&res, &ctx.name_ref_syntax) { |
@@ -31,6 +34,24 @@ pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionC | |||
31 | }); | 34 | }); |
32 | } | 35 | } |
33 | 36 | ||
37 | fn complete_enum_variants(acc: &mut Completions, ctx: &CompletionContext) { | ||
38 | if let Some(ty) = ctx.expected_type_of(&ctx.token.parent()) { | ||
39 | if let Some(Adt::Enum(enum_data)) = ty.as_adt() { | ||
40 | let variants = enum_data.variants(ctx.db); | ||
41 | let module = enum_data.module(ctx.db); | ||
42 | for variant in variants { | ||
43 | if let Some(path) = module.find_use_path(ctx.db, ModuleDef::from(variant)) { | ||
44 | // Variants with trivial paths are already added by the existing completion logic, | ||
45 | // so we should avoid adding these twice | ||
46 | if path.segments.len() > 1 { | ||
47 | acc.add_enum_variant(ctx, variant, Some(path.to_string())); | ||
48 | } | ||
49 | } | ||
50 | } | ||
51 | } | ||
52 | } | ||
53 | } | ||
54 | |||
34 | #[cfg(test)] | 55 | #[cfg(test)] |
35 | mod tests { | 56 | mod tests { |
36 | use insta::assert_debug_snapshot; | 57 | use insta::assert_debug_snapshot; |
@@ -82,7 +103,7 @@ mod tests { | |||
82 | } | 103 | } |
83 | " | 104 | " |
84 | ), | 105 | ), |
85 | @r###"[]"### | 106 | @"[]" |
86 | ); | 107 | ); |
87 | } | 108 | } |
88 | 109 | ||
@@ -712,7 +733,7 @@ mod tests { | |||
712 | @r###" | 733 | @r###" |
713 | [ | 734 | [ |
714 | CompletionItem { | 735 | CompletionItem { |
715 | label: "bar!", | 736 | label: "bar!(…)", |
716 | source_range: [252; 252), | 737 | source_range: [252; 252), |
717 | delete: [252; 252), | 738 | delete: [252; 252), |
718 | insert: "bar!($0)", | 739 | insert: "bar!($0)", |
@@ -720,7 +741,7 @@ mod tests { | |||
720 | detail: "macro_rules! bar", | 741 | detail: "macro_rules! bar", |
721 | }, | 742 | }, |
722 | CompletionItem { | 743 | CompletionItem { |
723 | label: "baz!", | 744 | label: "baz!(…)", |
724 | source_range: [252; 252), | 745 | source_range: [252; 252), |
725 | delete: [252; 252), | 746 | delete: [252; 252), |
726 | insert: "baz!($0)", | 747 | insert: "baz!($0)", |
@@ -728,7 +749,7 @@ mod tests { | |||
728 | detail: "#[macro_export]\nmacro_rules! baz", | 749 | detail: "#[macro_export]\nmacro_rules! baz", |
729 | }, | 750 | }, |
730 | CompletionItem { | 751 | CompletionItem { |
731 | label: "foo!", | 752 | label: "foo!(…)", |
732 | source_range: [252; 252), | 753 | source_range: [252; 252), |
733 | delete: [252; 252), | 754 | delete: [252; 252), |
734 | insert: "foo!($0)", | 755 | insert: "foo!($0)", |
@@ -781,7 +802,7 @@ mod tests { | |||
781 | @r###" | 802 | @r###" |
782 | [ | 803 | [ |
783 | CompletionItem { | 804 | CompletionItem { |
784 | label: "foo!", | 805 | label: "foo!(…)", |
785 | source_range: [49; 49), | 806 | source_range: [49; 49), |
786 | delete: [49; 49), | 807 | delete: [49; 49), |
787 | insert: "foo!($0)", | 808 | insert: "foo!($0)", |
@@ -820,7 +841,7 @@ mod tests { | |||
820 | @r###" | 841 | @r###" |
821 | [ | 842 | [ |
822 | CompletionItem { | 843 | CompletionItem { |
823 | label: "foo!", | 844 | label: "foo!(…)", |
824 | source_range: [57; 57), | 845 | source_range: [57; 57), |
825 | delete: [57; 57), | 846 | delete: [57; 57), |
826 | insert: "foo!($0)", | 847 | insert: "foo!($0)", |
@@ -859,7 +880,7 @@ mod tests { | |||
859 | @r###" | 880 | @r###" |
860 | [ | 881 | [ |
861 | CompletionItem { | 882 | CompletionItem { |
862 | label: "foo!", | 883 | label: "foo!(…)", |
863 | source_range: [50; 50), | 884 | source_range: [50; 50), |
864 | delete: [50; 50), | 885 | delete: [50; 50), |
865 | insert: "foo!($0)", | 886 | insert: "foo!($0)", |
@@ -932,7 +953,7 @@ mod tests { | |||
932 | @r###" | 953 | @r###" |
933 | [ | 954 | [ |
934 | CompletionItem { | 955 | CompletionItem { |
935 | label: "m!", | 956 | label: "m!(…)", |
936 | source_range: [145; 145), | 957 | source_range: [145; 145), |
937 | delete: [145; 145), | 958 | delete: [145; 145), |
938 | insert: "m!($0)", | 959 | insert: "m!($0)", |
@@ -985,7 +1006,7 @@ mod tests { | |||
985 | @r###" | 1006 | @r###" |
986 | [ | 1007 | [ |
987 | CompletionItem { | 1008 | CompletionItem { |
988 | label: "m!", | 1009 | label: "m!(…)", |
989 | source_range: [145; 146), | 1010 | source_range: [145; 146), |
990 | delete: [145; 146), | 1011 | delete: [145; 146), |
991 | insert: "m!($0)", | 1012 | insert: "m!($0)", |
@@ -1038,7 +1059,7 @@ mod tests { | |||
1038 | @r###" | 1059 | @r###" |
1039 | [ | 1060 | [ |
1040 | CompletionItem { | 1061 | CompletionItem { |
1041 | label: "m!", | 1062 | label: "m!(…)", |
1042 | source_range: [145; 146), | 1063 | source_range: [145; 146), |
1043 | delete: [145; 146), | 1064 | delete: [145; 146), |
1044 | insert: "m!($0)", | 1065 | insert: "m!($0)", |
@@ -1109,4 +1130,182 @@ mod tests { | |||
1109 | "### | 1130 | "### |
1110 | ); | 1131 | ); |
1111 | } | 1132 | } |
1133 | #[test] | ||
1134 | fn completes_enum_variant_matcharm() { | ||
1135 | assert_debug_snapshot!( | ||
1136 | do_reference_completion( | ||
1137 | r" | ||
1138 | enum Foo { | ||
1139 | Bar, | ||
1140 | Baz, | ||
1141 | Quux | ||
1142 | } | ||
1143 | |||
1144 | fn main() { | ||
1145 | let foo = Foo::Quux; | ||
1146 | |||
1147 | match foo { | ||
1148 | Qu<|> | ||
1149 | } | ||
1150 | } | ||
1151 | " | ||
1152 | ), | ||
1153 | @r###" | ||
1154 | [ | ||
1155 | CompletionItem { | ||
1156 | label: "Foo", | ||
1157 | source_range: [248; 250), | ||
1158 | delete: [248; 250), | ||
1159 | insert: "Foo", | ||
1160 | kind: Enum, | ||
1161 | }, | ||
1162 | CompletionItem { | ||
1163 | label: "Foo::Bar", | ||
1164 | source_range: [248; 250), | ||
1165 | delete: [248; 250), | ||
1166 | insert: "Foo::Bar", | ||
1167 | kind: EnumVariant, | ||
1168 | detail: "()", | ||
1169 | }, | ||
1170 | CompletionItem { | ||
1171 | label: "Foo::Baz", | ||
1172 | source_range: [248; 250), | ||
1173 | delete: [248; 250), | ||
1174 | insert: "Foo::Baz", | ||
1175 | kind: EnumVariant, | ||
1176 | detail: "()", | ||
1177 | }, | ||
1178 | CompletionItem { | ||
1179 | label: "Foo::Quux", | ||
1180 | source_range: [248; 250), | ||
1181 | delete: [248; 250), | ||
1182 | insert: "Foo::Quux", | ||
1183 | kind: EnumVariant, | ||
1184 | detail: "()", | ||
1185 | }, | ||
1186 | ] | ||
1187 | "### | ||
1188 | ) | ||
1189 | } | ||
1190 | |||
1191 | #[test] | ||
1192 | fn completes_enum_variant_iflet() { | ||
1193 | assert_debug_snapshot!( | ||
1194 | do_reference_completion( | ||
1195 | r" | ||
1196 | enum Foo { | ||
1197 | Bar, | ||
1198 | Baz, | ||
1199 | Quux | ||
1200 | } | ||
1201 | |||
1202 | fn main() { | ||
1203 | let foo = Foo::Quux; | ||
1204 | |||
1205 | if let Qu<|> = foo { | ||
1206 | |||
1207 | } | ||
1208 | } | ||
1209 | " | ||
1210 | ), | ||
1211 | @r###" | ||
1212 | [ | ||
1213 | CompletionItem { | ||
1214 | label: "Foo", | ||
1215 | source_range: [219; 221), | ||
1216 | delete: [219; 221), | ||
1217 | insert: "Foo", | ||
1218 | kind: Enum, | ||
1219 | }, | ||
1220 | CompletionItem { | ||
1221 | label: "Foo::Bar", | ||
1222 | source_range: [219; 221), | ||
1223 | delete: [219; 221), | ||
1224 | insert: "Foo::Bar", | ||
1225 | kind: EnumVariant, | ||
1226 | detail: "()", | ||
1227 | }, | ||
1228 | CompletionItem { | ||
1229 | label: "Foo::Baz", | ||
1230 | source_range: [219; 221), | ||
1231 | delete: [219; 221), | ||
1232 | insert: "Foo::Baz", | ||
1233 | kind: EnumVariant, | ||
1234 | detail: "()", | ||
1235 | }, | ||
1236 | CompletionItem { | ||
1237 | label: "Foo::Quux", | ||
1238 | source_range: [219; 221), | ||
1239 | delete: [219; 221), | ||
1240 | insert: "Foo::Quux", | ||
1241 | kind: EnumVariant, | ||
1242 | detail: "()", | ||
1243 | }, | ||
1244 | ] | ||
1245 | "### | ||
1246 | ) | ||
1247 | } | ||
1248 | |||
1249 | #[test] | ||
1250 | fn completes_enum_variant_basic_expr() { | ||
1251 | assert_debug_snapshot!( | ||
1252 | do_reference_completion( | ||
1253 | r" | ||
1254 | enum Foo { | ||
1255 | Bar, | ||
1256 | Baz, | ||
1257 | Quux | ||
1258 | } | ||
1259 | |||
1260 | fn main() { | ||
1261 | let foo: Foo = Q<|> | ||
1262 | } | ||
1263 | " | ||
1264 | ), | ||
1265 | @r###" | ||
1266 | [ | ||
1267 | CompletionItem { | ||
1268 | label: "Foo", | ||
1269 | source_range: [185; 186), | ||
1270 | delete: [185; 186), | ||
1271 | insert: "Foo", | ||
1272 | kind: Enum, | ||
1273 | }, | ||
1274 | CompletionItem { | ||
1275 | label: "Foo::Bar", | ||
1276 | source_range: [185; 186), | ||
1277 | delete: [185; 186), | ||
1278 | insert: "Foo::Bar", | ||
1279 | kind: EnumVariant, | ||
1280 | detail: "()", | ||
1281 | }, | ||
1282 | CompletionItem { | ||
1283 | label: "Foo::Baz", | ||
1284 | source_range: [185; 186), | ||
1285 | delete: [185; 186), | ||
1286 | insert: "Foo::Baz", | ||
1287 | kind: EnumVariant, | ||
1288 | detail: "()", | ||
1289 | }, | ||
1290 | CompletionItem { | ||
1291 | label: "Foo::Quux", | ||
1292 | source_range: [185; 186), | ||
1293 | delete: [185; 186), | ||
1294 | insert: "Foo::Quux", | ||
1295 | kind: EnumVariant, | ||
1296 | detail: "()", | ||
1297 | }, | ||
1298 | CompletionItem { | ||
1299 | label: "main()", | ||
1300 | source_range: [185; 186), | ||
1301 | delete: [185; 186), | ||
1302 | insert: "main()$0", | ||
1303 | kind: Function, | ||
1304 | lookup: "main", | ||
1305 | detail: "fn main()", | ||
1306 | }, | ||
1307 | ] | ||
1308 | "### | ||
1309 | ) | ||
1310 | } | ||
1112 | } | 1311 | } |
diff --git a/crates/ra_ide/src/completion/completion_config.rs b/crates/ra_ide/src/completion/completion_config.rs new file mode 100644 index 000000000..71b49ace8 --- /dev/null +++ b/crates/ra_ide/src/completion/completion_config.rs | |||
@@ -0,0 +1,35 @@ | |||
1 | //! Settings for tweaking completion. | ||
2 | //! | ||
3 | //! The fun thing here is `SnippetCap` -- this type can only be created in this | ||
4 | //! module, and we use to statically check that we only produce snippet | ||
5 | //! completions if we are allowed to. | ||
6 | |||
7 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
8 | pub struct CompletionConfig { | ||
9 | pub enable_postfix_completions: bool, | ||
10 | pub add_call_parenthesis: bool, | ||
11 | pub add_call_argument_snippets: bool, | ||
12 | pub snippet_cap: Option<SnippetCap>, | ||
13 | } | ||
14 | |||
15 | impl CompletionConfig { | ||
16 | pub fn allow_snippets(&mut self, yes: bool) { | ||
17 | self.snippet_cap = if yes { Some(SnippetCap { _private: () }) } else { None } | ||
18 | } | ||
19 | } | ||
20 | |||
21 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
22 | pub struct SnippetCap { | ||
23 | _private: (), | ||
24 | } | ||
25 | |||
26 | impl Default for CompletionConfig { | ||
27 | fn default() -> Self { | ||
28 | CompletionConfig { | ||
29 | enable_postfix_completions: true, | ||
30 | add_call_parenthesis: true, | ||
31 | add_call_argument_snippets: true, | ||
32 | snippet_cap: Some(SnippetCap { _private: () }), | ||
33 | } | ||
34 | } | ||
35 | } | ||
diff --git a/crates/ra_ide/src/completion/completion_context.rs b/crates/ra_ide/src/completion/completion_context.rs index 8b3401595..37880448a 100644 --- a/crates/ra_ide/src/completion/completion_context.rs +++ b/crates/ra_ide/src/completion/completion_context.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use hir::{Semantics, SemanticsScope}; | 3 | use hir::{Semantics, SemanticsScope, Type}; |
4 | use ra_db::SourceDatabase; | 4 | use ra_db::SourceDatabase; |
5 | use ra_ide_db::RootDatabase; | 5 | use ra_ide_db::RootDatabase; |
6 | use ra_syntax::{ | 6 | use ra_syntax::{ |
@@ -11,7 +11,7 @@ use ra_syntax::{ | |||
11 | }; | 11 | }; |
12 | use ra_text_edit::AtomTextEdit; | 12 | use ra_text_edit::AtomTextEdit; |
13 | 13 | ||
14 | use crate::{completion::CompletionConfig, FilePosition}; | 14 | use crate::{call_info::ActiveParameter, completion::CompletionConfig, 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. |
@@ -31,7 +31,10 @@ pub(crate) struct CompletionContext<'a> { | |||
31 | pub(super) use_item_syntax: Option<ast::UseItem>, | 31 | pub(super) use_item_syntax: Option<ast::UseItem>, |
32 | pub(super) record_lit_syntax: Option<ast::RecordLit>, | 32 | pub(super) record_lit_syntax: Option<ast::RecordLit>, |
33 | pub(super) record_pat_syntax: Option<ast::RecordPat>, | 33 | pub(super) record_pat_syntax: Option<ast::RecordPat>, |
34 | pub(super) record_field_syntax: Option<ast::RecordField>, | ||
34 | pub(super) impl_def: Option<ast::ImplDef>, | 35 | pub(super) impl_def: Option<ast::ImplDef>, |
36 | /// FIXME: `ActiveParameter` is string-based, which is very wrong | ||
37 | pub(super) active_parameter: Option<ActiveParameter>, | ||
35 | pub(super) is_param: bool, | 38 | pub(super) is_param: bool, |
36 | /// If a name-binding or reference to a const in a pattern. | 39 | /// If a name-binding or reference to a const in a pattern. |
37 | /// Irrefutable patterns (like let) are excluded. | 40 | /// Irrefutable patterns (like let) are excluded. |
@@ -54,6 +57,7 @@ pub(crate) struct CompletionContext<'a> { | |||
54 | pub(super) is_macro_call: bool, | 57 | pub(super) is_macro_call: bool, |
55 | pub(super) is_path_type: bool, | 58 | pub(super) is_path_type: bool, |
56 | pub(super) has_type_args: bool, | 59 | pub(super) has_type_args: bool, |
60 | pub(super) is_attribute: bool, | ||
57 | } | 61 | } |
58 | 62 | ||
59 | impl<'a> CompletionContext<'a> { | 63 | impl<'a> CompletionContext<'a> { |
@@ -94,7 +98,9 @@ impl<'a> CompletionContext<'a> { | |||
94 | use_item_syntax: None, | 98 | use_item_syntax: None, |
95 | record_lit_syntax: None, | 99 | record_lit_syntax: None, |
96 | record_pat_syntax: None, | 100 | record_pat_syntax: None, |
101 | record_field_syntax: None, | ||
97 | impl_def: None, | 102 | impl_def: None, |
103 | active_parameter: ActiveParameter::at(db, position), | ||
98 | is_param: false, | 104 | is_param: false, |
99 | is_pat_binding_or_const: false, | 105 | is_pat_binding_or_const: false, |
100 | is_trivial_path: false, | 106 | is_trivial_path: false, |
@@ -108,6 +114,7 @@ impl<'a> CompletionContext<'a> { | |||
108 | is_path_type: false, | 114 | is_path_type: false, |
109 | has_type_args: false, | 115 | has_type_args: false, |
110 | dot_receiver_is_ambiguous_float_literal: false, | 116 | dot_receiver_is_ambiguous_float_literal: false, |
117 | is_attribute: false, | ||
111 | }; | 118 | }; |
112 | 119 | ||
113 | let mut original_file = original_file.syntax().clone(); | 120 | let mut original_file = original_file.syntax().clone(); |
@@ -168,6 +175,17 @@ impl<'a> CompletionContext<'a> { | |||
168 | self.sema.scope_at_offset(&self.token.parent(), self.offset) | 175 | self.sema.scope_at_offset(&self.token.parent(), self.offset) |
169 | } | 176 | } |
170 | 177 | ||
178 | pub(crate) fn expected_type_of(&self, node: &SyntaxNode) -> Option<Type> { | ||
179 | for ancestor in node.ancestors() { | ||
180 | if let Some(pat) = ast::Pat::cast(ancestor.clone()) { | ||
181 | return self.sema.type_of_pat(&pat); | ||
182 | } else if let Some(expr) = ast::Expr::cast(ancestor) { | ||
183 | return self.sema.type_of_expr(&expr); | ||
184 | } | ||
185 | } | ||
186 | None | ||
187 | } | ||
188 | |||
171 | fn fill( | 189 | fn fill( |
172 | &mut self, | 190 | &mut self, |
173 | original_file: &SyntaxNode, | 191 | original_file: &SyntaxNode, |
@@ -268,6 +286,14 @@ impl<'a> CompletionContext<'a> { | |||
268 | .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE) | 286 | .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE) |
269 | .find_map(ast::FnDef::cast); | 287 | .find_map(ast::FnDef::cast); |
270 | 288 | ||
289 | self.record_field_syntax = self | ||
290 | .sema | ||
291 | .ancestors_with_macros(self.token.parent()) | ||
292 | .take_while(|it| { | ||
293 | it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR | ||
294 | }) | ||
295 | .find_map(ast::RecordField::cast); | ||
296 | |||
271 | let parent = match name_ref.syntax().parent() { | 297 | let parent = match name_ref.syntax().parent() { |
272 | Some(it) => it, | 298 | Some(it) => it, |
273 | None => return, | 299 | None => return, |
@@ -282,6 +308,7 @@ impl<'a> CompletionContext<'a> { | |||
282 | .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast)) | 308 | .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast)) |
283 | .is_some(); | 309 | .is_some(); |
284 | self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some(); | 310 | self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some(); |
311 | self.is_attribute = path.syntax().parent().and_then(ast::Attr::cast).is_some(); | ||
285 | 312 | ||
286 | self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some(); | 313 | self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some(); |
287 | self.has_type_args = segment.type_arg_list().is_some(); | 314 | self.has_type_args = segment.type_arg_list().is_some(); |
diff --git a/crates/ra_ide/src/completion/completion_item.rs b/crates/ra_ide/src/completion/completion_item.rs index bc0f1aff5..5936fb8f7 100644 --- a/crates/ra_ide/src/completion/completion_item.rs +++ b/crates/ra_ide/src/completion/completion_item.rs | |||
@@ -2,6 +2,7 @@ | |||
2 | 2 | ||
3 | use std::fmt; | 3 | use std::fmt; |
4 | 4 | ||
5 | use super::completion_config::SnippetCap; | ||
5 | use hir::Documentation; | 6 | use hir::Documentation; |
6 | use ra_syntax::TextRange; | 7 | use ra_syntax::TextRange; |
7 | use ra_text_edit::TextEdit; | 8 | use ra_text_edit::TextEdit; |
@@ -51,6 +52,9 @@ pub struct CompletionItem { | |||
51 | /// If completing a function call, ask the editor to show parameter popup | 52 | /// If completing a function call, ask the editor to show parameter popup |
52 | /// after completion. | 53 | /// after completion. |
53 | trigger_call_info: bool, | 54 | trigger_call_info: bool, |
55 | |||
56 | /// Score is useful to pre select or display in better order completion items | ||
57 | score: Option<CompletionScore>, | ||
54 | } | 58 | } |
55 | 59 | ||
56 | // We use custom debug for CompletionItem to make `insta`'s diffs more readable. | 60 | // We use custom debug for CompletionItem to make `insta`'s diffs more readable. |
@@ -80,6 +84,9 @@ impl fmt::Debug for CompletionItem { | |||
80 | if self.deprecated { | 84 | if self.deprecated { |
81 | s.field("deprecated", &true); | 85 | s.field("deprecated", &true); |
82 | } | 86 | } |
87 | if let Some(score) = &self.score { | ||
88 | s.field("score", score); | ||
89 | } | ||
83 | if self.trigger_call_info { | 90 | if self.trigger_call_info { |
84 | s.field("trigger_call_info", &true); | 91 | s.field("trigger_call_info", &true); |
85 | } | 92 | } |
@@ -87,6 +94,14 @@ impl fmt::Debug for CompletionItem { | |||
87 | } | 94 | } |
88 | } | 95 | } |
89 | 96 | ||
97 | #[derive(Debug, Clone, Copy)] | ||
98 | pub enum CompletionScore { | ||
99 | /// If only type match | ||
100 | TypeMatch, | ||
101 | /// If type and name match | ||
102 | TypeAndNameMatch, | ||
103 | } | ||
104 | |||
90 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 105 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
91 | pub enum CompletionItemKind { | 106 | pub enum CompletionItemKind { |
92 | Snippet, | 107 | Snippet, |
@@ -106,6 +121,7 @@ pub enum CompletionItemKind { | |||
106 | Method, | 121 | Method, |
107 | TypeParam, | 122 | TypeParam, |
108 | Macro, | 123 | Macro, |
124 | Attribute, | ||
109 | } | 125 | } |
110 | 126 | ||
111 | #[derive(Debug, PartialEq, Eq, Copy, Clone)] | 127 | #[derive(Debug, PartialEq, Eq, Copy, Clone)] |
@@ -119,6 +135,7 @@ pub(crate) enum CompletionKind { | |||
119 | Snippet, | 135 | Snippet, |
120 | Postfix, | 136 | Postfix, |
121 | BuiltinType, | 137 | BuiltinType, |
138 | Attribute, | ||
122 | } | 139 | } |
123 | 140 | ||
124 | #[derive(Debug, PartialEq, Eq, Copy, Clone)] | 141 | #[derive(Debug, PartialEq, Eq, Copy, Clone)] |
@@ -147,6 +164,7 @@ impl CompletionItem { | |||
147 | text_edit: None, | 164 | text_edit: None, |
148 | deprecated: None, | 165 | deprecated: None, |
149 | trigger_call_info: None, | 166 | trigger_call_info: None, |
167 | score: None, | ||
150 | } | 168 | } |
151 | } | 169 | } |
152 | /// What user sees in pop-up in the UI. | 170 | /// What user sees in pop-up in the UI. |
@@ -175,7 +193,7 @@ impl CompletionItem { | |||
175 | } | 193 | } |
176 | /// What string is used for filtering. | 194 | /// What string is used for filtering. |
177 | pub fn lookup(&self) -> &str { | 195 | pub fn lookup(&self) -> &str { |
178 | self.lookup.as_deref().unwrap_or_else(|| self.label()) | 196 | self.lookup.as_deref().unwrap_or(&self.label) |
179 | } | 197 | } |
180 | 198 | ||
181 | pub fn kind(&self) -> Option<CompletionItemKind> { | 199 | pub fn kind(&self) -> Option<CompletionItemKind> { |
@@ -186,6 +204,10 @@ impl CompletionItem { | |||
186 | self.deprecated | 204 | self.deprecated |
187 | } | 205 | } |
188 | 206 | ||
207 | pub fn score(&self) -> Option<CompletionScore> { | ||
208 | self.score | ||
209 | } | ||
210 | |||
189 | pub fn trigger_call_info(&self) -> bool { | 211 | pub fn trigger_call_info(&self) -> bool { |
190 | self.trigger_call_info | 212 | self.trigger_call_info |
191 | } | 213 | } |
@@ -206,6 +228,7 @@ pub(crate) struct Builder { | |||
206 | text_edit: Option<TextEdit>, | 228 | text_edit: Option<TextEdit>, |
207 | deprecated: Option<bool>, | 229 | deprecated: Option<bool>, |
208 | trigger_call_info: Option<bool>, | 230 | trigger_call_info: Option<bool>, |
231 | score: Option<CompletionScore>, | ||
209 | } | 232 | } |
210 | 233 | ||
211 | impl Builder { | 234 | impl Builder { |
@@ -235,6 +258,7 @@ impl Builder { | |||
235 | completion_kind: self.completion_kind, | 258 | completion_kind: self.completion_kind, |
236 | deprecated: self.deprecated.unwrap_or(false), | 259 | deprecated: self.deprecated.unwrap_or(false), |
237 | trigger_call_info: self.trigger_call_info.unwrap_or(false), | 260 | trigger_call_info: self.trigger_call_info.unwrap_or(false), |
261 | score: self.score, | ||
238 | } | 262 | } |
239 | } | 263 | } |
240 | pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder { | 264 | pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder { |
@@ -249,7 +273,11 @@ impl Builder { | |||
249 | self.insert_text = Some(insert_text.into()); | 273 | self.insert_text = Some(insert_text.into()); |
250 | self | 274 | self |
251 | } | 275 | } |
252 | pub(crate) fn insert_snippet(mut self, snippet: impl Into<String>) -> Builder { | 276 | pub(crate) fn insert_snippet( |
277 | mut self, | ||
278 | _cap: SnippetCap, | ||
279 | snippet: impl Into<String>, | ||
280 | ) -> Builder { | ||
253 | self.insert_text_format = InsertTextFormat::Snippet; | 281 | self.insert_text_format = InsertTextFormat::Snippet; |
254 | self.insert_text(snippet) | 282 | self.insert_text(snippet) |
255 | } | 283 | } |
@@ -261,7 +289,7 @@ impl Builder { | |||
261 | self.text_edit = Some(edit); | 289 | self.text_edit = Some(edit); |
262 | self | 290 | self |
263 | } | 291 | } |
264 | pub(crate) fn snippet_edit(mut self, edit: TextEdit) -> Builder { | 292 | pub(crate) fn snippet_edit(mut self, _cap: SnippetCap, edit: TextEdit) -> Builder { |
265 | self.insert_text_format = InsertTextFormat::Snippet; | 293 | self.insert_text_format = InsertTextFormat::Snippet; |
266 | self.text_edit(edit) | 294 | self.text_edit(edit) |
267 | } | 295 | } |
@@ -285,6 +313,10 @@ impl Builder { | |||
285 | self.deprecated = Some(deprecated); | 313 | self.deprecated = Some(deprecated); |
286 | self | 314 | self |
287 | } | 315 | } |
316 | pub(crate) fn set_score(mut self, score: CompletionScore) -> Builder { | ||
317 | self.score = Some(score); | ||
318 | self | ||
319 | } | ||
288 | pub(crate) fn trigger_call_info(mut self) -> Builder { | 320 | pub(crate) fn trigger_call_info(mut self) -> Builder { |
289 | self.trigger_call_info = Some(true); | 321 | self.trigger_call_info = Some(true); |
290 | self | 322 | self |
diff --git a/crates/ra_ide/src/completion/presentation.rs b/crates/ra_ide/src/completion/presentation.rs index 2189cef65..6a6ddc7bd 100644 --- a/crates/ra_ide/src/completion/presentation.rs +++ b/crates/ra_ide/src/completion/presentation.rs | |||
@@ -11,7 +11,7 @@ use crate::{ | |||
11 | CompletionKind, Completions, | 11 | CompletionKind, Completions, |
12 | }, | 12 | }, |
13 | display::{const_label, macro_label, type_label, FunctionSignature}, | 13 | display::{const_label, macro_label, type_label, FunctionSignature}, |
14 | RootDatabase, | 14 | CompletionScore, RootDatabase, |
15 | }; | 15 | }; |
16 | 16 | ||
17 | impl Completions { | 17 | impl Completions { |
@@ -22,16 +22,20 @@ impl Completions { | |||
22 | ty: &Type, | 22 | ty: &Type, |
23 | ) { | 23 | ) { |
24 | let is_deprecated = is_deprecated(field, ctx.db); | 24 | let is_deprecated = is_deprecated(field, ctx.db); |
25 | CompletionItem::new( | 25 | let ty = ty.display(ctx.db).to_string(); |
26 | CompletionKind::Reference, | 26 | let name = field.name(ctx.db); |
27 | ctx.source_range(), | 27 | let mut completion_item = |
28 | field.name(ctx.db).to_string(), | 28 | CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string()) |
29 | ) | 29 | .kind(CompletionItemKind::Field) |
30 | .kind(CompletionItemKind::Field) | 30 | .detail(ty.clone()) |
31 | .detail(ty.display(ctx.db).to_string()) | 31 | .set_documentation(field.docs(ctx.db)) |
32 | .set_documentation(field.docs(ctx.db)) | 32 | .set_deprecated(is_deprecated); |
33 | .set_deprecated(is_deprecated) | 33 | |
34 | .add_to(self); | 34 | if let Some(score) = compute_score(ctx, &ty, &name.to_string()) { |
35 | completion_item = completion_item.set_score(score); | ||
36 | } | ||
37 | |||
38 | completion_item.add_to(self); | ||
35 | } | 39 | } |
36 | 40 | ||
37 | pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) { | 41 | pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) { |
@@ -110,44 +114,23 @@ impl Completions { | |||
110 | 114 | ||
111 | // Add `<>` for generic types | 115 | // Add `<>` for generic types |
112 | if ctx.is_path_type && !ctx.has_type_args && ctx.config.add_call_parenthesis { | 116 | if ctx.is_path_type && !ctx.has_type_args && ctx.config.add_call_parenthesis { |
113 | let has_non_default_type_params = match resolution { | 117 | if let Some(cap) = ctx.config.snippet_cap { |
114 | ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db), | 118 | let has_non_default_type_params = match resolution { |
115 | ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db), | 119 | ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db), |
116 | _ => false, | 120 | ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db), |
117 | }; | 121 | _ => false, |
118 | if has_non_default_type_params { | 122 | }; |
119 | tested_by!(inserts_angle_brackets_for_generics); | 123 | if has_non_default_type_params { |
120 | completion_item = completion_item | 124 | tested_by!(inserts_angle_brackets_for_generics); |
121 | .lookup_by(local_name.clone()) | 125 | completion_item = completion_item |
122 | .label(format!("{}<…>", local_name)) | 126 | .lookup_by(local_name.clone()) |
123 | .insert_snippet(format!("{}<$0>", local_name)); | 127 | .label(format!("{}<…>", local_name)) |
124 | } | 128 | .insert_snippet(cap, format!("{}<$0>", local_name)); |
125 | } | ||
126 | |||
127 | completion_item.kind(kind).set_documentation(docs).add_to(self) | ||
128 | } | ||
129 | |||
130 | fn guess_macro_braces(&self, macro_name: &str, docs: &str) -> &'static str { | ||
131 | let mut votes = [0, 0, 0]; | ||
132 | for (idx, s) in docs.match_indices(¯o_name) { | ||
133 | let (before, after) = (&docs[..idx], &docs[idx + s.len()..]); | ||
134 | // Ensure to match the full word | ||
135 | if after.starts_with('!') | ||
136 | && !before.ends_with(|c: char| c == '_' || c.is_ascii_alphanumeric()) | ||
137 | { | ||
138 | // It may have spaces before the braces like `foo! {}` | ||
139 | match after[1..].chars().find(|&c| !c.is_whitespace()) { | ||
140 | Some('{') => votes[0] += 1, | ||
141 | Some('[') => votes[1] += 1, | ||
142 | Some('(') => votes[2] += 1, | ||
143 | _ => {} | ||
144 | } | 129 | } |
145 | } | 130 | } |
146 | } | 131 | } |
147 | 132 | ||
148 | // Insert a space before `{}`. | 133 | completion_item.kind(kind).set_documentation(docs).add_to(self) |
149 | // We prefer the last one when some votes equal. | ||
150 | *votes.iter().zip(&[" {$0}", "[$0]", "($0)"]).max_by_key(|&(&vote, _)| vote).unwrap().1 | ||
151 | } | 134 | } |
152 | 135 | ||
153 | pub(crate) fn add_macro( | 136 | pub(crate) fn add_macro( |
@@ -171,22 +154,31 @@ impl Completions { | |||
171 | let detail = macro_label(&ast_node); | 154 | let detail = macro_label(&ast_node); |
172 | 155 | ||
173 | let docs = macro_.docs(ctx.db); | 156 | let docs = macro_.docs(ctx.db); |
174 | let macro_declaration = format!("{}!", name); | ||
175 | 157 | ||
176 | let mut builder = | 158 | let mut builder = CompletionItem::new( |
177 | CompletionItem::new(CompletionKind::Reference, ctx.source_range(), ¯o_declaration) | 159 | CompletionKind::Reference, |
178 | .kind(CompletionItemKind::Macro) | 160 | ctx.source_range(), |
179 | .set_documentation(docs.clone()) | 161 | &format!("{}!", name), |
180 | .set_deprecated(is_deprecated(macro_, ctx.db)) | 162 | ) |
181 | .detail(detail); | 163 | .kind(CompletionItemKind::Macro) |
182 | 164 | .set_documentation(docs.clone()) | |
183 | builder = if ctx.use_item_syntax.is_some() || ctx.is_macro_call { | 165 | .set_deprecated(is_deprecated(macro_, ctx.db)) |
184 | tested_by!(dont_insert_macro_call_parens_unncessary); | 166 | .detail(detail); |
185 | builder.insert_text(name) | 167 | |
186 | } else { | 168 | let needs_bang = ctx.use_item_syntax.is_none() && !ctx.is_macro_call; |
187 | let macro_braces_to_insert = | 169 | builder = match ctx.config.snippet_cap { |
188 | self.guess_macro_braces(&name, docs.as_ref().map_or("", |s| s.as_str())); | 170 | Some(cap) if needs_bang => { |
189 | builder.insert_snippet(macro_declaration + macro_braces_to_insert) | 171 | let docs = docs.as_ref().map_or("", |s| s.as_str()); |
172 | let (bra, ket) = guess_macro_braces(&name, docs); | ||
173 | builder | ||
174 | .insert_snippet(cap, format!("{}!{}$0{}", name, bra, ket)) | ||
175 | .label(format!("{}!{}…{}", name, bra, ket)) | ||
176 | } | ||
177 | None if needs_bang => builder.insert_text(format!("{}!", name)), | ||
178 | _ => { | ||
179 | tested_by!(dont_insert_macro_call_parens_unncessary); | ||
180 | builder.insert_text(name) | ||
181 | } | ||
190 | }; | 182 | }; |
191 | 183 | ||
192 | self.add(builder); | 184 | self.add(builder); |
@@ -300,6 +292,42 @@ impl Completions { | |||
300 | } | 292 | } |
301 | } | 293 | } |
302 | 294 | ||
295 | pub(crate) fn compute_score( | ||
296 | ctx: &CompletionContext, | ||
297 | // FIXME: this definitely should be a `Type` | ||
298 | ty: &str, | ||
299 | name: &str, | ||
300 | ) -> Option<CompletionScore> { | ||
301 | let (active_name, active_type) = if let Some(record_field) = &ctx.record_field_syntax { | ||
302 | tested_by!(test_struct_field_completion_in_record_lit); | ||
303 | let (struct_field, _local) = ctx.sema.resolve_record_field(record_field)?; | ||
304 | ( | ||
305 | struct_field.name(ctx.db).to_string(), | ||
306 | struct_field.signature_ty(ctx.db).display(ctx.db).to_string(), | ||
307 | ) | ||
308 | } else if let Some(active_parameter) = &ctx.active_parameter { | ||
309 | tested_by!(test_struct_field_completion_in_func_call); | ||
310 | (active_parameter.name.clone(), active_parameter.ty.clone()) | ||
311 | } else { | ||
312 | return None; | ||
313 | }; | ||
314 | |||
315 | // Compute score | ||
316 | // For the same type | ||
317 | if &active_type != ty { | ||
318 | return None; | ||
319 | } | ||
320 | |||
321 | let mut res = CompletionScore::TypeMatch; | ||
322 | |||
323 | // If same type + same name then go top position | ||
324 | if active_name == name { | ||
325 | res = CompletionScore::TypeAndNameMatch | ||
326 | } | ||
327 | |||
328 | Some(res) | ||
329 | } | ||
330 | |||
303 | enum Params { | 331 | enum Params { |
304 | Named(Vec<String>), | 332 | Named(Vec<String>), |
305 | Anonymous(usize), | 333 | Anonymous(usize), |
@@ -326,6 +354,10 @@ impl Builder { | |||
326 | if ctx.use_item_syntax.is_some() || ctx.is_call { | 354 | if ctx.use_item_syntax.is_some() || ctx.is_call { |
327 | return self; | 355 | return self; |
328 | } | 356 | } |
357 | let cap = match ctx.config.snippet_cap { | ||
358 | Some(it) => it, | ||
359 | None => return self, | ||
360 | }; | ||
329 | // If not an import, add parenthesis automatically. | 361 | // If not an import, add parenthesis automatically. |
330 | tested_by!(inserts_parens_for_function_calls); | 362 | tested_by!(inserts_parens_for_function_calls); |
331 | 363 | ||
@@ -347,7 +379,7 @@ impl Builder { | |||
347 | 379 | ||
348 | (snippet, format!("{}(…)", name)) | 380 | (snippet, format!("{}(…)", name)) |
349 | }; | 381 | }; |
350 | self.lookup_by(name).label(label).insert_snippet(snippet) | 382 | self.lookup_by(name).label(label).insert_snippet(cap, snippet) |
351 | } | 383 | } |
352 | } | 384 | } |
353 | 385 | ||
@@ -355,6 +387,34 @@ fn is_deprecated(node: impl HasAttrs, db: &RootDatabase) -> bool { | |||
355 | node.attrs(db).by_key("deprecated").exists() | 387 | node.attrs(db).by_key("deprecated").exists() |
356 | } | 388 | } |
357 | 389 | ||
390 | fn guess_macro_braces(macro_name: &str, docs: &str) -> (&'static str, &'static str) { | ||
391 | let mut votes = [0, 0, 0]; | ||
392 | for (idx, s) in docs.match_indices(¯o_name) { | ||
393 | let (before, after) = (&docs[..idx], &docs[idx + s.len()..]); | ||
394 | // Ensure to match the full word | ||
395 | if after.starts_with('!') | ||
396 | && !before.ends_with(|c: char| c == '_' || c.is_ascii_alphanumeric()) | ||
397 | { | ||
398 | // It may have spaces before the braces like `foo! {}` | ||
399 | match after[1..].chars().find(|&c| !c.is_whitespace()) { | ||
400 | Some('{') => votes[0] += 1, | ||
401 | Some('[') => votes[1] += 1, | ||
402 | Some('(') => votes[2] += 1, | ||
403 | _ => {} | ||
404 | } | ||
405 | } | ||
406 | } | ||
407 | |||
408 | // Insert a space before `{}`. | ||
409 | // We prefer the last one when some votes equal. | ||
410 | let (_vote, (bra, ket)) = votes | ||
411 | .iter() | ||
412 | .zip(&[(" {", "}"), ("[", "]"), ("(", ")")]) | ||
413 | .max_by_key(|&(&vote, _)| vote) | ||
414 | .unwrap(); | ||
415 | (*bra, *ket) | ||
416 | } | ||
417 | |||
358 | #[cfg(test)] | 418 | #[cfg(test)] |
359 | mod tests { | 419 | mod tests { |
360 | use insta::assert_debug_snapshot; | 420 | use insta::assert_debug_snapshot; |
@@ -1031,4 +1091,237 @@ mod tests { | |||
1031 | "### | 1091 | "### |
1032 | ); | 1092 | ); |
1033 | } | 1093 | } |
1094 | |||
1095 | #[test] | ||
1096 | fn test_struct_field_completion_in_func_call() { | ||
1097 | covers!(test_struct_field_completion_in_func_call); | ||
1098 | assert_debug_snapshot!( | ||
1099 | do_reference_completion( | ||
1100 | r" | ||
1101 | struct A { another_field: i64, the_field: u32, my_string: String } | ||
1102 | fn test(my_param: u32) -> u32 { my_param } | ||
1103 | fn foo(a: A) { | ||
1104 | test(a.<|>) | ||
1105 | } | ||
1106 | ", | ||
1107 | ), | ||
1108 | @r###" | ||
1109 | [ | ||
1110 | CompletionItem { | ||
1111 | label: "another_field", | ||
1112 | source_range: [201; 201), | ||
1113 | delete: [201; 201), | ||
1114 | insert: "another_field", | ||
1115 | kind: Field, | ||
1116 | detail: "i64", | ||
1117 | }, | ||
1118 | CompletionItem { | ||
1119 | label: "my_string", | ||
1120 | source_range: [201; 201), | ||
1121 | delete: [201; 201), | ||
1122 | insert: "my_string", | ||
1123 | kind: Field, | ||
1124 | detail: "{unknown}", | ||
1125 | }, | ||
1126 | CompletionItem { | ||
1127 | label: "the_field", | ||
1128 | source_range: [201; 201), | ||
1129 | delete: [201; 201), | ||
1130 | insert: "the_field", | ||
1131 | kind: Field, | ||
1132 | detail: "u32", | ||
1133 | score: TypeMatch, | ||
1134 | }, | ||
1135 | ] | ||
1136 | "### | ||
1137 | ); | ||
1138 | } | ||
1139 | |||
1140 | #[test] | ||
1141 | fn test_struct_field_completion_in_func_call_with_type_and_name() { | ||
1142 | assert_debug_snapshot!( | ||
1143 | do_reference_completion( | ||
1144 | r" | ||
1145 | struct A { another_field: i64, another_good_type: u32, the_field: u32 } | ||
1146 | fn test(the_field: u32) -> u32 { the_field } | ||
1147 | fn foo(a: A) { | ||
1148 | test(a.<|>) | ||
1149 | } | ||
1150 | ", | ||
1151 | ), | ||
1152 | @r###" | ||
1153 | [ | ||
1154 | CompletionItem { | ||
1155 | label: "another_field", | ||
1156 | source_range: [208; 208), | ||
1157 | delete: [208; 208), | ||
1158 | insert: "another_field", | ||
1159 | kind: Field, | ||
1160 | detail: "i64", | ||
1161 | }, | ||
1162 | CompletionItem { | ||
1163 | label: "another_good_type", | ||
1164 | source_range: [208; 208), | ||
1165 | delete: [208; 208), | ||
1166 | insert: "another_good_type", | ||
1167 | kind: Field, | ||
1168 | detail: "u32", | ||
1169 | score: TypeMatch, | ||
1170 | }, | ||
1171 | CompletionItem { | ||
1172 | label: "the_field", | ||
1173 | source_range: [208; 208), | ||
1174 | delete: [208; 208), | ||
1175 | insert: "the_field", | ||
1176 | kind: Field, | ||
1177 | detail: "u32", | ||
1178 | score: TypeAndNameMatch, | ||
1179 | }, | ||
1180 | ] | ||
1181 | "### | ||
1182 | ); | ||
1183 | } | ||
1184 | |||
1185 | #[test] | ||
1186 | fn test_struct_field_completion_in_record_lit() { | ||
1187 | covers!(test_struct_field_completion_in_func_call); | ||
1188 | assert_debug_snapshot!( | ||
1189 | do_reference_completion( | ||
1190 | r" | ||
1191 | struct A { another_field: i64, another_good_type: u32, the_field: u32 } | ||
1192 | struct B { my_string: String, my_vec: Vec<u32>, the_field: u32 } | ||
1193 | fn foo(a: A) { | ||
1194 | let b = B { | ||
1195 | the_field: a.<|> | ||
1196 | }; | ||
1197 | } | ||
1198 | ", | ||
1199 | ), | ||
1200 | @r###" | ||
1201 | [ | ||
1202 | CompletionItem { | ||
1203 | label: "another_field", | ||
1204 | source_range: [270; 270), | ||
1205 | delete: [270; 270), | ||
1206 | insert: "another_field", | ||
1207 | kind: Field, | ||
1208 | detail: "i64", | ||
1209 | }, | ||
1210 | CompletionItem { | ||
1211 | label: "another_good_type", | ||
1212 | source_range: [270; 270), | ||
1213 | delete: [270; 270), | ||
1214 | insert: "another_good_type", | ||
1215 | kind: Field, | ||
1216 | detail: "u32", | ||
1217 | score: TypeMatch, | ||
1218 | }, | ||
1219 | CompletionItem { | ||
1220 | label: "the_field", | ||
1221 | source_range: [270; 270), | ||
1222 | delete: [270; 270), | ||
1223 | insert: "the_field", | ||
1224 | kind: Field, | ||
1225 | detail: "u32", | ||
1226 | score: TypeAndNameMatch, | ||
1227 | }, | ||
1228 | ] | ||
1229 | "### | ||
1230 | ); | ||
1231 | } | ||
1232 | |||
1233 | #[test] | ||
1234 | fn test_struct_field_completion_in_record_lit_and_fn_call() { | ||
1235 | assert_debug_snapshot!( | ||
1236 | do_reference_completion( | ||
1237 | r" | ||
1238 | struct A { another_field: i64, another_good_type: u32, the_field: u32 } | ||
1239 | struct B { my_string: String, my_vec: Vec<u32>, the_field: u32 } | ||
1240 | fn test(the_field: i64) -> i64 { the_field } | ||
1241 | fn foo(a: A) { | ||
1242 | let b = B { | ||
1243 | the_field: test(a.<|>) | ||
1244 | }; | ||
1245 | } | ||
1246 | ", | ||
1247 | ), | ||
1248 | @r###" | ||
1249 | [ | ||
1250 | CompletionItem { | ||
1251 | label: "another_field", | ||
1252 | source_range: [336; 336), | ||
1253 | delete: [336; 336), | ||
1254 | insert: "another_field", | ||
1255 | kind: Field, | ||
1256 | detail: "i64", | ||
1257 | score: TypeMatch, | ||
1258 | }, | ||
1259 | CompletionItem { | ||
1260 | label: "another_good_type", | ||
1261 | source_range: [336; 336), | ||
1262 | delete: [336; 336), | ||
1263 | insert: "another_good_type", | ||
1264 | kind: Field, | ||
1265 | detail: "u32", | ||
1266 | }, | ||
1267 | CompletionItem { | ||
1268 | label: "the_field", | ||
1269 | source_range: [336; 336), | ||
1270 | delete: [336; 336), | ||
1271 | insert: "the_field", | ||
1272 | kind: Field, | ||
1273 | detail: "u32", | ||
1274 | }, | ||
1275 | ] | ||
1276 | "### | ||
1277 | ); | ||
1278 | } | ||
1279 | |||
1280 | #[test] | ||
1281 | fn test_struct_field_completion_in_fn_call_and_record_lit() { | ||
1282 | assert_debug_snapshot!( | ||
1283 | do_reference_completion( | ||
1284 | r" | ||
1285 | struct A { another_field: i64, another_good_type: u32, the_field: u32 } | ||
1286 | struct B { my_string: String, my_vec: Vec<u32>, the_field: u32 } | ||
1287 | fn test(the_field: i64) -> i64 { the_field } | ||
1288 | fn foo(a: A) { | ||
1289 | test(B { | ||
1290 | the_field: a.<|> | ||
1291 | }); | ||
1292 | } | ||
1293 | ", | ||
1294 | ), | ||
1295 | @r###" | ||
1296 | [ | ||
1297 | CompletionItem { | ||
1298 | label: "another_field", | ||
1299 | source_range: [328; 328), | ||
1300 | delete: [328; 328), | ||
1301 | insert: "another_field", | ||
1302 | kind: Field, | ||
1303 | detail: "i64", | ||
1304 | }, | ||
1305 | CompletionItem { | ||
1306 | label: "another_good_type", | ||
1307 | source_range: [328; 328), | ||
1308 | delete: [328; 328), | ||
1309 | insert: "another_good_type", | ||
1310 | kind: Field, | ||
1311 | detail: "u32", | ||
1312 | score: TypeMatch, | ||
1313 | }, | ||
1314 | CompletionItem { | ||
1315 | label: "the_field", | ||
1316 | source_range: [328; 328), | ||
1317 | delete: [328; 328), | ||
1318 | insert: "the_field", | ||
1319 | kind: Field, | ||
1320 | detail: "u32", | ||
1321 | score: TypeAndNameMatch, | ||
1322 | }, | ||
1323 | ] | ||
1324 | "### | ||
1325 | ); | ||
1326 | } | ||
1034 | } | 1327 | } |
diff --git a/crates/ra_ide/src/display/function_signature.rs b/crates/ra_ide/src/display/function_signature.rs index b967a6816..b5e2785fe 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 | // 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,27 @@ impl FunctionSignature { | |||
151 | 168 | ||
152 | impl From<&'_ ast::FnDef> for FunctionSignature { | 169 | impl 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 | res_types.push( | ||
181 | raw_param.split(':').nth(1).unwrap_or_else(|| " Self")[1..].to_string(), | ||
182 | ); | ||
183 | res.push(raw_param); | ||
161 | } | 184 | } |
162 | 185 | ||
163 | res.extend(param_list.params().map(|param| param.syntax().text().to_string())); | 186 | res.extend(param_list.params().map(|param| param.syntax().text().to_string())); |
187 | res_types.extend(param_list.params().map(|param| { | ||
188 | param.syntax().text().to_string().split(':').nth(1).unwrap()[1..].to_string() | ||
189 | })); | ||
164 | } | 190 | } |
165 | (has_self_param, res) | 191 | (has_self_param, res, res_types) |
166 | } | 192 | } |
167 | 193 | ||
168 | fn param_name_list(node: &ast::FnDef) -> Vec<String> { | 194 | fn param_name_list(node: &ast::FnDef) -> Vec<String> { |
@@ -192,7 +218,7 @@ impl From<&'_ ast::FnDef> for FunctionSignature { | |||
192 | res | 218 | res |
193 | } | 219 | } |
194 | 220 | ||
195 | let (has_self_param, parameters) = param_list(node); | 221 | let (has_self_param, parameters, parameter_types) = param_list(node); |
196 | 222 | ||
197 | FunctionSignature { | 223 | FunctionSignature { |
198 | kind: CallableKind::Function, | 224 | kind: CallableKind::Function, |
@@ -204,6 +230,7 @@ impl From<&'_ ast::FnDef> for FunctionSignature { | |||
204 | .map(|n| n.syntax().text().to_string()), | 230 | .map(|n| n.syntax().text().to_string()), |
205 | parameters, | 231 | parameters, |
206 | parameter_names: param_name_list(node), | 232 | parameter_names: param_name_list(node), |
233 | parameter_types, | ||
207 | generic_parameters: generic_parameters(node), | 234 | generic_parameters: generic_parameters(node), |
208 | where_predicates: where_predicates(node), | 235 | where_predicates: where_predicates(node), |
209 | // docs are processed separately | 236 | // docs are processed separately |
diff --git a/crates/ra_ide/src/display/navigation_target.rs b/crates/ra_ide/src/display/navigation_target.rs index 6289f53f3..67bc9c31b 100644 --- a/crates/ra_ide/src/display/navigation_target.rs +++ b/crates/ra_ide/src/display/navigation_target.rs | |||
@@ -176,7 +176,7 @@ impl ToNav for FileSymbol { | |||
176 | file_id: self.file_id, | 176 | file_id: self.file_id, |
177 | name: self.name.clone(), | 177 | name: self.name.clone(), |
178 | kind: self.kind, | 178 | kind: self.kind, |
179 | full_range: self.ptr.range(), | 179 | full_range: self.range, |
180 | focus_range: self.name_range, | 180 | focus_range: self.name_range, |
181 | container_name: self.container_name.clone(), | 181 | container_name: self.container_name.clone(), |
182 | description: description_from_symbol(db, self), | 182 | description: description_from_symbol(db, self), |
diff --git a/crates/ra_ide/src/lib.rs b/crates/ra_ide/src/lib.rs index 5599f143f..f692fbaa2 100644 --- a/crates/ra_ide/src/lib.rs +++ b/crates/ra_ide/src/lib.rs | |||
@@ -67,7 +67,9 @@ use crate::display::ToNav; | |||
67 | pub use crate::{ | 67 | pub use crate::{ |
68 | assists::{Assist, AssistId}, | 68 | assists::{Assist, AssistId}, |
69 | call_hierarchy::CallItem, | 69 | call_hierarchy::CallItem, |
70 | completion::{CompletionConfig, CompletionItem, CompletionItemKind, InsertTextFormat}, | 70 | completion::{ |
71 | CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat, | ||
72 | }, | ||
71 | diagnostics::Severity, | 73 | diagnostics::Severity, |
72 | display::{file_structure, FunctionSignature, NavigationTarget, StructureNode}, | 74 | display::{file_structure, FunctionSignature, NavigationTarget, StructureNode}, |
73 | expand_macro::ExpandedMacro, | 75 | expand_macro::ExpandedMacro, |
diff --git a/crates/ra_ide/src/marks.rs b/crates/ra_ide/src/marks.rs index eee44e886..bea30fe2a 100644 --- a/crates/ra_ide/src/marks.rs +++ b/crates/ra_ide/src/marks.rs | |||
@@ -9,4 +9,6 @@ test_utils::marks!( | |||
9 | search_filters_by_range | 9 | search_filters_by_range |
10 | dont_insert_macro_call_parens_unncessary | 10 | dont_insert_macro_call_parens_unncessary |
11 | self_fulfilling_completion | 11 | self_fulfilling_completion |
12 | test_struct_field_completion_in_func_call | ||
13 | test_struct_field_completion_in_record_lit | ||
12 | ); | 14 | ); |
diff --git a/crates/ra_ide/src/runnables.rs b/crates/ra_ide/src/runnables.rs index 9433f3a24..05a66e03c 100644 --- a/crates/ra_ide/src/runnables.rs +++ b/crates/ra_ide/src/runnables.rs | |||
@@ -34,7 +34,7 @@ impl Display for TestId { | |||
34 | 34 | ||
35 | #[derive(Debug)] | 35 | #[derive(Debug)] |
36 | pub enum RunnableKind { | 36 | pub enum RunnableKind { |
37 | Test { test_id: TestId }, | 37 | Test { test_id: TestId, attr: TestAttr }, |
38 | TestMod { path: String }, | 38 | TestMod { path: String }, |
39 | Bench { test_id: TestId }, | 39 | Bench { test_id: TestId }, |
40 | Bin, | 40 | Bin, |
@@ -77,7 +77,8 @@ fn runnable_fn(sema: &Semantics<RootDatabase>, fn_def: ast::FnDef) -> Option<Run | |||
77 | }; | 77 | }; |
78 | 78 | ||
79 | if has_test_related_attribute(&fn_def) { | 79 | if has_test_related_attribute(&fn_def) { |
80 | RunnableKind::Test { test_id } | 80 | let attr = TestAttr::from_fn(&fn_def); |
81 | RunnableKind::Test { test_id, attr } | ||
81 | } else if fn_def.has_atom_attr("bench") { | 82 | } else if fn_def.has_atom_attr("bench") { |
82 | RunnableKind::Bench { test_id } | 83 | RunnableKind::Bench { test_id } |
83 | } else { | 84 | } else { |
@@ -87,6 +88,21 @@ fn runnable_fn(sema: &Semantics<RootDatabase>, fn_def: ast::FnDef) -> Option<Run | |||
87 | Some(Runnable { range: fn_def.syntax().text_range(), kind }) | 88 | Some(Runnable { range: fn_def.syntax().text_range(), kind }) |
88 | } | 89 | } |
89 | 90 | ||
91 | #[derive(Debug)] | ||
92 | pub struct TestAttr { | ||
93 | pub ignore: bool, | ||
94 | } | ||
95 | |||
96 | impl TestAttr { | ||
97 | fn from_fn(fn_def: &ast::FnDef) -> TestAttr { | ||
98 | let ignore = fn_def | ||
99 | .attrs() | ||
100 | .filter_map(|attr| attr.simple_name()) | ||
101 | .any(|attribute_text| attribute_text == "ignore"); | ||
102 | TestAttr { ignore } | ||
103 | } | ||
104 | } | ||
105 | |||
90 | /// This is a method with a heuristics to support test methods annotated with custom test annotations, such as | 106 | /// This is a method with a heuristics to support test methods annotated with custom test annotations, such as |
91 | /// `#[test_case(...)]`, `#[tokio::test]` and similar. | 107 | /// `#[test_case(...)]`, `#[tokio::test]` and similar. |
92 | /// Also a regular `#[test]` annotation is supported. | 108 | /// Also a regular `#[test]` annotation is supported. |
@@ -157,6 +173,9 @@ mod tests { | |||
157 | test_id: Path( | 173 | test_id: Path( |
158 | "test_foo", | 174 | "test_foo", |
159 | ), | 175 | ), |
176 | attr: TestAttr { | ||
177 | ignore: false, | ||
178 | }, | ||
160 | }, | 179 | }, |
161 | }, | 180 | }, |
162 | Runnable { | 181 | Runnable { |
@@ -165,6 +184,9 @@ mod tests { | |||
165 | test_id: Path( | 184 | test_id: Path( |
166 | "test_foo", | 185 | "test_foo", |
167 | ), | 186 | ), |
187 | attr: TestAttr { | ||
188 | ignore: true, | ||
189 | }, | ||
168 | }, | 190 | }, |
169 | }, | 191 | }, |
170 | ] | 192 | ] |
@@ -200,6 +222,9 @@ mod tests { | |||
200 | test_id: Path( | 222 | test_id: Path( |
201 | "test_mod::test_foo1", | 223 | "test_mod::test_foo1", |
202 | ), | 224 | ), |
225 | attr: TestAttr { | ||
226 | ignore: false, | ||
227 | }, | ||
203 | }, | 228 | }, |
204 | }, | 229 | }, |
205 | ] | 230 | ] |
@@ -237,6 +262,9 @@ mod tests { | |||
237 | test_id: Path( | 262 | test_id: Path( |
238 | "foo::test_mod::test_foo1", | 263 | "foo::test_mod::test_foo1", |
239 | ), | 264 | ), |
265 | attr: TestAttr { | ||
266 | ignore: false, | ||
267 | }, | ||
240 | }, | 268 | }, |
241 | }, | 269 | }, |
242 | ] | 270 | ] |
@@ -276,6 +304,9 @@ mod tests { | |||
276 | test_id: Path( | 304 | test_id: Path( |
277 | "foo::bar::test_mod::test_foo1", | 305 | "foo::bar::test_mod::test_foo1", |
278 | ), | 306 | ), |
307 | attr: TestAttr { | ||
308 | ignore: false, | ||
309 | }, | ||
279 | }, | 310 | }, |
280 | }, | 311 | }, |
281 | ] | 312 | ] |
diff --git a/crates/ra_ide/src/snapshots/highlight_strings.html b/crates/ra_ide/src/snapshots/highlight_strings.html new file mode 100644 index 000000000..433f2e0c5 --- /dev/null +++ b/crates/ra_ide/src/snapshots/highlight_strings.html | |||
@@ -0,0 +1,82 @@ | |||
1 | |||
2 | <style> | ||
3 | body { margin: 0; } | ||
4 | pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padding: 0.4em; } | ||
5 | |||
6 | .lifetime { color: #DFAF8F; font-style: italic; } | ||
7 | .comment { color: #7F9F7F; } | ||
8 | .struct, .enum { color: #7CB8BB; } | ||
9 | .enum_variant { color: #BDE0F3; } | ||
10 | .string_literal { color: #CC9393; } | ||
11 | .field { color: #94BFF3; } | ||
12 | .function { color: #93E0E3; } | ||
13 | .parameter { color: #94BFF3; } | ||
14 | .text { color: #DCDCCC; } | ||
15 | .type { color: #7CB8BB; } | ||
16 | .builtin_type { color: #8CD0D3; } | ||
17 | .type_param { color: #DFAF8F; } | ||
18 | .attribute { color: #94BFF3; } | ||
19 | .numeric_literal { color: #BFEBBF; } | ||
20 | .macro { color: #94BFF3; } | ||
21 | .module { color: #AFD8AF; } | ||
22 | .variable { color: #DCDCCC; } | ||
23 | .mutable { text-decoration: underline; } | ||
24 | |||
25 | .keyword { color: #F0DFAF; font-weight: bold; } | ||
26 | .keyword.unsafe { color: #BC8383; font-weight: bold; } | ||
27 | .control { font-style: italic; } | ||
28 | </style> | ||
29 | <pre><code><span class="macro">macro_rules!</span> println { | ||
30 | ($($arg:tt)*) => ({ | ||
31 | $<span class="keyword">crate</span>::io::_print($<span class="keyword">crate</span>::format_args_nl!($($arg)*)); | ||
32 | }) | ||
33 | } | ||
34 | #[rustc_builtin_macro] | ||
35 | <span class="macro">macro_rules!</span> format_args_nl { | ||
36 | ($fmt:expr) => {{ <span class="comment">/* compiler built-in */</span> }}; | ||
37 | ($fmt:expr, $($args:tt)*) => {{ <span class="comment">/* compiler built-in */</span> }}; | ||
38 | } | ||
39 | |||
40 | <span class="keyword">fn</span> <span class="function declaration">main</span>() { | ||
41 | <span class="comment">// from https://doc.rust-lang.org/std/fmt/index.html</span> | ||
42 | <span class="macro">println!</span>(<span class="string_literal">"Hello"</span>); <span class="comment">// => "Hello"</span> | ||
43 | <span class="macro">println!</span>(<span class="string_literal">"Hello, </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"world"</span>); <span class="comment">// => "Hello, world!"</span> | ||
44 | <span class="macro">println!</span>(<span class="string_literal">"The number is </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="numeric_literal">1</span>); <span class="comment">// => "The number is 1"</span> | ||
45 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">?</span><span class="attribute">}</span><span class="string_literal">"</span>, (<span class="numeric_literal">3</span>, <span class="numeric_literal">4</span>)); <span class="comment">// => "(3, 4)"</span> | ||
46 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="variable">value</span><span class="attribute">}</span><span class="string_literal">"</span>, value=<span class="numeric_literal">4</span>); <span class="comment">// => "4"</span> | ||
47 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="numeric_literal">1</span>, <span class="numeric_literal">2</span>); <span class="comment">// => "1 2"</span> | ||
48 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">:</span><span class="numeric_literal">0</span><span class="numeric_literal">4</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="numeric_literal">42</span>); <span class="comment">// => "0042" with leading zerosV</span> | ||
49 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="numeric_literal">1</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="numeric_literal">0</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="numeric_literal">1</span>, <span class="numeric_literal">2</span>); <span class="comment">// => "2 1 1 2"</span> | ||
50 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="variable">argument</span><span class="attribute">}</span><span class="string_literal">"</span>, argument = <span class="string_literal">"test"</span>); <span class="comment">// => "test"</span> | ||
51 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="variable">name</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="numeric_literal">1</span>, name = <span class="numeric_literal">2</span>); <span class="comment">// => "2 1"</span> | ||
52 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="variable">a</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="variable">c</span><span class="attribute">}</span><span class="string_literal"> </span><span class="attribute">{</span><span class="variable">b</span><span class="attribute">}</span><span class="string_literal">"</span>, a=<span class="string_literal">"a"</span>, b=<span class="char_literal">'b'</span>, c=<span class="numeric_literal">3</span>); <span class="comment">// => "a 3 b"</span> | ||
53 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>); | ||
54 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="numeric_literal">1</span><span class="attribute">$</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>, <span class="numeric_literal">5</span>); | ||
55 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="numeric_literal">1</span><span class="attribute">:</span><span class="numeric_literal">0</span><span class="attribute">$</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="numeric_literal">5</span>, <span class="string_literal">"x"</span>); | ||
56 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="variable">width</span><span class="attribute">$</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>, width = <span class="numeric_literal">5</span>); | ||
57 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute"><</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>); | ||
58 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">-</span><span class="attribute"><</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>); | ||
59 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">^</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>); | ||
60 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">></span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"x"</span>); | ||
61 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">+</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="numeric_literal">5</span>); | ||
62 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">#</span><span class="variable">x</span><span class="string_literal">}!"</span>, <span class="numeric_literal">27</span>); | ||
63 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="numeric_literal">0</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="numeric_literal">5</span>); | ||
64 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">:</span><span class="numeric_literal">0</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">!"</span>, -<span class="numeric_literal">5</span>); | ||
65 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">#</span><span class="numeric_literal">0</span><span class="numeric_literal">10</span><span class="variable">x</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="numeric_literal">27</span>); | ||
66 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="numeric_literal">0</span><span class="attribute">}</span><span class="string_literal"> is </span><span class="attribute">{</span><span class="numeric_literal">1</span><span class="attribute">:</span><span class="attribute">.</span><span class="numeric_literal">5</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="string_literal">"x"</span>, <span class="numeric_literal">0.01</span>); | ||
67 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="numeric_literal">1</span><span class="attribute">}</span><span class="string_literal"> is </span><span class="attribute">{</span><span class="numeric_literal">2</span><span class="attribute">:</span><span class="attribute">.</span><span class="numeric_literal">0</span><span class="attribute">$</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="numeric_literal">5</span>, <span class="string_literal">"x"</span>, <span class="numeric_literal">0.01</span>); | ||
68 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="numeric_literal">0</span><span class="attribute">}</span><span class="string_literal"> is </span><span class="attribute">{</span><span class="numeric_literal">2</span><span class="attribute">:</span><span class="attribute">.</span><span class="numeric_literal">1</span><span class="attribute">$</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="string_literal">"x"</span>, <span class="numeric_literal">5</span>, <span class="numeric_literal">0.01</span>); | ||
69 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal"> is </span><span class="attribute">{</span><span class="attribute">:</span><span class="attribute">.</span><span class="attribute">*</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="string_literal">"x"</span>, <span class="numeric_literal">5</span>, <span class="numeric_literal">0.01</span>); | ||
70 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal"> is </span><span class="attribute">{</span><span class="numeric_literal">2</span><span class="attribute">:</span><span class="attribute">.</span><span class="attribute">*</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="string_literal">"x"</span>, <span class="numeric_literal">5</span>, <span class="numeric_literal">0.01</span>); | ||
71 | <span class="macro">println!</span>(<span class="string_literal">"Hello </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal"> is </span><span class="attribute">{</span><span class="variable">number</span><span class="attribute">:</span><span class="attribute">.</span><span class="variable">prec</span><span class="attribute">$</span><span class="attribute">}</span><span class="string_literal">"</span>, <span class="string_literal">"x"</span>, prec = <span class="numeric_literal">5</span>, number = <span class="numeric_literal">0.01</span>); | ||
72 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">, `</span><span class="attribute">{</span><span class="variable">name</span><span class="attribute">:</span><span class="attribute">.</span><span class="attribute">*</span><span class="attribute">}</span><span class="string_literal">` has 3 fractional digits"</span>, <span class="string_literal">"Hello"</span>, <span class="numeric_literal">3</span>, name=<span class="numeric_literal">1234.56</span>); | ||
73 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">, `</span><span class="attribute">{</span><span class="variable">name</span><span class="attribute">:</span><span class="attribute">.</span><span class="attribute">*</span><span class="attribute">}</span><span class="string_literal">` has 3 characters"</span>, <span class="string_literal">"Hello"</span>, <span class="numeric_literal">3</span>, name=<span class="string_literal">"1234.56"</span>); | ||
74 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">, `</span><span class="attribute">{</span><span class="variable">name</span><span class="attribute">:</span><span class="attribute">></span><span class="numeric_literal">8</span><span class="attribute">.</span><span class="attribute">*</span><span class="attribute">}</span><span class="string_literal">` has 3 right-aligned characters"</span>, <span class="string_literal">"Hello"</span>, <span class="numeric_literal">3</span>, name=<span class="string_literal">"1234.56"</span>); | ||
75 | <span class="macro">println!</span>(<span class="string_literal">"Hello {{}}"</span>); | ||
76 | <span class="macro">println!</span>(<span class="string_literal">"{{ Hello"</span>); | ||
77 | |||
78 | <span class="macro">println!</span>(<span class="string_literal">r"Hello, </span><span class="attribute">{</span><span class="attribute">}</span><span class="string_literal">!"</span>, <span class="string_literal">"world"</span>); | ||
79 | |||
80 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="variable">\x41</span><span class="attribute">}</span><span class="string_literal">"</span>, A = <span class="numeric_literal">92</span>); | ||
81 | <span class="macro">println!</span>(<span class="string_literal">"</span><span class="attribute">{</span><span class="variable">ничоси</span><span class="attribute">}</span><span class="string_literal">"</span>, ничоси = <span class="numeric_literal">92</span>); | ||
82 | }</code></pre> \ No newline at end of file | ||
diff --git a/crates/ra_ide/src/syntax_highlighting.rs b/crates/ra_ide/src/syntax_highlighting.rs index 93d502875..c0728bfb1 100644 --- a/crates/ra_ide/src/syntax_highlighting.rs +++ b/crates/ra_ide/src/syntax_highlighting.rs | |||
@@ -12,15 +12,16 @@ use ra_ide_db::{ | |||
12 | }; | 12 | }; |
13 | use ra_prof::profile; | 13 | use ra_prof::profile; |
14 | use ra_syntax::{ | 14 | use ra_syntax::{ |
15 | ast::{self, HasQuotes, HasStringValue}, | 15 | ast::{self, HasFormatSpecifier, HasQuotes, HasStringValue}, |
16 | AstNode, AstToken, Direction, NodeOrToken, SyntaxElement, | 16 | AstNode, AstToken, Direction, NodeOrToken, SyntaxElement, |
17 | SyntaxKind::*, | 17 | SyntaxKind::*, |
18 | SyntaxToken, TextRange, WalkEvent, T, | 18 | SyntaxToken, TextRange, WalkEvent, T, |
19 | }; | 19 | }; |
20 | use rustc_hash::FxHashMap; | 20 | use rustc_hash::FxHashMap; |
21 | 21 | ||
22 | use crate::{call_info::call_info_for_token, Analysis, FileId}; | 22 | use crate::{call_info::ActiveParameter, Analysis, FileId}; |
23 | 23 | ||
24 | use ast::FormatSpecifier; | ||
24 | pub(crate) use html::highlight_as_html; | 25 | pub(crate) use html::highlight_as_html; |
25 | pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag}; | 26 | pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag}; |
26 | 27 | ||
@@ -31,6 +32,81 @@ pub struct HighlightedRange { | |||
31 | pub binding_hash: Option<u64>, | 32 | pub binding_hash: Option<u64>, |
32 | } | 33 | } |
33 | 34 | ||
35 | #[derive(Debug)] | ||
36 | struct HighlightedRangeStack { | ||
37 | stack: Vec<Vec<HighlightedRange>>, | ||
38 | } | ||
39 | |||
40 | /// We use a stack to implement the flattening logic for the highlighted | ||
41 | /// syntax ranges. | ||
42 | impl HighlightedRangeStack { | ||
43 | fn new() -> Self { | ||
44 | Self { stack: vec![Vec::new()] } | ||
45 | } | ||
46 | |||
47 | fn push(&mut self) { | ||
48 | self.stack.push(Vec::new()); | ||
49 | } | ||
50 | |||
51 | /// Flattens the highlighted ranges. | ||
52 | /// | ||
53 | /// For example `#[cfg(feature = "foo")]` contains the nested ranges: | ||
54 | /// 1) parent-range: Attribute [0, 23) | ||
55 | /// 2) child-range: String [16, 21) | ||
56 | /// | ||
57 | /// The following code implements the flattening, for our example this results to: | ||
58 | /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]` | ||
59 | fn pop(&mut self) { | ||
60 | let children = self.stack.pop().unwrap(); | ||
61 | let prev = self.stack.last_mut().unwrap(); | ||
62 | let needs_flattening = !children.is_empty() | ||
63 | && !prev.is_empty() | ||
64 | && children.first().unwrap().range.is_subrange(&prev.last().unwrap().range); | ||
65 | if !needs_flattening { | ||
66 | prev.extend(children); | ||
67 | } else { | ||
68 | let mut parent = prev.pop().unwrap(); | ||
69 | for ele in children { | ||
70 | assert!(ele.range.is_subrange(&parent.range)); | ||
71 | let mut cloned = parent.clone(); | ||
72 | parent.range = TextRange::from_to(parent.range.start(), ele.range.start()); | ||
73 | cloned.range = TextRange::from_to(ele.range.end(), cloned.range.end()); | ||
74 | if !parent.range.is_empty() { | ||
75 | prev.push(parent); | ||
76 | } | ||
77 | prev.push(ele); | ||
78 | parent = cloned; | ||
79 | } | ||
80 | if !parent.range.is_empty() { | ||
81 | prev.push(parent); | ||
82 | } | ||
83 | } | ||
84 | } | ||
85 | |||
86 | fn add(&mut self, range: HighlightedRange) { | ||
87 | self.stack | ||
88 | .last_mut() | ||
89 | .expect("during DFS traversal, the stack must not be empty") | ||
90 | .push(range) | ||
91 | } | ||
92 | |||
93 | fn flattened(mut self) -> Vec<HighlightedRange> { | ||
94 | assert_eq!( | ||
95 | self.stack.len(), | ||
96 | 1, | ||
97 | "after DFS traversal, the stack should only contain a single element" | ||
98 | ); | ||
99 | let mut res = self.stack.pop().unwrap(); | ||
100 | res.sort_by_key(|range| range.range.start()); | ||
101 | // Check that ranges are sorted and disjoint | ||
102 | assert!(res | ||
103 | .iter() | ||
104 | .zip(res.iter().skip(1)) | ||
105 | .all(|(left, right)| left.range.end() <= right.range.start())); | ||
106 | res | ||
107 | } | ||
108 | } | ||
109 | |||
34 | pub(crate) fn highlight( | 110 | pub(crate) fn highlight( |
35 | db: &RootDatabase, | 111 | db: &RootDatabase, |
36 | file_id: FileId, | 112 | file_id: FileId, |
@@ -57,52 +133,18 @@ pub(crate) fn highlight( | |||
57 | let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default(); | 133 | let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default(); |
58 | // We use a stack for the DFS traversal below. | 134 | // We use a stack for the DFS traversal below. |
59 | // When we leave a node, the we use it to flatten the highlighted ranges. | 135 | // When we leave a node, the we use it to flatten the highlighted ranges. |
60 | let mut res: Vec<Vec<HighlightedRange>> = vec![Vec::new()]; | 136 | let mut stack = HighlightedRangeStack::new(); |
61 | 137 | ||
62 | let mut current_macro_call: Option<ast::MacroCall> = None; | 138 | let mut current_macro_call: Option<ast::MacroCall> = None; |
139 | let mut format_string: Option<SyntaxElement> = None; | ||
63 | 140 | ||
64 | // Walk all nodes, keeping track of whether we are inside a macro or not. | 141 | // Walk all nodes, keeping track of whether we are inside a macro or not. |
65 | // If in macro, expand it first and highlight the expanded code. | 142 | // If in macro, expand it first and highlight the expanded code. |
66 | for event in root.preorder_with_tokens() { | 143 | for event in root.preorder_with_tokens() { |
67 | match &event { | 144 | match &event { |
68 | WalkEvent::Enter(_) => res.push(Vec::new()), | 145 | WalkEvent::Enter(_) => stack.push(), |
69 | WalkEvent::Leave(_) => { | 146 | WalkEvent::Leave(_) => stack.pop(), |
70 | /* Flattens the highlighted ranges. | ||
71 | * | ||
72 | * For example `#[cfg(feature = "foo")]` contains the nested ranges: | ||
73 | * 1) parent-range: Attribute [0, 23) | ||
74 | * 2) child-range: String [16, 21) | ||
75 | * | ||
76 | * The following code implements the flattening, for our example this results to: | ||
77 | * `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]` | ||
78 | */ | ||
79 | let children = res.pop().unwrap(); | ||
80 | let prev = res.last_mut().unwrap(); | ||
81 | let needs_flattening = !children.is_empty() | ||
82 | && !prev.is_empty() | ||
83 | && children.first().unwrap().range.is_subrange(&prev.last().unwrap().range); | ||
84 | if !needs_flattening { | ||
85 | prev.extend(children); | ||
86 | } else { | ||
87 | let mut parent = prev.pop().unwrap(); | ||
88 | for ele in children { | ||
89 | assert!(ele.range.is_subrange(&parent.range)); | ||
90 | let mut cloned = parent.clone(); | ||
91 | parent.range = TextRange::from_to(parent.range.start(), ele.range.start()); | ||
92 | cloned.range = TextRange::from_to(ele.range.end(), cloned.range.end()); | ||
93 | if !parent.range.is_empty() { | ||
94 | prev.push(parent); | ||
95 | } | ||
96 | prev.push(ele); | ||
97 | parent = cloned; | ||
98 | } | ||
99 | if !parent.range.is_empty() { | ||
100 | prev.push(parent); | ||
101 | } | ||
102 | } | ||
103 | } | ||
104 | }; | 147 | }; |
105 | let current = res.last_mut().expect("during DFS traversal, the stack must not be empty"); | ||
106 | 148 | ||
107 | let event_range = match &event { | 149 | let event_range = match &event { |
108 | WalkEvent::Enter(it) => it.text_range(), | 150 | WalkEvent::Enter(it) => it.text_range(), |
@@ -119,7 +161,7 @@ pub(crate) fn highlight( | |||
119 | WalkEvent::Enter(Some(mc)) => { | 161 | WalkEvent::Enter(Some(mc)) => { |
120 | current_macro_call = Some(mc.clone()); | 162 | current_macro_call = Some(mc.clone()); |
121 | if let Some(range) = macro_call_range(&mc) { | 163 | if let Some(range) = macro_call_range(&mc) { |
122 | current.push(HighlightedRange { | 164 | stack.add(HighlightedRange { |
123 | range, | 165 | range, |
124 | highlight: HighlightTag::Macro.into(), | 166 | highlight: HighlightTag::Macro.into(), |
125 | binding_hash: None, | 167 | binding_hash: None, |
@@ -130,6 +172,7 @@ pub(crate) fn highlight( | |||
130 | WalkEvent::Leave(Some(mc)) => { | 172 | WalkEvent::Leave(Some(mc)) => { |
131 | assert!(current_macro_call == Some(mc)); | 173 | assert!(current_macro_call == Some(mc)); |
132 | current_macro_call = None; | 174 | current_macro_call = None; |
175 | format_string = None; | ||
133 | continue; | 176 | continue; |
134 | } | 177 | } |
135 | _ => (), | 178 | _ => (), |
@@ -150,6 +193,30 @@ pub(crate) fn highlight( | |||
150 | }; | 193 | }; |
151 | let token = sema.descend_into_macros(token.clone()); | 194 | let token = sema.descend_into_macros(token.clone()); |
152 | let parent = token.parent(); | 195 | let parent = token.parent(); |
196 | |||
197 | // Check if macro takes a format string and remember it for highlighting later. | ||
198 | // The macros that accept a format string expand to a compiler builtin macros | ||
199 | // `format_args` and `format_args_nl`. | ||
200 | if let Some(fmt_macro_call) = parent.parent().and_then(ast::MacroCall::cast) { | ||
201 | if let Some(name) = | ||
202 | fmt_macro_call.path().and_then(|p| p.segment()).and_then(|s| s.name_ref()) | ||
203 | { | ||
204 | match name.text().as_str() { | ||
205 | "format_args" | "format_args_nl" => { | ||
206 | format_string = parent | ||
207 | .children_with_tokens() | ||
208 | .filter(|t| t.kind() != WHITESPACE) | ||
209 | .nth(1) | ||
210 | .filter(|e| { | ||
211 | ast::String::can_cast(e.kind()) | ||
212 | || ast::RawString::can_cast(e.kind()) | ||
213 | }) | ||
214 | } | ||
215 | _ => {} | ||
216 | } | ||
217 | } | ||
218 | } | ||
219 | |||
153 | // We only care Name and Name_ref | 220 | // We only care Name and Name_ref |
154 | match (token.kind(), parent.kind()) { | 221 | match (token.kind(), parent.kind()) { |
155 | (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(), | 222 | (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(), |
@@ -161,27 +228,72 @@ pub(crate) fn highlight( | |||
161 | 228 | ||
162 | if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) { | 229 | if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) { |
163 | let expanded = element_to_highlight.as_token().unwrap().clone(); | 230 | let expanded = element_to_highlight.as_token().unwrap().clone(); |
164 | if highlight_injection(current, &sema, token, expanded).is_some() { | 231 | if highlight_injection(&mut stack, &sema, token, expanded).is_some() { |
165 | continue; | 232 | continue; |
166 | } | 233 | } |
167 | } | 234 | } |
168 | 235 | ||
236 | let is_format_string = format_string.as_ref() == Some(&element_to_highlight); | ||
237 | |||
169 | if let Some((highlight, binding_hash)) = | 238 | if let Some((highlight, binding_hash)) = |
170 | highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight) | 239 | highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone()) |
171 | { | 240 | { |
172 | current.push(HighlightedRange { range, highlight, binding_hash }); | 241 | stack.add(HighlightedRange { range, highlight, binding_hash }); |
242 | if let Some(string) = | ||
243 | element_to_highlight.as_token().cloned().and_then(ast::String::cast) | ||
244 | { | ||
245 | stack.push(); | ||
246 | if is_format_string { | ||
247 | string.lex_format_specifier(|piece_range, kind| { | ||
248 | if let Some(highlight) = highlight_format_specifier(kind) { | ||
249 | stack.add(HighlightedRange { | ||
250 | range: piece_range + range.start(), | ||
251 | highlight: highlight.into(), | ||
252 | binding_hash: None, | ||
253 | }); | ||
254 | } | ||
255 | }); | ||
256 | } | ||
257 | stack.pop(); | ||
258 | } else if let Some(string) = | ||
259 | element_to_highlight.as_token().cloned().and_then(ast::RawString::cast) | ||
260 | { | ||
261 | stack.push(); | ||
262 | if is_format_string { | ||
263 | string.lex_format_specifier(|piece_range, kind| { | ||
264 | if let Some(highlight) = highlight_format_specifier(kind) { | ||
265 | stack.add(HighlightedRange { | ||
266 | range: piece_range + range.start(), | ||
267 | highlight: highlight.into(), | ||
268 | binding_hash: None, | ||
269 | }); | ||
270 | } | ||
271 | }); | ||
272 | } | ||
273 | stack.pop(); | ||
274 | } | ||
173 | } | 275 | } |
174 | } | 276 | } |
175 | 277 | ||
176 | assert_eq!(res.len(), 1, "after DFS traversal, the stack should only contain a single element"); | 278 | stack.flattened() |
177 | let mut res = res.pop().unwrap(); | 279 | } |
178 | res.sort_by_key(|range| range.range.start()); | 280 | |
179 | // Check that ranges are sorted and disjoint | 281 | fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> { |
180 | assert!(res | 282 | Some(match kind { |
181 | .iter() | 283 | FormatSpecifier::Open |
182 | .zip(res.iter().skip(1)) | 284 | | FormatSpecifier::Close |
183 | .all(|(left, right)| left.range.end() <= right.range.start())); | 285 | | FormatSpecifier::Colon |
184 | res | 286 | | FormatSpecifier::Fill |
287 | | FormatSpecifier::Align | ||
288 | | FormatSpecifier::Sign | ||
289 | | FormatSpecifier::NumberSign | ||
290 | | FormatSpecifier::DollarSign | ||
291 | | FormatSpecifier::Dot | ||
292 | | FormatSpecifier::Asterisk | ||
293 | | FormatSpecifier::QuestionMark => HighlightTag::Attribute, | ||
294 | FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral, | ||
295 | FormatSpecifier::Identifier => HighlightTag::Local, | ||
296 | }) | ||
185 | } | 297 | } |
186 | 298 | ||
187 | fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> { | 299 | fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> { |
@@ -359,22 +471,20 @@ fn highlight_name_by_syntax(name: ast::Name) -> Highlight { | |||
359 | } | 471 | } |
360 | 472 | ||
361 | fn highlight_injection( | 473 | fn highlight_injection( |
362 | acc: &mut Vec<HighlightedRange>, | 474 | acc: &mut HighlightedRangeStack, |
363 | sema: &Semantics<RootDatabase>, | 475 | sema: &Semantics<RootDatabase>, |
364 | literal: ast::RawString, | 476 | literal: ast::RawString, |
365 | expanded: SyntaxToken, | 477 | expanded: SyntaxToken, |
366 | ) -> Option<()> { | 478 | ) -> Option<()> { |
367 | let call_info = call_info_for_token(&sema, expanded)?; | 479 | let active_parameter = ActiveParameter::at_token(&sema, expanded)?; |
368 | let idx = call_info.active_parameter?; | 480 | if !active_parameter.name.starts_with("ra_fixture") { |
369 | let name = call_info.signature.parameter_names.get(idx)?; | ||
370 | if !name.starts_with("ra_fixture") { | ||
371 | return None; | 481 | return None; |
372 | } | 482 | } |
373 | let value = literal.value()?; | 483 | let value = literal.value()?; |
374 | let (analysis, tmp_file_id) = Analysis::from_single_file(value); | 484 | let (analysis, tmp_file_id) = Analysis::from_single_file(value); |
375 | 485 | ||
376 | if let Some(range) = literal.open_quote_text_range() { | 486 | if let Some(range) = literal.open_quote_text_range() { |
377 | acc.push(HighlightedRange { | 487 | acc.add(HighlightedRange { |
378 | range, | 488 | range, |
379 | highlight: HighlightTag::StringLiteral.into(), | 489 | highlight: HighlightTag::StringLiteral.into(), |
380 | binding_hash: None, | 490 | binding_hash: None, |
@@ -384,12 +494,12 @@ fn highlight_injection( | |||
384 | for mut h in analysis.highlight(tmp_file_id).unwrap() { | 494 | for mut h in analysis.highlight(tmp_file_id).unwrap() { |
385 | if let Some(r) = literal.map_range_up(h.range) { | 495 | if let Some(r) = literal.map_range_up(h.range) { |
386 | h.range = r; | 496 | h.range = r; |
387 | acc.push(h) | 497 | acc.add(h) |
388 | } | 498 | } |
389 | } | 499 | } |
390 | 500 | ||
391 | if let Some(range) = literal.close_quote_text_range() { | 501 | if let Some(range) = literal.close_quote_text_range() { |
392 | acc.push(HighlightedRange { | 502 | acc.add(HighlightedRange { |
393 | range, | 503 | range, |
394 | highlight: HighlightTag::StringLiteral.into(), | 504 | highlight: HighlightTag::StringLiteral.into(), |
395 | binding_hash: None, | 505 | binding_hash: None, |
diff --git a/crates/ra_ide/src/syntax_highlighting/tests.rs b/crates/ra_ide/src/syntax_highlighting/tests.rs index 73611e23a..a9aae957f 100644 --- a/crates/ra_ide/src/syntax_highlighting/tests.rs +++ b/crates/ra_ide/src/syntax_highlighting/tests.rs | |||
@@ -168,3 +168,73 @@ macro_rules! test {} | |||
168 | ); | 168 | ); |
169 | let _ = analysis.highlight(file_id).unwrap(); | 169 | let _ = analysis.highlight(file_id).unwrap(); |
170 | } | 170 | } |
171 | |||
172 | #[test] | ||
173 | fn test_string_highlighting() { | ||
174 | // The format string detection is based on macro-expansion, | ||
175 | // thus, we have to copy the macro definition from `std` | ||
176 | let (analysis, file_id) = single_file( | ||
177 | r#" | ||
178 | macro_rules! println { | ||
179 | ($($arg:tt)*) => ({ | ||
180 | $crate::io::_print($crate::format_args_nl!($($arg)*)); | ||
181 | }) | ||
182 | } | ||
183 | #[rustc_builtin_macro] | ||
184 | macro_rules! format_args_nl { | ||
185 | ($fmt:expr) => {{ /* compiler built-in */ }}; | ||
186 | ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }}; | ||
187 | } | ||
188 | |||
189 | fn main() { | ||
190 | // from https://doc.rust-lang.org/std/fmt/index.html | ||
191 | println!("Hello"); // => "Hello" | ||
192 | println!("Hello, {}!", "world"); // => "Hello, world!" | ||
193 | println!("The number is {}", 1); // => "The number is 1" | ||
194 | println!("{:?}", (3, 4)); // => "(3, 4)" | ||
195 | println!("{value}", value=4); // => "4" | ||
196 | println!("{} {}", 1, 2); // => "1 2" | ||
197 | println!("{:04}", 42); // => "0042" with leading zerosV | ||
198 | println!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" | ||
199 | println!("{argument}", argument = "test"); // => "test" | ||
200 | println!("{name} {}", 1, name = 2); // => "2 1" | ||
201 | println!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" | ||
202 | println!("Hello {:5}!", "x"); | ||
203 | println!("Hello {:1$}!", "x", 5); | ||
204 | println!("Hello {1:0$}!", 5, "x"); | ||
205 | println!("Hello {:width$}!", "x", width = 5); | ||
206 | println!("Hello {:<5}!", "x"); | ||
207 | println!("Hello {:-<5}!", "x"); | ||
208 | println!("Hello {:^5}!", "x"); | ||
209 | println!("Hello {:>5}!", "x"); | ||
210 | println!("Hello {:+}!", 5); | ||
211 | println!("{:#x}!", 27); | ||
212 | println!("Hello {:05}!", 5); | ||
213 | println!("Hello {:05}!", -5); | ||
214 | println!("{:#010x}!", 27); | ||
215 | println!("Hello {0} is {1:.5}", "x", 0.01); | ||
216 | println!("Hello {1} is {2:.0$}", 5, "x", 0.01); | ||
217 | println!("Hello {0} is {2:.1$}", "x", 5, 0.01); | ||
218 | println!("Hello {} is {:.*}", "x", 5, 0.01); | ||
219 | println!("Hello {} is {2:.*}", "x", 5, 0.01); | ||
220 | println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); | ||
221 | println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); | ||
222 | println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); | ||
223 | println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); | ||
224 | println!("Hello {{}}"); | ||
225 | println!("{{ Hello"); | ||
226 | |||
227 | println!(r"Hello, {}!", "world"); | ||
228 | |||
229 | println!("{\x41}", A = 92); | ||
230 | println!("{ничоси}", ничоси = 92); | ||
231 | }"# | ||
232 | .trim(), | ||
233 | ); | ||
234 | |||
235 | let dst_file = project_dir().join("crates/ra_ide/src/snapshots/highlight_strings.html"); | ||
236 | let actual_html = &analysis.highlight_as_html(file_id, false).unwrap(); | ||
237 | let expected_html = &read_text(&dst_file); | ||
238 | fs::write(dst_file, &actual_html).unwrap(); | ||
239 | assert_eq_text!(expected_html, actual_html); | ||
240 | } | ||
diff --git a/crates/ra_ide_db/src/symbol_index.rs b/crates/ra_ide_db/src/symbol_index.rs index 937abb433..95be11134 100644 --- a/crates/ra_ide_db/src/symbol_index.rs +++ b/crates/ra_ide_db/src/symbol_index.rs | |||
@@ -313,6 +313,7 @@ pub struct FileSymbol { | |||
313 | pub file_id: FileId, | 313 | pub file_id: FileId, |
314 | pub name: SmolStr, | 314 | pub name: SmolStr, |
315 | pub kind: SyntaxKind, | 315 | pub kind: SyntaxKind, |
316 | pub range: TextRange, | ||
316 | pub ptr: SyntaxNodePtr, | 317 | pub ptr: SyntaxNodePtr, |
317 | pub name_range: Option<TextRange>, | 318 | pub name_range: Option<TextRange>, |
318 | pub container_name: Option<SmolStr>, | 319 | pub container_name: Option<SmolStr>, |
@@ -379,6 +380,7 @@ fn to_file_symbol(node: &SyntaxNode, file_id: FileId) -> Option<FileSymbol> { | |||
379 | to_symbol(node).map(move |(name, ptr, name_range)| FileSymbol { | 380 | to_symbol(node).map(move |(name, ptr, name_range)| FileSymbol { |
380 | name, | 381 | name, |
381 | kind: node.kind(), | 382 | kind: node.kind(), |
383 | range: node.text_range(), | ||
382 | ptr, | 384 | ptr, |
383 | file_id, | 385 | file_id, |
384 | name_range: Some(name_range), | 386 | name_range: Some(name_range), |
diff --git a/crates/ra_proc_macro/src/process.rs b/crates/ra_proc_macro/src/process.rs index 673f80a7a..5bcdacb48 100644 --- a/crates/ra_proc_macro/src/process.rs +++ b/crates/ra_proc_macro/src/process.rs | |||
@@ -189,7 +189,7 @@ fn mk_child(path: &Path, args: impl IntoIterator<Item = impl AsRef<OsStr>>) -> i | |||
189 | .args(args) | 189 | .args(args) |
190 | .stdin(Stdio::piped()) | 190 | .stdin(Stdio::piped()) |
191 | .stdout(Stdio::piped()) | 191 | .stdout(Stdio::piped()) |
192 | .stderr(Stdio::null()) | 192 | .stderr(Stdio::inherit()) |
193 | .spawn() | 193 | .spawn() |
194 | } | 194 | } |
195 | 195 | ||
diff --git a/crates/ra_proc_macro_srv/src/cli.rs b/crates/ra_proc_macro_srv/src/cli.rs index 5f1f3ba3c..7282e5b9b 100644 --- a/crates/ra_proc_macro_srv/src/cli.rs +++ b/crates/ra_proc_macro_srv/src/cli.rs | |||
@@ -4,17 +4,8 @@ use crate::{expand_task, list_macros}; | |||
4 | use ra_proc_macro::msg::{self, Message}; | 4 | use ra_proc_macro::msg::{self, Message}; |
5 | use std::io; | 5 | use std::io; |
6 | 6 | ||
7 | pub fn run() { | 7 | pub fn run() -> io::Result<()> { |
8 | loop { | 8 | while let Some(req) = read_request()? { |
9 | let req = match read_request() { | ||
10 | Err(err) => { | ||
11 | eprintln!("Read message error on ra_proc_macro_srv: {}", err); | ||
12 | continue; | ||
13 | } | ||
14 | Ok(None) => continue, | ||
15 | Ok(Some(req)) => req, | ||
16 | }; | ||
17 | |||
18 | let res = match req { | 9 | let res = match req { |
19 | msg::Request::ListMacro(task) => Ok(msg::Response::ListMacro(list_macros(&task))), | 10 | msg::Request::ListMacro(task) => Ok(msg::Response::ListMacro(list_macros(&task))), |
20 | msg::Request::ExpansionMacro(task) => { | 11 | msg::Request::ExpansionMacro(task) => { |
@@ -33,6 +24,8 @@ pub fn run() { | |||
33 | eprintln!("Write message error: {}", err); | 24 | eprintln!("Write message error: {}", err); |
34 | } | 25 | } |
35 | } | 26 | } |
27 | |||
28 | Ok(()) | ||
36 | } | 29 | } |
37 | 30 | ||
38 | fn read_request() -> io::Result<Option<msg::Request>> { | 31 | fn read_request() -> io::Result<Option<msg::Request>> { |
diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index 84008b2e3..0613310f1 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs | |||
@@ -141,6 +141,11 @@ impl CargoWorkspace { | |||
141 | cargo_toml: &Path, | 141 | cargo_toml: &Path, |
142 | cargo_features: &CargoConfig, | 142 | cargo_features: &CargoConfig, |
143 | ) -> Result<CargoWorkspace> { | 143 | ) -> Result<CargoWorkspace> { |
144 | let _ = Command::new(cargo_binary()) | ||
145 | .arg("--version") | ||
146 | .status() | ||
147 | .context("failed to run `cargo --version`, is `cargo` in PATH?")?; | ||
148 | |||
144 | let mut meta = MetadataCommand::new(); | 149 | let mut meta = MetadataCommand::new(); |
145 | meta.manifest_path(cargo_toml); | 150 | meta.manifest_path(cargo_toml); |
146 | if cargo_features.all_features { | 151 | if cargo_features.all_features { |
diff --git a/crates/ra_syntax/src/ast/tokens.rs b/crates/ra_syntax/src/ast/tokens.rs index e8320b57e..aa34b682d 100644 --- a/crates/ra_syntax/src/ast/tokens.rs +++ b/crates/ra_syntax/src/ast/tokens.rs | |||
@@ -172,3 +172,362 @@ impl RawString { | |||
172 | Some(range + contents_range.start()) | 172 | Some(range + contents_range.start()) |
173 | } | 173 | } |
174 | } | 174 | } |
175 | |||
176 | #[derive(Debug)] | ||
177 | pub enum FormatSpecifier { | ||
178 | Open, | ||
179 | Close, | ||
180 | Integer, | ||
181 | Identifier, | ||
182 | Colon, | ||
183 | Fill, | ||
184 | Align, | ||
185 | Sign, | ||
186 | NumberSign, | ||
187 | Zero, | ||
188 | DollarSign, | ||
189 | Dot, | ||
190 | Asterisk, | ||
191 | QuestionMark, | ||
192 | } | ||
193 | |||
194 | pub trait HasFormatSpecifier: AstToken { | ||
195 | fn char_ranges( | ||
196 | &self, | ||
197 | ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>>; | ||
198 | |||
199 | fn lex_format_specifier<F>(&self, mut callback: F) | ||
200 | where | ||
201 | F: FnMut(TextRange, FormatSpecifier), | ||
202 | { | ||
203 | let char_ranges = if let Some(char_ranges) = self.char_ranges() { | ||
204 | char_ranges | ||
205 | } else { | ||
206 | return; | ||
207 | }; | ||
208 | let mut chars = char_ranges.iter().peekable(); | ||
209 | |||
210 | while let Some((range, first_char)) = chars.next() { | ||
211 | match first_char { | ||
212 | Ok('{') => { | ||
213 | // Format specifier, see syntax at https://doc.rust-lang.org/std/fmt/index.html#syntax | ||
214 | if let Some((_, Ok('{'))) = chars.peek() { | ||
215 | // Escaped format specifier, `{{` | ||
216 | chars.next(); | ||
217 | continue; | ||
218 | } | ||
219 | |||
220 | callback(*range, FormatSpecifier::Open); | ||
221 | |||
222 | // check for integer/identifier | ||
223 | match chars | ||
224 | .peek() | ||
225 | .and_then(|next| next.1.as_ref().ok()) | ||
226 | .copied() | ||
227 | .unwrap_or_default() | ||
228 | { | ||
229 | '0'..='9' => { | ||
230 | // integer | ||
231 | read_integer(&mut chars, &mut callback); | ||
232 | } | ||
233 | c if c == '_' || c.is_alphabetic() => { | ||
234 | // identifier | ||
235 | read_identifier(&mut chars, &mut callback); | ||
236 | } | ||
237 | _ => {} | ||
238 | } | ||
239 | |||
240 | if let Some((_, Ok(':'))) = chars.peek() { | ||
241 | skip_char_and_emit(&mut chars, FormatSpecifier::Colon, &mut callback); | ||
242 | |||
243 | // check for fill/align | ||
244 | let mut cloned = chars.clone().take(2); | ||
245 | let first = cloned | ||
246 | .next() | ||
247 | .and_then(|next| next.1.as_ref().ok()) | ||
248 | .copied() | ||
249 | .unwrap_or_default(); | ||
250 | let second = cloned | ||
251 | .next() | ||
252 | .and_then(|next| next.1.as_ref().ok()) | ||
253 | .copied() | ||
254 | .unwrap_or_default(); | ||
255 | match second { | ||
256 | '<' | '^' | '>' => { | ||
257 | // alignment specifier, first char specifies fillment | ||
258 | skip_char_and_emit( | ||
259 | &mut chars, | ||
260 | FormatSpecifier::Fill, | ||
261 | &mut callback, | ||
262 | ); | ||
263 | skip_char_and_emit( | ||
264 | &mut chars, | ||
265 | FormatSpecifier::Align, | ||
266 | &mut callback, | ||
267 | ); | ||
268 | } | ||
269 | _ => match first { | ||
270 | '<' | '^' | '>' => { | ||
271 | skip_char_and_emit( | ||
272 | &mut chars, | ||
273 | FormatSpecifier::Align, | ||
274 | &mut callback, | ||
275 | ); | ||
276 | } | ||
277 | _ => {} | ||
278 | }, | ||
279 | } | ||
280 | |||
281 | // check for sign | ||
282 | match chars | ||
283 | .peek() | ||
284 | .and_then(|next| next.1.as_ref().ok()) | ||
285 | .copied() | ||
286 | .unwrap_or_default() | ||
287 | { | ||
288 | '+' | '-' => { | ||
289 | skip_char_and_emit( | ||
290 | &mut chars, | ||
291 | FormatSpecifier::Sign, | ||
292 | &mut callback, | ||
293 | ); | ||
294 | } | ||
295 | _ => {} | ||
296 | } | ||
297 | |||
298 | // check for `#` | ||
299 | if let Some((_, Ok('#'))) = chars.peek() { | ||
300 | skip_char_and_emit( | ||
301 | &mut chars, | ||
302 | FormatSpecifier::NumberSign, | ||
303 | &mut callback, | ||
304 | ); | ||
305 | } | ||
306 | |||
307 | // check for `0` | ||
308 | let mut cloned = chars.clone().take(2); | ||
309 | let first = cloned.next().and_then(|next| next.1.as_ref().ok()).copied(); | ||
310 | let second = cloned.next().and_then(|next| next.1.as_ref().ok()).copied(); | ||
311 | |||
312 | if first == Some('0') && second != Some('$') { | ||
313 | skip_char_and_emit(&mut chars, FormatSpecifier::Zero, &mut callback); | ||
314 | } | ||
315 | |||
316 | // width | ||
317 | match chars | ||
318 | .peek() | ||
319 | .and_then(|next| next.1.as_ref().ok()) | ||
320 | .copied() | ||
321 | .unwrap_or_default() | ||
322 | { | ||
323 | '0'..='9' => { | ||
324 | read_integer(&mut chars, &mut callback); | ||
325 | if let Some((_, Ok('$'))) = chars.peek() { | ||
326 | skip_char_and_emit( | ||
327 | &mut chars, | ||
328 | FormatSpecifier::DollarSign, | ||
329 | &mut callback, | ||
330 | ); | ||
331 | } | ||
332 | } | ||
333 | c if c == '_' || c.is_alphabetic() => { | ||
334 | read_identifier(&mut chars, &mut callback); | ||
335 | if chars.peek().and_then(|next| next.1.as_ref().ok()).copied() | ||
336 | != Some('$') | ||
337 | { | ||
338 | continue; | ||
339 | } | ||
340 | skip_char_and_emit( | ||
341 | &mut chars, | ||
342 | FormatSpecifier::DollarSign, | ||
343 | &mut callback, | ||
344 | ); | ||
345 | } | ||
346 | _ => {} | ||
347 | } | ||
348 | |||
349 | // precision | ||
350 | if let Some((_, Ok('.'))) = chars.peek() { | ||
351 | skip_char_and_emit(&mut chars, FormatSpecifier::Dot, &mut callback); | ||
352 | |||
353 | match chars | ||
354 | .peek() | ||
355 | .and_then(|next| next.1.as_ref().ok()) | ||
356 | .copied() | ||
357 | .unwrap_or_default() | ||
358 | { | ||
359 | '*' => { | ||
360 | skip_char_and_emit( | ||
361 | &mut chars, | ||
362 | FormatSpecifier::Asterisk, | ||
363 | &mut callback, | ||
364 | ); | ||
365 | } | ||
366 | '0'..='9' => { | ||
367 | read_integer(&mut chars, &mut callback); | ||
368 | if let Some((_, Ok('$'))) = chars.peek() { | ||
369 | skip_char_and_emit( | ||
370 | &mut chars, | ||
371 | FormatSpecifier::DollarSign, | ||
372 | &mut callback, | ||
373 | ); | ||
374 | } | ||
375 | } | ||
376 | c if c == '_' || c.is_alphabetic() => { | ||
377 | read_identifier(&mut chars, &mut callback); | ||
378 | if chars.peek().and_then(|next| next.1.as_ref().ok()).copied() | ||
379 | != Some('$') | ||
380 | { | ||
381 | continue; | ||
382 | } | ||
383 | skip_char_and_emit( | ||
384 | &mut chars, | ||
385 | FormatSpecifier::DollarSign, | ||
386 | &mut callback, | ||
387 | ); | ||
388 | } | ||
389 | _ => { | ||
390 | continue; | ||
391 | } | ||
392 | } | ||
393 | } | ||
394 | |||
395 | // type | ||
396 | match chars | ||
397 | .peek() | ||
398 | .and_then(|next| next.1.as_ref().ok()) | ||
399 | .copied() | ||
400 | .unwrap_or_default() | ||
401 | { | ||
402 | '?' => { | ||
403 | skip_char_and_emit( | ||
404 | &mut chars, | ||
405 | FormatSpecifier::QuestionMark, | ||
406 | &mut callback, | ||
407 | ); | ||
408 | } | ||
409 | c if c == '_' || c.is_alphabetic() => { | ||
410 | read_identifier(&mut chars, &mut callback); | ||
411 | } | ||
412 | _ => {} | ||
413 | } | ||
414 | } | ||
415 | |||
416 | let mut cloned = chars.clone().take(2); | ||
417 | let first = cloned.next().and_then(|next| next.1.as_ref().ok()).copied(); | ||
418 | let second = cloned.next().and_then(|next| next.1.as_ref().ok()).copied(); | ||
419 | if first != Some('}') { | ||
420 | continue; | ||
421 | } | ||
422 | if second == Some('}') { | ||
423 | // Escaped format end specifier, `}}` | ||
424 | continue; | ||
425 | } | ||
426 | skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback); | ||
427 | } | ||
428 | _ => { | ||
429 | while let Some((_, Ok(next_char))) = chars.peek() { | ||
430 | match next_char { | ||
431 | '{' => break, | ||
432 | _ => {} | ||
433 | } | ||
434 | chars.next(); | ||
435 | } | ||
436 | } | ||
437 | }; | ||
438 | } | ||
439 | |||
440 | fn skip_char_and_emit<'a, I, F>( | ||
441 | chars: &mut std::iter::Peekable<I>, | ||
442 | emit: FormatSpecifier, | ||
443 | callback: &mut F, | ||
444 | ) where | ||
445 | I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>, | ||
446 | F: FnMut(TextRange, FormatSpecifier), | ||
447 | { | ||
448 | let (range, _) = chars.next().unwrap(); | ||
449 | callback(*range, emit); | ||
450 | } | ||
451 | |||
452 | fn read_integer<'a, I, F>(chars: &mut std::iter::Peekable<I>, callback: &mut F) | ||
453 | where | ||
454 | I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>, | ||
455 | F: FnMut(TextRange, FormatSpecifier), | ||
456 | { | ||
457 | let (mut range, c) = chars.next().unwrap(); | ||
458 | assert!(c.as_ref().unwrap().is_ascii_digit()); | ||
459 | while let Some((r, Ok(next_char))) = chars.peek() { | ||
460 | if next_char.is_ascii_digit() { | ||
461 | chars.next(); | ||
462 | range = range.extend_to(r); | ||
463 | } else { | ||
464 | break; | ||
465 | } | ||
466 | } | ||
467 | callback(range, FormatSpecifier::Integer); | ||
468 | } | ||
469 | |||
470 | fn read_identifier<'a, I, F>(chars: &mut std::iter::Peekable<I>, callback: &mut F) | ||
471 | where | ||
472 | I: Iterator<Item = &'a (TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>, | ||
473 | F: FnMut(TextRange, FormatSpecifier), | ||
474 | { | ||
475 | let (mut range, c) = chars.next().unwrap(); | ||
476 | assert!(c.as_ref().unwrap().is_alphabetic() || *c.as_ref().unwrap() == '_'); | ||
477 | while let Some((r, Ok(next_char))) = chars.peek() { | ||
478 | if *next_char == '_' || next_char.is_ascii_digit() || next_char.is_alphabetic() { | ||
479 | chars.next(); | ||
480 | range = range.extend_to(r); | ||
481 | } else { | ||
482 | break; | ||
483 | } | ||
484 | } | ||
485 | callback(range, FormatSpecifier::Identifier); | ||
486 | } | ||
487 | } | ||
488 | } | ||
489 | |||
490 | impl HasFormatSpecifier for String { | ||
491 | fn char_ranges( | ||
492 | &self, | ||
493 | ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>> { | ||
494 | let text = self.text().as_str(); | ||
495 | let text = &text[self.text_range_between_quotes()? - self.syntax().text_range().start()]; | ||
496 | let offset = self.text_range_between_quotes()?.start() - self.syntax().text_range().start(); | ||
497 | |||
498 | let mut res = Vec::with_capacity(text.len()); | ||
499 | rustc_lexer::unescape::unescape_str(text, &mut |range, unescaped_char| { | ||
500 | res.push(( | ||
501 | TextRange::from_to( | ||
502 | TextUnit::from_usize(range.start), | ||
503 | TextUnit::from_usize(range.end), | ||
504 | ) + offset, | ||
505 | unescaped_char, | ||
506 | )) | ||
507 | }); | ||
508 | |||
509 | Some(res) | ||
510 | } | ||
511 | } | ||
512 | |||
513 | impl HasFormatSpecifier for RawString { | ||
514 | fn char_ranges( | ||
515 | &self, | ||
516 | ) -> Option<Vec<(TextRange, Result<char, rustc_lexer::unescape::EscapeError>)>> { | ||
517 | let text = self.text().as_str(); | ||
518 | let text = &text[self.text_range_between_quotes()? - self.syntax().text_range().start()]; | ||
519 | let offset = self.text_range_between_quotes()?.start() - self.syntax().text_range().start(); | ||
520 | |||
521 | let mut res = Vec::with_capacity(text.len()); | ||
522 | for (idx, c) in text.char_indices() { | ||
523 | res.push(( | ||
524 | TextRange::from_to( | ||
525 | TextUnit::from_usize(idx), | ||
526 | TextUnit::from_usize(idx + c.len_utf8()), | ||
527 | ) + offset, | ||
528 | Ok(c), | ||
529 | )); | ||
530 | } | ||
531 | Some(res) | ||
532 | } | ||
533 | } | ||
diff --git a/crates/ra_syntax/src/ptr.rs b/crates/ra_syntax/src/ptr.rs index 3be648c2a..ecbfffcf4 100644 --- a/crates/ra_syntax/src/ptr.rs +++ b/crates/ra_syntax/src/ptr.rs | |||
@@ -30,10 +30,6 @@ impl SyntaxNodePtr { | |||
30 | .unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self)) | 30 | .unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self)) |
31 | } | 31 | } |
32 | 32 | ||
33 | pub fn range(&self) -> TextRange { | ||
34 | self.range | ||
35 | } | ||
36 | |||
37 | pub fn cast<N: AstNode>(self) -> Option<AstPtr<N>> { | 33 | pub fn cast<N: AstNode>(self) -> Option<AstPtr<N>> { |
38 | if !N::can_cast(self.kind) { | 34 | if !N::can_cast(self.kind) { |
39 | return None; | 35 | return None; |
diff --git a/crates/rust-analyzer/src/bin/args.rs b/crates/rust-analyzer/src/bin/args.rs index b14409c39..8e3ca9343 100644 --- a/crates/rust-analyzer/src/bin/args.rs +++ b/crates/rust-analyzer/src/bin/args.rs | |||
@@ -75,6 +75,10 @@ impl Args { | |||
75 | let subcommand = match matches.subcommand()? { | 75 | let subcommand = match matches.subcommand()? { |
76 | Some(it) => it, | 76 | Some(it) => it, |
77 | None => { | 77 | None => { |
78 | if matches.contains(["-h", "--help"]) { | ||
79 | print_subcommands(); | ||
80 | return Ok(Err(HelpPrinted)); | ||
81 | } | ||
78 | matches.finish().or_else(handle_extra_flags)?; | 82 | matches.finish().or_else(handle_extra_flags)?; |
79 | return Ok(Ok(Args { verbosity, command: Command::RunServer })); | 83 | return Ok(Ok(Args { verbosity, command: Command::RunServer })); |
80 | } | 84 | } |
@@ -267,8 +271,17 @@ ARGS: | |||
267 | } | 271 | } |
268 | "proc-macro" => Command::ProcMacro, | 272 | "proc-macro" => Command::ProcMacro, |
269 | _ => { | 273 | _ => { |
270 | eprintln!( | 274 | print_subcommands(); |
271 | "\ | 275 | return Ok(Err(HelpPrinted)); |
276 | } | ||
277 | }; | ||
278 | Ok(Ok(Args { verbosity, command })) | ||
279 | } | ||
280 | } | ||
281 | |||
282 | fn print_subcommands() { | ||
283 | eprintln!( | ||
284 | "\ | ||
272 | rust-analyzer | 285 | rust-analyzer |
273 | 286 | ||
274 | USAGE: | 287 | USAGE: |
@@ -285,12 +298,7 @@ SUBCOMMANDS: | |||
285 | proc-macro | 298 | proc-macro |
286 | parse | 299 | parse |
287 | symbols" | 300 | symbols" |
288 | ); | 301 | ) |
289 | return Ok(Err(HelpPrinted)); | ||
290 | } | ||
291 | }; | ||
292 | Ok(Ok(Args { verbosity, command })) | ||
293 | } | ||
294 | } | 302 | } |
295 | 303 | ||
296 | pub(crate) struct HelpPrinted; | 304 | pub(crate) struct HelpPrinted; |
diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index e8d5dad65..22a84b50c 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs | |||
@@ -66,7 +66,7 @@ fn setup_logging() -> Result<()> { | |||
66 | } | 66 | } |
67 | 67 | ||
68 | fn run_proc_macro_srv() -> Result<()> { | 68 | fn run_proc_macro_srv() -> Result<()> { |
69 | ra_proc_macro_srv::cli::run(); | 69 | ra_proc_macro_srv::cli::run()?; |
70 | Ok(()) | 70 | Ok(()) |
71 | } | 71 | } |
72 | 72 | ||
diff --git a/crates/rust-analyzer/src/cargo_target_spec.rs b/crates/rust-analyzer/src/cargo_target_spec.rs index 942c30328..c2ece49f4 100644 --- a/crates/rust-analyzer/src/cargo_target_spec.rs +++ b/crates/rust-analyzer/src/cargo_target_spec.rs | |||
@@ -23,7 +23,7 @@ impl CargoTargetSpec { | |||
23 | let mut args = Vec::new(); | 23 | let mut args = Vec::new(); |
24 | let mut extra_args = Vec::new(); | 24 | let mut extra_args = Vec::new(); |
25 | match kind { | 25 | match kind { |
26 | RunnableKind::Test { test_id } => { | 26 | RunnableKind::Test { test_id, attr } => { |
27 | args.push("test".to_string()); | 27 | args.push("test".to_string()); |
28 | if let Some(spec) = spec { | 28 | if let Some(spec) = spec { |
29 | spec.push_to(&mut args); | 29 | spec.push_to(&mut args); |
@@ -33,6 +33,9 @@ impl CargoTargetSpec { | |||
33 | extra_args.push("--exact".to_string()); | 33 | extra_args.push("--exact".to_string()); |
34 | } | 34 | } |
35 | extra_args.push("--nocapture".to_string()); | 35 | extra_args.push("--nocapture".to_string()); |
36 | if attr.ignore { | ||
37 | extra_args.push("--ignored".to_string()) | ||
38 | } | ||
36 | } | 39 | } |
37 | RunnableKind::TestMod { path } => { | 40 | RunnableKind::TestMod { path } => { |
38 | args.push("test".to_string()); | 41 | args.push("test".to_string()); |
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index d442cbd63..9fa7dad71 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs | |||
@@ -162,9 +162,13 @@ pub fn analysis_stats( | |||
162 | let (_, sm) = db.body_with_source_map(f_id.into()); | 162 | let (_, sm) = db.body_with_source_map(f_id.into()); |
163 | let src = sm.expr_syntax(expr_id); | 163 | let src = sm.expr_syntax(expr_id); |
164 | if let Ok(src) = src { | 164 | if let Ok(src) = src { |
165 | let node = { | ||
166 | let root = db.parse_or_expand(src.file_id).unwrap(); | ||
167 | src.value.to_node(&root) | ||
168 | }; | ||
165 | let original_file = src.file_id.original_file(db); | 169 | let original_file = src.file_id.original_file(db); |
166 | let line_index = host.analysis().file_line_index(original_file).unwrap(); | 170 | let line_index = host.analysis().file_line_index(original_file).unwrap(); |
167 | let text_range = src.value.syntax_node_ptr().range(); | 171 | let text_range = node.syntax().text_range(); |
168 | let (start, end) = ( | 172 | let (start, end) = ( |
169 | line_index.line_col(text_range.start()), | 173 | line_index.line_col(text_range.start()), |
170 | line_index.line_col(text_range.end()), | 174 | line_index.line_col(text_range.end()), |
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 3597a14e3..715eddadb 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs | |||
@@ -7,6 +7,8 @@ | |||
7 | //! configure the server itself, feature flags are passed into analysis, and | 7 | //! configure the server itself, feature flags are passed into analysis, and |
8 | //! tweak things like automatic insertion of `()` in completions. | 8 | //! tweak things like automatic insertion of `()` in completions. |
9 | 9 | ||
10 | use std::{ffi::OsString, path::PathBuf}; | ||
11 | |||
10 | use lsp_types::TextDocumentClientCapabilities; | 12 | use lsp_types::TextDocumentClientCapabilities; |
11 | use ra_flycheck::FlycheckConfig; | 13 | use ra_flycheck::FlycheckConfig; |
12 | use ra_ide::{CompletionConfig, InlayHintsConfig}; | 14 | use ra_ide::{CompletionConfig, InlayHintsConfig}; |
@@ -20,7 +22,7 @@ pub struct Config { | |||
20 | pub with_sysroot: bool, | 22 | pub with_sysroot: bool, |
21 | pub publish_diagnostics: bool, | 23 | pub publish_diagnostics: bool, |
22 | pub lru_capacity: Option<usize>, | 24 | pub lru_capacity: Option<usize>, |
23 | pub proc_macro_srv: Option<(String, Vec<String>)>, | 25 | pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>, |
24 | pub files: FilesConfig, | 26 | pub files: FilesConfig, |
25 | pub notifications: NotificationsConfig, | 27 | pub notifications: NotificationsConfig, |
26 | 28 | ||
@@ -102,6 +104,7 @@ impl Default for Config { | |||
102 | enable_postfix_completions: true, | 104 | enable_postfix_completions: true, |
103 | add_call_parenthesis: true, | 105 | add_call_parenthesis: true, |
104 | add_call_argument_snippets: true, | 106 | add_call_argument_snippets: true, |
107 | ..CompletionConfig::default() | ||
105 | }, | 108 | }, |
106 | call_info_full: true, | 109 | call_info_full: true, |
107 | } | 110 | } |
@@ -118,7 +121,7 @@ impl Config { | |||
118 | self.client_caps = client_caps; | 121 | self.client_caps = client_caps; |
119 | 122 | ||
120 | set(value, "/withSysroot", &mut self.with_sysroot); | 123 | set(value, "/withSysroot", &mut self.with_sysroot); |
121 | set(value, "/featureFlags/lsp.diagnostics", &mut self.publish_diagnostics); | 124 | set(value, "/diagnostics/enable", &mut self.publish_diagnostics); |
122 | set(value, "/lruCapacity", &mut self.lru_capacity); | 125 | set(value, "/lruCapacity", &mut self.lru_capacity); |
123 | self.files.watcher = match get(value, "/files/watcher") { | 126 | self.files.watcher = match get(value, "/files/watcher") { |
124 | Some("client") => FilesWatcher::Client, | 127 | Some("client") => FilesWatcher::Client, |
@@ -132,10 +135,10 @@ impl Config { | |||
132 | set(value, "/cargo/features", &mut self.cargo.features); | 135 | set(value, "/cargo/features", &mut self.cargo.features); |
133 | set(value, "/cargo/loadOutDirsFromCheck", &mut self.cargo.load_out_dirs_from_check); | 136 | set(value, "/cargo/loadOutDirsFromCheck", &mut self.cargo.load_out_dirs_from_check); |
134 | 137 | ||
135 | match get::<bool>(value, "/procMacro/enabled") { | 138 | match get(value, "/procMacro/enable") { |
136 | Some(true) => { | 139 | Some(true) => { |
137 | if let Ok(path) = std::env::current_exe() { | 140 | if let Ok(path) = std::env::current_exe() { |
138 | self.proc_macro_srv = Some((path.to_string_lossy().to_string(), vec!["proc-macro".to_string()])); | 141 | self.proc_macro_srv = Some((path, vec!["proc-macro".into()])); |
139 | } | 142 | } |
140 | } | 143 | } |
141 | _ => self.proc_macro_srv = None, | 144 | _ => self.proc_macro_srv = None, |
@@ -212,5 +215,13 @@ impl Config { | |||
212 | if let Some(value) = caps.folding_range.as_ref().and_then(|it| it.line_folding_only) { | 215 | if let Some(value) = caps.folding_range.as_ref().and_then(|it| it.line_folding_only) { |
213 | self.client_caps.line_folding_only = value | 216 | self.client_caps.line_folding_only = value |
214 | } | 217 | } |
218 | self.completion.allow_snippets(false); | ||
219 | if let Some(completion) = &caps.completion { | ||
220 | if let Some(completion_item) = &completion.completion_item { | ||
221 | if let Some(value) = completion_item.snippet_support { | ||
222 | self.completion.allow_snippets(value); | ||
223 | } | ||
224 | } | ||
225 | } | ||
215 | } | 226 | } |
216 | } | 227 | } |
diff --git a/crates/rust-analyzer/src/conv.rs b/crates/rust-analyzer/src/conv.rs index 8d2360cc8..2285cb1d3 100644 --- a/crates/rust-analyzer/src/conv.rs +++ b/crates/rust-analyzer/src/conv.rs | |||
@@ -100,6 +100,7 @@ impl Conv for CompletionItemKind { | |||
100 | CompletionItemKind::Method => Method, | 100 | CompletionItemKind::Method => Method, |
101 | CompletionItemKind::TypeParam => TypeParameter, | 101 | CompletionItemKind::TypeParam => TypeParameter, |
102 | CompletionItemKind::Macro => Method, | 102 | CompletionItemKind::Macro => Method, |
103 | CompletionItemKind::Attribute => EnumMember, | ||
103 | } | 104 | } |
104 | } | 105 | } |
105 | } | 106 | } |
@@ -125,7 +126,7 @@ impl ConvWith<(&LineIndex, LineEndings)> for CompletionItem { | |||
125 | for atom_edit in self.text_edit().as_atoms() { | 126 | for atom_edit in self.text_edit().as_atoms() { |
126 | if self.source_range().is_subrange(&atom_edit.delete) { | 127 | if self.source_range().is_subrange(&atom_edit.delete) { |
127 | text_edit = Some(if atom_edit.delete == self.source_range() { | 128 | text_edit = Some(if atom_edit.delete == self.source_range() { |
128 | atom_edit.conv_with(ctx) | 129 | atom_edit.conv_with((ctx.0, ctx.1)) |
129 | } else { | 130 | } else { |
130 | assert!(self.source_range().end() == atom_edit.delete.end()); | 131 | assert!(self.source_range().end() == atom_edit.delete.end()); |
131 | let range1 = | 132 | let range1 = |
@@ -133,12 +134,12 @@ impl ConvWith<(&LineIndex, LineEndings)> for CompletionItem { | |||
133 | let range2 = self.source_range(); | 134 | let range2 = self.source_range(); |
134 | let edit1 = AtomTextEdit::replace(range1, String::new()); | 135 | let edit1 = AtomTextEdit::replace(range1, String::new()); |
135 | let edit2 = AtomTextEdit::replace(range2, atom_edit.insert.clone()); | 136 | let edit2 = AtomTextEdit::replace(range2, atom_edit.insert.clone()); |
136 | additional_text_edits.push(edit1.conv_with(ctx)); | 137 | additional_text_edits.push(edit1.conv_with((ctx.0, ctx.1))); |
137 | edit2.conv_with(ctx) | 138 | edit2.conv_with((ctx.0, ctx.1)) |
138 | }) | 139 | }) |
139 | } else { | 140 | } else { |
140 | assert!(self.source_range().intersection(&atom_edit.delete).is_none()); | 141 | assert!(self.source_range().intersection(&atom_edit.delete).is_none()); |
141 | additional_text_edits.push(atom_edit.conv_with(ctx)); | 142 | additional_text_edits.push(atom_edit.conv_with((ctx.0, ctx.1))); |
142 | } | 143 | } |
143 | } | 144 | } |
144 | let text_edit = text_edit.unwrap(); | 145 | let text_edit = text_edit.unwrap(); |
@@ -165,6 +166,10 @@ impl ConvWith<(&LineIndex, LineEndings)> for CompletionItem { | |||
165 | ..Default::default() | 166 | ..Default::default() |
166 | }; | 167 | }; |
167 | 168 | ||
169 | if self.score().is_some() { | ||
170 | res.preselect = Some(true) | ||
171 | } | ||
172 | |||
168 | if self.deprecated() { | 173 | if self.deprecated() { |
169 | res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated]) | 174 | res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated]) |
170 | } | 175 | } |
diff --git a/crates/rust-analyzer/src/main_loop/handlers.rs b/crates/rust-analyzer/src/main_loop/handlers.rs index b207f0764..41d9fe344 100644 --- a/crates/rust-analyzer/src/main_loop/handlers.rs +++ b/crates/rust-analyzer/src/main_loop/handlers.rs | |||
@@ -968,7 +968,7 @@ fn to_lsp_runnable( | |||
968 | let (args, extra_args) = CargoTargetSpec::runnable_args(spec, &runnable.kind)?; | 968 | let (args, extra_args) = CargoTargetSpec::runnable_args(spec, &runnable.kind)?; |
969 | let line_index = world.analysis().file_line_index(file_id)?; | 969 | let line_index = world.analysis().file_line_index(file_id)?; |
970 | let label = match &runnable.kind { | 970 | let label = match &runnable.kind { |
971 | RunnableKind::Test { test_id } => format!("test {}", test_id), | 971 | RunnableKind::Test { test_id, .. } => format!("test {}", test_id), |
972 | RunnableKind::TestMod { path } => format!("test-mod {}", path), | 972 | RunnableKind::TestMod { path } => format!("test-mod {}", path), |
973 | RunnableKind::Bench { test_id } => format!("bench {}", test_id), | 973 | RunnableKind::Bench { test_id } => format!("bench {}", test_id), |
974 | RunnableKind::Bin => "run binary".to_string(), | 974 | RunnableKind::Bin => "run binary".to_string(), |
diff --git a/crates/rust-analyzer/src/world.rs b/crates/rust-analyzer/src/world.rs index 8e1744bf9..34941931b 100644 --- a/crates/rust-analyzer/src/world.rs +++ b/crates/rust-analyzer/src/world.rs | |||
@@ -152,8 +152,8 @@ impl WorldState { | |||
152 | Ok(it) => it, | 152 | Ok(it) => it, |
153 | Err(err) => { | 153 | Err(err) => { |
154 | log::error!( | 154 | log::error!( |
155 | "Fail to run ra_proc_macro_srv from path {}, error: {:?}", | 155 | "Failed to run ra_proc_macro_srv from path {}, error: {:?}", |
156 | path, | 156 | path.display(), |
157 | err | 157 | err |
158 | ); | 158 | ); |
159 | ProcMacroClient::dummy() | 159 | ProcMacroClient::dummy() |
diff --git a/crates/rust-analyzer/tests/heavy_tests/main.rs b/crates/rust-analyzer/tests/heavy_tests/main.rs index 1dd2676b6..b31533e5e 100644 --- a/crates/rust-analyzer/tests/heavy_tests/main.rs +++ b/crates/rust-analyzer/tests/heavy_tests/main.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | mod support; | 1 | mod support; |
2 | 2 | ||
3 | use std::{collections::HashMap, time::Instant}; | 3 | use std::{collections::HashMap, path::PathBuf, time::Instant}; |
4 | 4 | ||
5 | use lsp_types::{ | 5 | use lsp_types::{ |
6 | CodeActionContext, DidOpenTextDocumentParams, DocumentFormattingParams, FormattingOptions, | 6 | CodeActionContext, DidOpenTextDocumentParams, DocumentFormattingParams, FormattingOptions, |
@@ -692,15 +692,10 @@ pub fn foo(_input: TokenStream) -> TokenStream { | |||
692 | "###, | 692 | "###, |
693 | ) | 693 | ) |
694 | .with_config(|config| { | 694 | .with_config(|config| { |
695 | // FIXME: Use env!("CARGO_BIN_EXE_ra-analyzer") instead after | 695 | let macro_srv_path = PathBuf::from(env!("CARGO_BIN_EXE_rust-analyzer")); |
696 | // https://github.com/rust-lang/cargo/pull/7697 landed | ||
697 | let macro_srv_path = std::path::Path::new(std::env!("CARGO_MANIFEST_DIR")) | ||
698 | .join("../../target/debug/rust-analyzer") | ||
699 | .to_string_lossy() | ||
700 | .to_string(); | ||
701 | 696 | ||
702 | config.cargo.load_out_dirs_from_check = true; | 697 | config.cargo.load_out_dirs_from_check = true; |
703 | config.proc_macro_srv = Some((macro_srv_path, vec!["proc-macro".to_string()])); | 698 | config.proc_macro_srv = Some((macro_srv_path, vec!["proc-macro".into()])); |
704 | }) | 699 | }) |
705 | .root("foo") | 700 | .root("foo") |
706 | .root("bar") | 701 | .root("bar") |
diff --git a/docs/user/readme.adoc b/docs/user/readme.adoc index 13ab2acc2..ce5704836 100644 --- a/docs/user/readme.adoc +++ b/docs/user/readme.adoc | |||
@@ -177,6 +177,26 @@ let g:LanguageClient_serverCommands = { | |||
177 | \ } | 177 | \ } |
178 | ---- | 178 | ---- |
179 | 179 | ||
180 | ==== YouCompleteMe | ||
181 | |||
182 | 1. Install YouCompleteMe by following the instructions | ||
183 | https://ycm-core.github.io/YouCompleteMe/#rust-semantic-completion[here] | ||
184 | |||
185 | 2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists): | ||
186 | + | ||
187 | [source,vim] | ||
188 | ---- | ||
189 | let g:ycm_language_server = | ||
190 | \ [ | ||
191 | \ { | ||
192 | \ 'name': 'rust', | ||
193 | \ 'cmdline': ['rust-analyzer'], | ||
194 | \ 'filetypes': ['rust'], | ||
195 | \ 'project_root_files': ['Cargo.toml'] | ||
196 | \ } | ||
197 | \ ] | ||
198 | ---- | ||
199 | |||
180 | ==== nvim-lsp | 200 | ==== nvim-lsp |
181 | 201 | ||
182 | NeoVim 0.5 (not yet released) has built-in language server support. | 202 | NeoVim 0.5 (not yet released) has built-in language server support. |
diff --git a/editors/code/package-lock.json b/editors/code/package-lock.json index e11cffd68..55ba5351d 100644 --- a/editors/code/package-lock.json +++ b/editors/code/package-lock.json | |||
@@ -25,25 +25,27 @@ | |||
25 | } | 25 | } |
26 | }, | 26 | }, |
27 | "@rollup/plugin-commonjs": { | 27 | "@rollup/plugin-commonjs": { |
28 | "version": "11.0.2", | 28 | "version": "11.1.0", |
29 | "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.0.2.tgz", | 29 | "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.1.0.tgz", |
30 | "integrity": "sha512-MPYGZr0qdbV5zZj8/2AuomVpnRVXRU5XKXb3HVniwRoRCreGlf5kOE081isNWeiLIi6IYkwTX9zE0/c7V8g81g==", | 30 | "integrity": "sha512-Ycr12N3ZPN96Fw2STurD21jMqzKwL9QuFhms3SD7KKRK7oaXUsBU9Zt0jL/rOPHiPYisI21/rXGO3jr9BnLHUA==", |
31 | "dev": true, | 31 | "dev": true, |
32 | "requires": { | 32 | "requires": { |
33 | "@rollup/pluginutils": "^3.0.0", | 33 | "@rollup/pluginutils": "^3.0.8", |
34 | "commondir": "^1.0.1", | ||
34 | "estree-walker": "^1.0.1", | 35 | "estree-walker": "^1.0.1", |
36 | "glob": "^7.1.2", | ||
35 | "is-reference": "^1.1.2", | 37 | "is-reference": "^1.1.2", |
36 | "magic-string": "^0.25.2", | 38 | "magic-string": "^0.25.2", |
37 | "resolve": "^1.11.0" | 39 | "resolve": "^1.11.0" |
38 | } | 40 | } |
39 | }, | 41 | }, |
40 | "@rollup/plugin-node-resolve": { | 42 | "@rollup/plugin-node-resolve": { |
41 | "version": "7.1.1", | 43 | "version": "7.1.3", |
42 | "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.1.1.tgz", | 44 | "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.1.3.tgz", |
43 | "integrity": "sha512-14ddhD7TnemeHE97a4rLOhobfYvUVcaYuqTnL8Ti7Jxi9V9Jr5LY7Gko4HZ5k4h4vqQM0gBQt6tsp9xXW94WPA==", | 45 | "integrity": "sha512-RxtSL3XmdTAE2byxekYLnx+98kEUOrPHF/KRVjLH+DEIHy6kjIw7YINQzn+NXiH/NTrQLAwYs0GWB+csWygA9Q==", |
44 | "dev": true, | 46 | "dev": true, |
45 | "requires": { | 47 | "requires": { |
46 | "@rollup/pluginutils": "^3.0.6", | 48 | "@rollup/pluginutils": "^3.0.8", |
47 | "@types/resolve": "0.0.8", | 49 | "@types/resolve": "0.0.8", |
48 | "builtin-modules": "^3.1.0", | 50 | "builtin-modules": "^3.1.0", |
49 | "is-module": "^1.0.0", | 51 | "is-module": "^1.0.0", |
@@ -51,12 +53,14 @@ | |||
51 | } | 53 | } |
52 | }, | 54 | }, |
53 | "@rollup/pluginutils": { | 55 | "@rollup/pluginutils": { |
54 | "version": "3.0.8", | 56 | "version": "3.0.9", |
55 | "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.0.8.tgz", | 57 | "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.0.9.tgz", |
56 | "integrity": "sha512-rYGeAc4sxcZ+kPG/Tw4/fwJODC3IXHYDH4qusdN/b6aLw5LPUbzpecYbEJh4sVQGPFJxd2dBU4kc1H3oy9/bnw==", | 58 | "integrity": "sha512-TLZavlfPAZYI7v33wQh4mTP6zojne14yok3DNSLcjoG/Hirxfkonn6icP5rrNWRn8nZsirJBFFpijVOJzkUHDg==", |
57 | "dev": true, | 59 | "dev": true, |
58 | "requires": { | 60 | "requires": { |
59 | "estree-walker": "^1.0.1" | 61 | "@types/estree": "0.0.39", |
62 | "estree-walker": "^1.0.1", | ||
63 | "micromatch": "^4.0.2" | ||
60 | } | 64 | } |
61 | }, | 65 | }, |
62 | "@types/color-name": { | 66 | "@types/color-name": { |
@@ -84,15 +88,15 @@ | |||
84 | "dev": true | 88 | "dev": true |
85 | }, | 89 | }, |
86 | "@types/node": { | 90 | "@types/node": { |
87 | "version": "12.12.34", | 91 | "version": "12.12.37", |
88 | "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.34.tgz", | 92 | "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.37.tgz", |
89 | "integrity": "sha512-BneGN0J9ke24lBRn44hVHNeDlrXRYF+VRp0HbSUNnEZahXGAysHZIqnf/hER6aabdBgzM4YOV4jrR8gj4Zfi0g==", | 93 | "integrity": "sha512-4mXKoDptrXAwZErQHrLzpe0FN/0Wmf5JRniSVIdwUrtDf9wnmEV1teCNLBo/TwuXhkK/bVegoEn/wmb+x0AuPg==", |
90 | "dev": true | 94 | "dev": true |
91 | }, | 95 | }, |
92 | "@types/node-fetch": { | 96 | "@types/node-fetch": { |
93 | "version": "2.5.5", | 97 | "version": "2.5.6", |
94 | "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.5.tgz", | 98 | "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.6.tgz", |
95 | "integrity": "sha512-IWwjsyYjGw+em3xTvWVQi5MgYKbRs0du57klfTaZkv/B24AEQ/p/IopNeqIYNy3EsfHOpg8ieQSDomPcsYMHpA==", | 99 | "integrity": "sha512-2w0NTwMWF1d3NJMK0Uiq2UNN8htVCyOWOD0jIPjPgC5Ph/YP4dVhs9YxxcMcuLuwAslz0dVEcZQUaqkLs3IzOQ==", |
96 | "dev": true, | 100 | "dev": true, |
97 | "requires": { | 101 | "requires": { |
98 | "@types/node": "*", | 102 | "@types/node": "*", |
@@ -115,25 +119,25 @@ | |||
115 | "dev": true | 119 | "dev": true |
116 | }, | 120 | }, |
117 | "@typescript-eslint/eslint-plugin": { | 121 | "@typescript-eslint/eslint-plugin": { |
118 | "version": "2.27.0", | 122 | "version": "2.29.0", |
119 | "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.27.0.tgz", | 123 | "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.29.0.tgz", |
120 | "integrity": "sha512-/my+vVHRN7zYgcp0n4z5A6HAK7bvKGBiswaM5zIlOQczsxj/aiD7RcgD+dvVFuwFaGh5+kM7XA6Q6PN0bvb1tw==", | 124 | "integrity": "sha512-X/YAY7azKirENm4QRpT7OVmzok02cSkqeIcLmdz6gXUQG4Hk0Fi9oBAynSAyNXeGdMRuZvjBa0c1Lu0dn/u6VA==", |
121 | "dev": true, | 125 | "dev": true, |
122 | "requires": { | 126 | "requires": { |
123 | "@typescript-eslint/experimental-utils": "2.27.0", | 127 | "@typescript-eslint/experimental-utils": "2.29.0", |
124 | "functional-red-black-tree": "^1.0.1", | 128 | "functional-red-black-tree": "^1.0.1", |
125 | "regexpp": "^3.0.0", | 129 | "regexpp": "^3.0.0", |
126 | "tsutils": "^3.17.1" | 130 | "tsutils": "^3.17.1" |
127 | } | 131 | } |
128 | }, | 132 | }, |
129 | "@typescript-eslint/experimental-utils": { | 133 | "@typescript-eslint/experimental-utils": { |
130 | "version": "2.27.0", | 134 | "version": "2.29.0", |
131 | "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.27.0.tgz", | 135 | "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.29.0.tgz", |
132 | "integrity": "sha512-vOsYzjwJlY6E0NJRXPTeCGqjv5OHgRU1kzxHKWJVPjDYGbPgLudBXjIlc+OD1hDBZ4l1DLbOc5VjofKahsu9Jw==", | 136 | "integrity": "sha512-H/6VJr6eWYstyqjWXBP2Nn1hQJyvJoFdDtsHxGiD+lEP7piGnGpb/ZQd+z1ZSB1F7dN+WsxUDh8+S4LwI+f3jw==", |
133 | "dev": true, | 137 | "dev": true, |
134 | "requires": { | 138 | "requires": { |
135 | "@types/json-schema": "^7.0.3", | 139 | "@types/json-schema": "^7.0.3", |
136 | "@typescript-eslint/typescript-estree": "2.27.0", | 140 | "@typescript-eslint/typescript-estree": "2.29.0", |
137 | "eslint-scope": "^5.0.0", | 141 | "eslint-scope": "^5.0.0", |
138 | "eslint-utils": "^2.0.0" | 142 | "eslint-utils": "^2.0.0" |
139 | }, | 143 | }, |
@@ -150,21 +154,21 @@ | |||
150 | } | 154 | } |
151 | }, | 155 | }, |
152 | "@typescript-eslint/parser": { | 156 | "@typescript-eslint/parser": { |
153 | "version": "2.27.0", | 157 | "version": "2.29.0", |
154 | "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-2.27.0.tgz", | 158 | "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-2.29.0.tgz", |
155 | "integrity": "sha512-HFUXZY+EdwrJXZo31DW4IS1ujQW3krzlRjBrFRrJcMDh0zCu107/nRfhk/uBasO8m0NVDbBF5WZKcIUMRO7vPg==", | 159 | "integrity": "sha512-H78M+jcu5Tf6m/5N8iiFblUUv+HJDguMSdFfzwa6vSg9lKR8Mk9BsgeSjO8l2EshKnJKcbv0e8IDDOvSNjl0EA==", |
156 | "dev": true, | 160 | "dev": true, |
157 | "requires": { | 161 | "requires": { |
158 | "@types/eslint-visitor-keys": "^1.0.0", | 162 | "@types/eslint-visitor-keys": "^1.0.0", |
159 | "@typescript-eslint/experimental-utils": "2.27.0", | 163 | "@typescript-eslint/experimental-utils": "2.29.0", |
160 | "@typescript-eslint/typescript-estree": "2.27.0", | 164 | "@typescript-eslint/typescript-estree": "2.29.0", |
161 | "eslint-visitor-keys": "^1.1.0" | 165 | "eslint-visitor-keys": "^1.1.0" |
162 | } | 166 | } |
163 | }, | 167 | }, |
164 | "@typescript-eslint/typescript-estree": { | 168 | "@typescript-eslint/typescript-estree": { |
165 | "version": "2.27.0", | 169 | "version": "2.29.0", |
166 | "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.27.0.tgz", | 170 | "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.29.0.tgz", |
167 | "integrity": "sha512-t2miCCJIb/FU8yArjAvxllxbTiyNqaXJag7UOpB5DVoM3+xnjeOngtqlJkLRnMtzaRcJhe3CIR9RmL40omubhg==", | 171 | "integrity": "sha512-3YGbtnWy4az16Egy5Fj5CckkVlpIh0MADtAQza+jiMADRSKkjdpzZp/5WuvwK/Qib3Z0HtzrDFeWanS99dNhnA==", |
168 | "dev": true, | 172 | "dev": true, |
169 | "requires": { | 173 | "requires": { |
170 | "debug": "^4.1.1", | 174 | "debug": "^4.1.1", |
@@ -287,6 +291,15 @@ | |||
287 | "concat-map": "0.0.1" | 291 | "concat-map": "0.0.1" |
288 | } | 292 | } |
289 | }, | 293 | }, |
294 | "braces": { | ||
295 | "version": "3.0.2", | ||
296 | "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", | ||
297 | "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", | ||
298 | "dev": true, | ||
299 | "requires": { | ||
300 | "fill-range": "^7.0.1" | ||
301 | } | ||
302 | }, | ||
290 | "buffer-crc32": { | 303 | "buffer-crc32": { |
291 | "version": "0.2.13", | 304 | "version": "0.2.13", |
292 | "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", | 305 | "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", |
@@ -387,6 +400,12 @@ | |||
387 | "integrity": "sha512-aE2Y4MTFJ870NuB/+2z1cXBhSBBzRydVVjzhFC4gtenEhpnj15yu0qptWGJsO9YGrcPZ3ezX8AWb1VA391MKpQ==", | 400 | "integrity": "sha512-aE2Y4MTFJ870NuB/+2z1cXBhSBBzRydVVjzhFC4gtenEhpnj15yu0qptWGJsO9YGrcPZ3ezX8AWb1VA391MKpQ==", |
388 | "dev": true | 401 | "dev": true |
389 | }, | 402 | }, |
403 | "commondir": { | ||
404 | "version": "1.0.1", | ||
405 | "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", | ||
406 | "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", | ||
407 | "dev": true | ||
408 | }, | ||
390 | "concat-map": { | 409 | "concat-map": { |
391 | "version": "0.0.1", | 410 | "version": "0.0.1", |
392 | "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", | 411 | "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", |
@@ -728,6 +747,15 @@ | |||
728 | "flat-cache": "^2.0.1" | 747 | "flat-cache": "^2.0.1" |
729 | } | 748 | } |
730 | }, | 749 | }, |
750 | "fill-range": { | ||
751 | "version": "7.0.1", | ||
752 | "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", | ||
753 | "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", | ||
754 | "dev": true, | ||
755 | "requires": { | ||
756 | "to-regex-range": "^5.0.1" | ||
757 | } | ||
758 | }, | ||
731 | "flat-cache": { | 759 | "flat-cache": { |
732 | "version": "2.0.1", | 760 | "version": "2.0.1", |
733 | "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", | 761 | "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", |
@@ -763,9 +791,9 @@ | |||
763 | "dev": true | 791 | "dev": true |
764 | }, | 792 | }, |
765 | "fsevents": { | 793 | "fsevents": { |
766 | "version": "2.1.2", | 794 | "version": "2.1.3", |
767 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz", | 795 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", |
768 | "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==", | 796 | "integrity": "sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ==", |
769 | "dev": true, | 797 | "dev": true, |
770 | "optional": true | 798 | "optional": true |
771 | }, | 799 | }, |
@@ -983,6 +1011,12 @@ | |||
983 | "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", | 1011 | "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", |
984 | "dev": true | 1012 | "dev": true |
985 | }, | 1013 | }, |
1014 | "is-number": { | ||
1015 | "version": "7.0.0", | ||
1016 | "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", | ||
1017 | "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", | ||
1018 | "dev": true | ||
1019 | }, | ||
986 | "is-promise": { | 1020 | "is-promise": { |
987 | "version": "2.1.0", | 1021 | "version": "2.1.0", |
988 | "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", | 1022 | "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", |
@@ -1114,6 +1148,16 @@ | |||
1114 | "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=", | 1148 | "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=", |
1115 | "dev": true | 1149 | "dev": true |
1116 | }, | 1150 | }, |
1151 | "micromatch": { | ||
1152 | "version": "4.0.2", | ||
1153 | "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", | ||
1154 | "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", | ||
1155 | "dev": true, | ||
1156 | "requires": { | ||
1157 | "braces": "^3.0.1", | ||
1158 | "picomatch": "^2.0.5" | ||
1159 | } | ||
1160 | }, | ||
1117 | "mime": { | 1161 | "mime": { |
1118 | "version": "1.6.0", | 1162 | "version": "1.6.0", |
1119 | "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", | 1163 | "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", |
@@ -1322,6 +1366,12 @@ | |||
1322 | "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", | 1366 | "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", |
1323 | "dev": true | 1367 | "dev": true |
1324 | }, | 1368 | }, |
1369 | "picomatch": { | ||
1370 | "version": "2.2.2", | ||
1371 | "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", | ||
1372 | "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", | ||
1373 | "dev": true | ||
1374 | }, | ||
1325 | "prelude-ls": { | 1375 | "prelude-ls": { |
1326 | "version": "1.1.2", | 1376 | "version": "1.1.2", |
1327 | "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", | 1377 | "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", |
@@ -1373,9 +1423,9 @@ | |||
1373 | "dev": true | 1423 | "dev": true |
1374 | }, | 1424 | }, |
1375 | "resolve": { | 1425 | "resolve": { |
1376 | "version": "1.15.1", | 1426 | "version": "1.16.1", |
1377 | "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz", | 1427 | "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.16.1.tgz", |
1378 | "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==", | 1428 | "integrity": "sha512-rmAglCSqWWMrrBv/XM6sW0NuRFiKViw/W4d9EbC4pt+49H8JwHy+mcGmALTEg504AUDcLTvb1T2q3E9AnmY+ig==", |
1379 | "dev": true, | 1429 | "dev": true, |
1380 | "requires": { | 1430 | "requires": { |
1381 | "path-parse": "^1.0.6" | 1431 | "path-parse": "^1.0.6" |
@@ -1407,9 +1457,9 @@ | |||
1407 | } | 1457 | } |
1408 | }, | 1458 | }, |
1409 | "rollup": { | 1459 | "rollup": { |
1410 | "version": "2.3.3", | 1460 | "version": "2.7.1", |
1411 | "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.3.3.tgz", | 1461 | "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.7.1.tgz", |
1412 | "integrity": "sha512-uJ9VNWk80mb4wDCSfd1AyHoSc9TrWbkZtnO6wbsMTp9muSWkT26Dvc99MX1yGCOTvUN1Skw/KpFzKdUDuZKTXA==", | 1462 | "integrity": "sha512-c1FCjY8HK1nAq0bTZHaR72ZknpP7p0EjxbcVc6BcmtOosurK//P5jtwxX+f/4fgtbrjczqf0uvR+EdtxpriE8g==", |
1413 | "dev": true, | 1463 | "dev": true, |
1414 | "requires": { | 1464 | "requires": { |
1415 | "fsevents": "~2.1.2" | 1465 | "fsevents": "~2.1.2" |
@@ -1629,6 +1679,15 @@ | |||
1629 | "os-tmpdir": "~1.0.2" | 1679 | "os-tmpdir": "~1.0.2" |
1630 | } | 1680 | } |
1631 | }, | 1681 | }, |
1682 | "to-regex-range": { | ||
1683 | "version": "5.0.1", | ||
1684 | "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", | ||
1685 | "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", | ||
1686 | "dev": true, | ||
1687 | "requires": { | ||
1688 | "is-number": "^7.0.0" | ||
1689 | } | ||
1690 | }, | ||
1632 | "tslib": { | 1691 | "tslib": { |
1633 | "version": "1.11.1", | 1692 | "version": "1.11.1", |
1634 | "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", | 1693 | "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", |
diff --git a/editors/code/package.json b/editors/code/package.json index 79410ad10..b8aaa07d8 100644 --- a/editors/code/package.json +++ b/editors/code/package.json | |||
@@ -37,15 +37,15 @@ | |||
37 | "vscode-languageclient": "7.0.0-next.1" | 37 | "vscode-languageclient": "7.0.0-next.1" |
38 | }, | 38 | }, |
39 | "devDependencies": { | 39 | "devDependencies": { |
40 | "@rollup/plugin-commonjs": "^11.0.2", | 40 | "@rollup/plugin-commonjs": "^11.1.0", |
41 | "@rollup/plugin-node-resolve": "^7.1.1", | 41 | "@rollup/plugin-node-resolve": "^7.1.3", |
42 | "@types/node": "^12.12.34", | 42 | "@types/node": "^12.12.37", |
43 | "@types/node-fetch": "^2.5.5", | 43 | "@types/node-fetch": "^2.5.6", |
44 | "@types/vscode": "^1.44.0", | 44 | "@types/vscode": "^1.44.0", |
45 | "@typescript-eslint/eslint-plugin": "^2.27.0", | 45 | "@typescript-eslint/eslint-plugin": "^2.29.0", |
46 | "@typescript-eslint/parser": "^2.27.0", | 46 | "@typescript-eslint/parser": "^2.29.0", |
47 | "eslint": "^6.8.0", | 47 | "eslint": "^6.8.0", |
48 | "rollup": "^2.3.3", | 48 | "rollup": "^2.7.1", |
49 | "tslib": "^1.11.1", | 49 | "tslib": "^1.11.1", |
50 | "typescript": "^3.8.3", | 50 | "typescript": "^3.8.3", |
51 | "typescript-formatter": "^7.2.2", | 51 | "typescript-formatter": "^7.2.2", |
@@ -166,11 +166,6 @@ | |||
166 | "command": "rust-analyzer.joinLines", | 166 | "command": "rust-analyzer.joinLines", |
167 | "key": "ctrl+shift+j", | 167 | "key": "ctrl+shift+j", |
168 | "when": "editorTextFocus && editorLangId == rust" | 168 | "when": "editorTextFocus && editorLangId == rust" |
169 | }, | ||
170 | { | ||
171 | "command": "rust-analyzer.onEnter", | ||
172 | "key": "enter", | ||
173 | "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust && !vim.active || vim.mode == 'Insert' && editorTextFocus && !suggestWidgetVisible && editorLangId == rust" | ||
174 | } | 169 | } |
175 | ], | 170 | ], |
176 | "configuration": { | 171 | "configuration": { |
@@ -389,7 +384,7 @@ | |||
389 | "type": "boolean", | 384 | "type": "boolean", |
390 | "default": false | 385 | "default": false |
391 | }, | 386 | }, |
392 | "rust-analyzer.procMacro.enabled": { | 387 | "rust-analyzer.procMacro.enable": { |
393 | "description": "Enable Proc macro support, cargo.loadOutDirsFromCheck must be enabled.", | 388 | "description": "Enable Proc macro support, cargo.loadOutDirsFromCheck must be enabled.", |
394 | "type": "boolean", | 389 | "type": "boolean", |
395 | "default": false | 390 | "default": false |
diff --git a/editors/code/ra_syntax_tree.tmGrammar.json b/editors/code/ra_syntax_tree.tmGrammar.json index 0d72a3e36..431d414f6 100644 --- a/editors/code/ra_syntax_tree.tmGrammar.json +++ b/editors/code/ra_syntax_tree.tmGrammar.json | |||
@@ -9,7 +9,7 @@ | |||
9 | ], | 9 | ], |
10 | "repository": { | 10 | "repository": { |
11 | "node_type": { | 11 | "node_type": { |
12 | "match": "^\\s*([A-Z_]+?)@", | 12 | "match": "^\\s*([A-Z_][A-Z_0-9]*?)@", |
13 | "captures": { | 13 | "captures": { |
14 | "1": { | 14 | "1": { |
15 | "name": "entity.name.class" | 15 | "name": "entity.name.class" |
diff --git a/editors/code/src/commands/syntax_tree.ts b/editors/code/src/commands/syntax_tree.ts index b7a397414..cfcf47b2f 100644 --- a/editors/code/src/commands/syntax_tree.ts +++ b/editors/code/src/commands/syntax_tree.ts | |||
@@ -198,7 +198,7 @@ class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, D | |||
198 | return new vscode.Hover(["```rust\n" + rustSourceCode + "\n```"], astFileRange); | 198 | return new vscode.Hover(["```rust\n" + rustSourceCode + "\n```"], astFileRange); |
199 | } | 199 | } |
200 | 200 | ||
201 | private findAstNodeRange(astLine: vscode.TextLine) { | 201 | private findAstNodeRange(astLine: vscode.TextLine): vscode.Range { |
202 | const lineOffset = astLine.range.start; | 202 | const lineOffset = astLine.range.start; |
203 | const begin = lineOffset.translate(undefined, astLine.firstNonWhitespaceCharacterIndex); | 203 | const begin = lineOffset.translate(undefined, astLine.firstNonWhitespaceCharacterIndex); |
204 | const end = lineOffset.translate(undefined, astLine.text.trimEnd().length); | 204 | const end = lineOffset.translate(undefined, astLine.text.trimEnd().length); |
@@ -209,10 +209,43 @@ class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, D | |||
209 | const parsedRange = /\[(\d+); (\d+)\)/.exec(astLine); | 209 | const parsedRange = /\[(\d+); (\d+)\)/.exec(astLine); |
210 | if (!parsedRange) return; | 210 | if (!parsedRange) return; |
211 | 211 | ||
212 | const [begin, end] = parsedRange.slice(1).map(off => doc.positionAt(+off)); | 212 | const [begin, end] = parsedRange |
213 | .slice(1) | ||
214 | .map(off => this.positionAt(doc, +off)); | ||
213 | 215 | ||
214 | return new vscode.Range(begin, end); | 216 | return new vscode.Range(begin, end); |
215 | } | 217 | } |
218 | |||
219 | // Memoize the last value, otherwise the CPU is at 100% single core | ||
220 | // with quadratic lookups when we build rust2Ast cache | ||
221 | cache?: { doc: vscode.TextDocument; offset: number; line: number }; | ||
222 | |||
223 | positionAt(doc: vscode.TextDocument, targetOffset: number): vscode.Position { | ||
224 | if (doc.eol === vscode.EndOfLine.LF) { | ||
225 | return doc.positionAt(targetOffset); | ||
226 | } | ||
227 | |||
228 | // Shitty workaround for crlf line endings | ||
229 | // We are still in this prehistoric era of carriage returns here... | ||
230 | |||
231 | let line = 0; | ||
232 | let offset = 0; | ||
233 | |||
234 | const cache = this.cache; | ||
235 | if (cache?.doc === doc && cache.offset <= targetOffset) { | ||
236 | ({ line, offset } = cache); | ||
237 | } | ||
238 | |||
239 | while (true) { | ||
240 | const lineLenWithLf = doc.lineAt(line).text.length + 1; | ||
241 | if (offset + lineLenWithLf > targetOffset) { | ||
242 | this.cache = { doc, offset, line }; | ||
243 | return doc.positionAt(targetOffset + line); | ||
244 | } | ||
245 | offset += lineLenWithLf; | ||
246 | line += 1; | ||
247 | } | ||
248 | } | ||
216 | } | 249 | } |
217 | 250 | ||
218 | class Lazy<T> { | 251 | class Lazy<T> { |
diff --git a/editors/code/src/tasks.ts b/editors/code/src/tasks.ts index fa1c4a951..1366c76d6 100644 --- a/editors/code/src/tasks.ts +++ b/editors/code/src/tasks.ts | |||
@@ -4,49 +4,80 @@ import * as vscode from 'vscode'; | |||
4 | // our configuration should be compatible with it so use the same key. | 4 | // our configuration should be compatible with it so use the same key. |
5 | const TASK_TYPE = 'cargo'; | 5 | const TASK_TYPE = 'cargo'; |
6 | 6 | ||
7 | export function activateTaskProvider(target: vscode.WorkspaceFolder): vscode.Disposable { | 7 | interface CargoTaskDefinition extends vscode.TaskDefinition { |
8 | const provider: vscode.TaskProvider = { | 8 | command?: string; |
9 | args?: string[]; | ||
10 | cwd?: string; | ||
11 | env?: { [key: string]: string }; | ||
12 | } | ||
13 | |||
14 | class CargoTaskProvider implements vscode.TaskProvider { | ||
15 | private readonly target: vscode.WorkspaceFolder; | ||
16 | |||
17 | constructor(target: vscode.WorkspaceFolder) { | ||
18 | this.target = target; | ||
19 | } | ||
20 | |||
21 | provideTasks(): vscode.Task[] { | ||
9 | // Detect Rust tasks. Currently we do not do any actual detection | 22 | // Detect Rust tasks. Currently we do not do any actual detection |
10 | // of tasks (e.g. aliases in .cargo/config) and just return a fixed | 23 | // of tasks (e.g. aliases in .cargo/config) and just return a fixed |
11 | // set of tasks that always exist. These tasks cannot be removed in | 24 | // set of tasks that always exist. These tasks cannot be removed in |
12 | // tasks.json - only tweaked. | 25 | // tasks.json - only tweaked. |
13 | provideTasks: () => getStandardCargoTasks(target), | ||
14 | 26 | ||
15 | // We don't need to implement this. | 27 | return [ |
16 | resolveTask: () => undefined, | 28 | { command: 'build', group: vscode.TaskGroup.Build }, |
17 | }; | 29 | { command: 'check', group: vscode.TaskGroup.Build }, |
30 | { command: 'test', group: vscode.TaskGroup.Test }, | ||
31 | { command: 'clean', group: vscode.TaskGroup.Clean }, | ||
32 | { command: 'run', group: undefined }, | ||
33 | ] | ||
34 | .map(({ command, group }) => { | ||
35 | const vscodeTask = new vscode.Task( | ||
36 | // The contents of this object end up in the tasks.json entries. | ||
37 | { | ||
38 | type: TASK_TYPE, | ||
39 | command, | ||
40 | }, | ||
41 | // The scope of the task - workspace or specific folder (global | ||
42 | // is not supported). | ||
43 | this.target, | ||
44 | // The task name, and task source. These are shown in the UI as | ||
45 | // `${source}: ${name}`, e.g. `rust: cargo build`. | ||
46 | `cargo ${command}`, | ||
47 | 'rust', | ||
48 | // What to do when this command is executed. | ||
49 | new vscode.ShellExecution('cargo', [command]), | ||
50 | // Problem matchers. | ||
51 | ['$rustc'], | ||
52 | ); | ||
53 | vscodeTask.group = group; | ||
54 | return vscodeTask; | ||
55 | }); | ||
56 | } | ||
18 | 57 | ||
19 | return vscode.tasks.registerTaskProvider(TASK_TYPE, provider); | 58 | resolveTask(task: vscode.Task): vscode.Task | undefined { |
20 | } | 59 | // VSCode calls this for every cargo task in the user's tasks.json, |
60 | // we need to inform VSCode how to execute that command by creating | ||
61 | // a ShellExecution for it. | ||
21 | 62 | ||
22 | function getStandardCargoTasks(target: vscode.WorkspaceFolder): vscode.Task[] { | 63 | const definition = task.definition as CargoTaskDefinition; |
23 | return [ | 64 | |
24 | { command: 'build', group: vscode.TaskGroup.Build }, | 65 | if (definition.type === 'cargo' && definition.command) { |
25 | { command: 'check', group: vscode.TaskGroup.Build }, | 66 | const args = [definition.command].concat(definition.args ?? []); |
26 | { command: 'test', group: vscode.TaskGroup.Test }, | 67 | |
27 | { command: 'clean', group: vscode.TaskGroup.Clean }, | 68 | return new vscode.Task( |
28 | { command: 'run', group: undefined }, | 69 | definition, |
29 | ] | 70 | task.name, |
30 | .map(({ command, group }) => { | ||
31 | const vscodeTask = new vscode.Task( | ||
32 | // The contents of this object end up in the tasks.json entries. | ||
33 | { | ||
34 | type: TASK_TYPE, | ||
35 | command, | ||
36 | }, | ||
37 | // The scope of the task - workspace or specific folder (global | ||
38 | // is not supported). | ||
39 | target, | ||
40 | // The task name, and task source. These are shown in the UI as | ||
41 | // `${source}: ${name}`, e.g. `rust: cargo build`. | ||
42 | `cargo ${command}`, | ||
43 | 'rust', | 71 | 'rust', |
44 | // What to do when this command is executed. | 72 | new vscode.ShellExecution('cargo', args, definition), |
45 | new vscode.ShellExecution('cargo', [command]), | ||
46 | // Problem matchers. | ||
47 | ['$rustc'], | ||
48 | ); | 73 | ); |
49 | vscodeTask.group = group; | 74 | } |
50 | return vscodeTask; | 75 | |
51 | }); | 76 | return undefined; |
77 | } | ||
52 | } | 78 | } |
79 | |||
80 | export function activateTaskProvider(target: vscode.WorkspaceFolder): vscode.Disposable { | ||
81 | const provider = new CargoTaskProvider(target); | ||
82 | return vscode.tasks.registerTaskProvider(TASK_TYPE, provider); | ||
83 | } \ No newline at end of file | ||
diff --git a/xtask/src/install.rs b/xtask/src/install.rs index bc32a04b3..9ba77a3aa 100644 --- a/xtask/src/install.rs +++ b/xtask/src/install.rs | |||
@@ -7,7 +7,7 @@ use anyhow::{bail, format_err, Context, Result}; | |||
7 | use crate::not_bash::{pushd, run}; | 7 | use crate::not_bash::{pushd, run}; |
8 | 8 | ||
9 | // Latest stable, feel free to send a PR if this lags behind. | 9 | // Latest stable, feel free to send a PR if this lags behind. |
10 | const REQUIRED_RUST_VERSION: u32 = 41; | 10 | const REQUIRED_RUST_VERSION: u32 = 43; |
11 | 11 | ||
12 | pub struct InstallCmd { | 12 | pub struct InstallCmd { |
13 | pub client: Option<ClientOpt>, | 13 | pub client: Option<ClientOpt>, |