From f9e2ac56e56cd011929b28d20edda8bed33e9a76 Mon Sep 17 00:00:00 2001 From: Ryo Yoshida Date: Tue, 30 Aug 2022 20:10:59 +0900 Subject: [PATCH 01/42] fix: handle trait methods as inherent methods for trait object types --- crates/hir-ty/src/method_resolution.rs | 22 ++++++++++++++++---- crates/hir-ty/src/tests/method_resolution.rs | 17 +++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index 9a63d5013b..c0ef4b2a9d 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -914,9 +914,6 @@ fn iterate_trait_method_candidates( let db = table.db; let env = table.trait_env.clone(); let self_is_array = matches!(self_ty.kind(Interner), chalk_ir::TyKind::Array(..)); - // if ty is `dyn Trait`, the trait doesn't need to be in scope - let inherent_trait = - self_ty.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t)); let env_traits = matches!(self_ty.kind(Interner), TyKind::Placeholder(_)) // if we have `T: Trait` in the param env, the trait doesn't need to be in scope .then(|| { @@ -925,7 +922,7 @@ fn iterate_trait_method_candidates( }) .into_iter() .flatten(); - let traits = inherent_trait.chain(env_traits).chain(traits_in_scope.iter().copied()); + let traits = env_traits.chain(traits_in_scope.iter().copied()); let canonical_self_ty = table.canonicalize(self_ty.clone()).value; @@ -990,6 +987,23 @@ fn iterate_inherent_methods( VisibleFromModule::None => (None, None), }; + // For trait object types, methods of the trait and its super traits are considered inherent + // methods. This matters because these trait methods have higher priority than the other + // traits' methods, which would be considered in `iterate_trait_method_candidates()` after this + // function. + let inherent_traits = + self_ty.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t)); + for t in inherent_traits { + let data = db.trait_data(t); + for &(_, item) in data.items.iter() { + // We don't pass `visible_from_module` as all trait items should be visible from the + // trait object. + if is_valid_candidate(table, name, receiver_ty, item, self_ty, None) { + callback(receiver_adjustments.clone().unwrap_or_default(), item)?; + } + } + } + if let Some(block_id) = block { if let Some(impls) = db.inherent_impls_in_block(block_id) { impls_for_self_ty( diff --git a/crates/hir-ty/src/tests/method_resolution.rs b/crates/hir-ty/src/tests/method_resolution.rs index 81588a7c4f..fb2fc9369a 100644 --- a/crates/hir-ty/src/tests/method_resolution.rs +++ b/crates/hir-ty/src/tests/method_resolution.rs @@ -1218,6 +1218,23 @@ fn main() { ); } +#[test] +fn dyn_trait_method_priority() { + check_types( + r#" +//- minicore: from +trait Trait { + fn into(&self) -> usize { 0 } +} + +fn foo(a: &dyn Trait) { + let _ = a.into(); + //^usize +} + "#, + ); +} + #[test] fn autoderef_visibility_field() { check( From 484d5b6e70e30e3e2b1714c9dcf641bb47f01b7c Mon Sep 17 00:00:00 2001 From: Ryo Yoshida Date: Wed, 31 Aug 2022 01:00:53 +0900 Subject: [PATCH 02/42] fix: handle trait methods as inherent methods for placeholders --- crates/hir-ty/src/method_resolution.rs | 87 ++++++++++++++------ crates/hir-ty/src/tests/method_resolution.rs | 17 ++++ 2 files changed, 77 insertions(+), 27 deletions(-) diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index c0ef4b2a9d..dbf2750032 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -914,19 +914,10 @@ fn iterate_trait_method_candidates( let db = table.db; let env = table.trait_env.clone(); let self_is_array = matches!(self_ty.kind(Interner), chalk_ir::TyKind::Array(..)); - let env_traits = matches!(self_ty.kind(Interner), TyKind::Placeholder(_)) - // if we have `T: Trait` in the param env, the trait doesn't need to be in scope - .then(|| { - env.traits_in_scope_from_clauses(self_ty.clone()) - .flat_map(|t| all_super_traits(db.upcast(), t)) - }) - .into_iter() - .flatten(); - let traits = env_traits.chain(traits_in_scope.iter().copied()); let canonical_self_ty = table.canonicalize(self_ty.clone()).value; - 'traits: for t in traits { + 'traits: for &t in traits_in_scope { let data = db.trait_data(t); // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during @@ -976,6 +967,43 @@ fn iterate_inherent_methods( ) -> ControlFlow<()> { let db = table.db; let env = table.trait_env.clone(); + + // For trait object types and placeholder types with trait bounds, the methods of the trait and + // its super traits are considered inherent methods. This matters because these methods have + // higher priority than the other traits' methods, which would be considered in + // `iterate_trait_method_candidates()` only after this function. + match self_ty.kind(Interner) { + TyKind::Placeholder(_) => { + let env = table.trait_env.clone(); + let traits = env + .traits_in_scope_from_clauses(self_ty.clone()) + .flat_map(|t| all_super_traits(db.upcast(), t)); + iterate_inherent_trait_methods( + self_ty, + table, + name, + receiver_ty, + receiver_adjustments.clone(), + callback, + traits, + )?; + } + TyKind::Dyn(_) => { + let principal_trait = self_ty.dyn_trait().unwrap(); + let traits = all_super_traits(db.upcast(), principal_trait); + iterate_inherent_trait_methods( + self_ty, + table, + name, + receiver_ty, + receiver_adjustments.clone(), + callback, + traits.into_iter(), + )?; + } + _ => {} + } + let def_crates = match def_crates(db, self_ty, env.krate) { Some(k) => k, None => return ControlFlow::Continue(()), @@ -987,23 +1015,6 @@ fn iterate_inherent_methods( VisibleFromModule::None => (None, None), }; - // For trait object types, methods of the trait and its super traits are considered inherent - // methods. This matters because these trait methods have higher priority than the other - // traits' methods, which would be considered in `iterate_trait_method_candidates()` after this - // function. - let inherent_traits = - self_ty.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t)); - for t in inherent_traits { - let data = db.trait_data(t); - for &(_, item) in data.items.iter() { - // We don't pass `visible_from_module` as all trait items should be visible from the - // trait object. - if is_valid_candidate(table, name, receiver_ty, item, self_ty, None) { - callback(receiver_adjustments.clone().unwrap_or_default(), item)?; - } - } - } - if let Some(block_id) = block { if let Some(impls) = db.inherent_impls_in_block(block_id) { impls_for_self_ty( @@ -1034,6 +1045,28 @@ fn iterate_inherent_methods( } return ControlFlow::Continue(()); + fn iterate_inherent_trait_methods( + self_ty: &Ty, + table: &mut InferenceTable<'_>, + name: Option<&Name>, + receiver_ty: Option<&Ty>, + receiver_adjustments: Option, + callback: &mut dyn FnMut(ReceiverAdjustments, AssocItemId) -> ControlFlow<()>, + traits: impl Iterator, + ) -> ControlFlow<()> { + let db = table.db; + for t in traits { + let data = db.trait_data(t); + for &(_, item) in data.items.iter() { + // We don't pass `visible_from_module` as all trait items should be visible. + if is_valid_candidate(table, name, receiver_ty, item, self_ty, None) { + callback(receiver_adjustments.clone().unwrap_or_default(), item)?; + } + } + } + ControlFlow::Continue(()) + } + fn impls_for_self_ty( impls: &InherentImpls, self_ty: &Ty, diff --git a/crates/hir-ty/src/tests/method_resolution.rs b/crates/hir-ty/src/tests/method_resolution.rs index fb2fc9369a..ac8edb841a 100644 --- a/crates/hir-ty/src/tests/method_resolution.rs +++ b/crates/hir-ty/src/tests/method_resolution.rs @@ -1235,6 +1235,23 @@ fn foo(a: &dyn Trait) { ); } +#[test] +fn trait_method_priority_for_placeholder_type() { + check_types( + r#" +//- minicore: from +trait Trait { + fn into(&self) -> usize { 0 } +} + +fn foo(a: &T) { + let _ = a.into(); + //^usize +} + "#, + ); +} + #[test] fn autoderef_visibility_field() { check( From 29729abc3c9736ca70bc0828e36e6670fb36b5bc Mon Sep 17 00:00:00 2001 From: Stanislav Date: Sun, 4 Sep 2022 19:10:04 +0300 Subject: [PATCH 03/42] Retain imports on find-all-references --- crates/ide/src/references.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 99614b645e..fad44930fe 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -79,6 +79,8 @@ pub(crate) fn find_all_refs( retain_adt_literal_usages(&mut usages, def, sema); } + retain_import_usages(&mut usages, sema); + let references = usages .into_iter() .map(|(file_id, refs)| { @@ -112,6 +114,32 @@ pub(crate) fn find_all_refs( } } +fn retain_import_usages(usages: &mut UsageSearchResult, sema: &Semantics<'_, RootDatabase>) { + for (file_id, refs) in &mut usages.references { + refs.retain(|x| { + let file_sema = sema.parse(file_id.clone()).syntax().clone(); + + let maybe_node = file_sema.child_or_token_at_range(x.range.clone()); + + if let Some(node) = maybe_node { + let res = match node { + syntax::NodeOrToken::Node(x) => { + if matches!(x.kind(), USE) { + false + } else { + true + } + } + syntax::NodeOrToken::Token(_) => true, + }; + res + } else { + true + } + }); + } +} + pub(crate) fn find_defs<'a>( sema: &'a Semantics<'_, RootDatabase>, syntax: &SyntaxNode, From ba40aa72ac1e2d5ddd1f0732e27a84b87692ccae Mon Sep 17 00:00:00 2001 From: Stanislav Date: Sun, 4 Sep 2022 19:41:06 +0300 Subject: [PATCH 04/42] Update crates/ide/src/references.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Laurențiu Nicola --- crates/ide/src/references.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index fad44930fe..021596618d 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -123,7 +123,7 @@ fn retain_import_usages(usages: &mut UsageSearchResult, sema: &Semantics<'_, Roo if let Some(node) = maybe_node { let res = match node { - syntax::NodeOrToken::Node(x) => { + syntax::NodeOrToken::Node(x) => !matches!(x.kind(), USE), if matches!(x.kind(), USE) { false } else { From 6001e7dfb191f68332e2daf2eec692bbc2ae244f Mon Sep 17 00:00:00 2001 From: Stanislav Date: Sun, 4 Sep 2022 19:45:50 +0300 Subject: [PATCH 05/42] fix --- crates/ide/src/references.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 021596618d..53a7a3a217 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -124,12 +124,6 @@ fn retain_import_usages(usages: &mut UsageSearchResult, sema: &Semantics<'_, Roo if let Some(node) = maybe_node { let res = match node { syntax::NodeOrToken::Node(x) => !matches!(x.kind(), USE), - if matches!(x.kind(), USE) { - false - } else { - true - } - } syntax::NodeOrToken::Token(_) => true, }; res From bd0eeb3f041cc57dad3ac40ed6cfcc08f1055638 Mon Sep 17 00:00:00 2001 From: Stanislav Date: Wed, 7 Sep 2022 03:01:06 +0300 Subject: [PATCH 06/42] Update crates/ide/src/references.rs Co-authored-by: Lukas Wirth --- crates/ide/src/references.rs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 53a7a3a217..d4c431f75f 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -116,19 +116,10 @@ pub(crate) fn find_all_refs( fn retain_import_usages(usages: &mut UsageSearchResult, sema: &Semantics<'_, RootDatabase>) { for (file_id, refs) in &mut usages.references { - refs.retain(|x| { - let file_sema = sema.parse(file_id.clone()).syntax().clone(); - - let maybe_node = file_sema.child_or_token_at_range(x.range.clone()); - - if let Some(node) = maybe_node { - let res = match node { - syntax::NodeOrToken::Node(x) => !matches!(x.kind(), USE), - syntax::NodeOrToken::Token(_) => true, - }; - res - } else { - true + refs.retain(|it| { + match if.name.as_name_ref() { + Some(name_ref) => name_ref.syntax().ancestors().any(|it| !matches(it.kind(), USE)), + None => true, } }); } From 92d54f9b304092f20645d8ef0d54d7b724810428 Mon Sep 17 00:00:00 2001 From: Stanislav Date: Wed, 7 Sep 2022 03:23:21 +0300 Subject: [PATCH 07/42] typo and draft --- crates/ide/src/references.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index d4c431f75f..e495bfee55 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -115,12 +115,32 @@ pub(crate) fn find_all_refs( } fn retain_import_usages(usages: &mut UsageSearchResult, sema: &Semantics<'_, RootDatabase>) { - for (file_id, refs) in &mut usages.references { + // todo use this https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs#L432 + + for (_file_id, refs) in &mut usages.references { refs.retain(|it| { - match if.name.as_name_ref() { - Some(name_ref) => name_ref.syntax().ancestors().any(|it| !matches(it.kind(), USE)), + match it.name.as_name_ref() { + Some(name_ref) => name_ref.syntax().ancestors().any(|it_ref| { + dbg!(&it_ref); + !matches!(it_ref.kind(), USE) + }), None => true, } + + // this works: + // let file_sema = sema.parse(file_id.clone()).syntax().clone(); + + // let maybe_node = file_sema.child_or_token_at_range(it.range.clone()); + + // if let Some(node) = maybe_node { + // let res = match node { + // syntax::NodeOrToken::Node(x) => !matches!(x.kind(), USE), + // syntax::NodeOrToken::Token(_) => true, + // }; + // res + // } else { + // true + // } }); } } From eba54c2fc9c15ec6480385486b7f711a7f2ca39e Mon Sep 17 00:00:00 2001 From: Stanislav Date: Wed, 7 Sep 2022 04:09:25 +0300 Subject: [PATCH 08/42] pretty solition works --- crates/ide/src/references.rs | 30 ++++++------------------------ 1 file changed, 6 insertions(+), 24 deletions(-) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index e495bfee55..6c8ae812c9 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -79,7 +79,7 @@ pub(crate) fn find_all_refs( retain_adt_literal_usages(&mut usages, def, sema); } - retain_import_usages(&mut usages, sema); + retain_import_usages(&mut usages); let references = usages .into_iter() @@ -114,33 +114,15 @@ pub(crate) fn find_all_refs( } } -fn retain_import_usages(usages: &mut UsageSearchResult, sema: &Semantics<'_, RootDatabase>) { +fn retain_import_usages(usages: &mut UsageSearchResult) { // todo use this https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs#L432 for (_file_id, refs) in &mut usages.references { - refs.retain(|it| { - match it.name.as_name_ref() { - Some(name_ref) => name_ref.syntax().ancestors().any(|it_ref| { - dbg!(&it_ref); - !matches!(it_ref.kind(), USE) - }), - None => true, + refs.retain(|it| match it.name.as_name_ref() { + Some(name_ref) => { + !name_ref.syntax().ancestors().any(|it_ref| matches!(it_ref.kind(), USE)) } - - // this works: - // let file_sema = sema.parse(file_id.clone()).syntax().clone(); - - // let maybe_node = file_sema.child_or_token_at_range(it.range.clone()); - - // if let Some(node) = maybe_node { - // let res = match node { - // syntax::NodeOrToken::Node(x) => !matches!(x.kind(), USE), - // syntax::NodeOrToken::Token(_) => true, - // }; - // res - // } else { - // true - // } + None => true, }); } } From 9f6553e1d66130325a61bfc412b4ea8335f8a28a Mon Sep 17 00:00:00 2001 From: Stanislav Date: Thu, 8 Sep 2022 01:53:20 +0300 Subject: [PATCH 09/42] add config for import filtering --- crates/ide/src/annotations.rs | 1 + crates/ide/src/lib.rs | 5 ++++- crates/ide/src/references.rs | 9 ++++++--- crates/rust-analyzer/src/config.rs | 7 +++++++ crates/rust-analyzer/src/handlers.rs | 8 ++++++-- editors/code/package.json | 5 +++++ 6 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index 210c5c7fac..ba4c330bf3 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -158,6 +158,7 @@ pub(crate) fn resolve_annotation(db: &RootDatabase, mut annotation: Annotation) &Semantics::new(db), FilePosition { file_id, offset: annotation.range.start() }, None, + false, ) .map(|result| { result diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index d61d69a090..5ad922ddbc 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -425,8 +425,11 @@ impl Analysis { &self, position: FilePosition, search_scope: Option, + exclude_imports: bool, ) -> Cancellable>> { - self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope)) + self.with_db(|db| { + references::find_all_refs(&Semantics::new(db), position, search_scope, exclude_imports) + }) } /// Finds all methods and free functions for the file. Does not return tests! diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 6c8ae812c9..73d118d8bb 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -54,6 +54,7 @@ pub(crate) fn find_all_refs( sema: &Semantics<'_, RootDatabase>, position: FilePosition, search_scope: Option, + exclude_imports: bool, ) -> Option> { let _p = profile::span("find_all_refs"); let syntax = sema.parse(position.file_id).syntax().clone(); @@ -79,7 +80,9 @@ pub(crate) fn find_all_refs( retain_adt_literal_usages(&mut usages, def, sema); } - retain_import_usages(&mut usages); + if exclude_imports { + filter_import_references(&mut usages); + } let references = usages .into_iter() @@ -114,7 +117,7 @@ pub(crate) fn find_all_refs( } } -fn retain_import_usages(usages: &mut UsageSearchResult) { +fn filter_import_references(usages: &mut UsageSearchResult) { // todo use this https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs#L432 for (_file_id, refs) in &mut usages.references { @@ -1109,7 +1112,7 @@ impl Foo { fn check_with_scope(ra_fixture: &str, search_scope: Option, expect: Expect) { let (analysis, pos) = fixture::position(ra_fixture); - let refs = analysis.find_all_refs(pos, search_scope).unwrap().unwrap(); + let refs = analysis.find_all_refs(pos, search_scope, false).unwrap().unwrap(); let mut actual = String::new(); for refs in refs { diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 54dcb42d99..2fdede40dd 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -220,6 +220,9 @@ config_data! { /// Controls file watching implementation. files_watcher: FilesWatcherDef = "\"client\"", + /// Exclude imports in "Find All References" + findAllRefs_excludeImports: bool = "false", + /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. highlightRelated_breakPoints_enable: bool = "true", /// Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`). @@ -1147,6 +1150,10 @@ impl Config { } } + pub fn find_all_refs_exclude_imports(&self) -> bool { + self.data.findAllRefs_excludeImports + } + pub fn snippet_cap(&self) -> bool { self.experimental("snippetTextEdit") } diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index d9b669afbe..70dc37e0c6 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs @@ -1012,7 +1012,9 @@ pub(crate) fn handle_references( let _p = profile::span("handle_references"); let position = from_proto::file_position(&snap, params.text_document_position)?; - let refs = match snap.analysis.find_all_refs(position, None)? { + let exclude_imports = snap.config.find_all_refs_exclude_imports(); + + let refs = match snap.analysis.find_all_refs(position, None, exclude_imports)? { None => return Ok(None), Some(refs) => refs, }; @@ -1652,7 +1654,9 @@ fn show_ref_command_link( position: &FilePosition, ) -> Option { if snap.config.hover_actions().references && snap.config.client_commands().show_reference { - if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) { + if let Some(ref_search_res) = + snap.analysis.find_all_refs(*position, None, false).unwrap_or(None) + { let uri = to_proto::url(snap, position.file_id); let line_index = snap.file_line_index(position.file_id).ok()?; let position = to_proto::position(&line_index, position.offset); diff --git a/editors/code/package.json b/editors/code/package.json index 767c5875bf..3af18dacd4 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -839,6 +839,11 @@ "type": "integer", "minimum": 0 }, + "rust-analyzer.findAllRefs.excludeImports": { + "markdownDescription": "Exclude imports from Find All References results", + "default": false, + "type": "boolean" + }, "rust-analyzer.inlayHints.closureReturnTypeHints.enable": { "markdownDescription": "Whether to show inlay type hints for return types of closures.", "default": "never", From 1764c425186142e4078e4dc1774321871f6f2eee Mon Sep 17 00:00:00 2001 From: Stanislav Date: Thu, 8 Sep 2022 22:36:36 +0300 Subject: [PATCH 10/42] fix comment --- crates/rust-analyzer/src/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 2fdede40dd..48a20189cc 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -220,7 +220,7 @@ config_data! { /// Controls file watching implementation. files_watcher: FilesWatcherDef = "\"client\"", - /// Exclude imports in "Find All References" + /// Exclude imports in `Find All References` findAllRefs_excludeImports: bool = "false", /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. From 0240294759379bc6807d2f1b87391075c84f6bf3 Mon Sep 17 00:00:00 2001 From: Stanislav Date: Thu, 8 Sep 2022 22:47:39 +0300 Subject: [PATCH 11/42] fix comment round 2 --- crates/rust-analyzer/src/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 48a20189cc..80a4b709e7 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -220,7 +220,7 @@ config_data! { /// Controls file watching implementation. files_watcher: FilesWatcherDef = "\"client\"", - /// Exclude imports in `Find All References` + /// Exclude imports from find-all-references. findAllRefs_excludeImports: bool = "false", /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. From ab0b64b26c95bd0cf60af2c299f35c6860c34431 Mon Sep 17 00:00:00 2001 From: Stanislav Date: Thu, 8 Sep 2022 22:55:04 +0300 Subject: [PATCH 12/42] fix comment round 3 --- docs/user/generated_config.adoc | 5 +++++ editors/code/package.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 72b9257264..517a73edd3 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -260,6 +260,11 @@ also need to add the folders to Code's `files.watcherExclude`. [[rust-analyzer.files.watcher]]rust-analyzer.files.watcher (default: `"client"`):: + -- +Find All References config. +-- +[[rust-analyzer.findAllRefs.excludeImports]]rust-analyzer.findAllRefs.excludeImports (default: `false`):: ++ +-- Controls file watching implementation. -- [[rust-analyzer.highlightRelated.breakPoints.enable]]rust-analyzer.highlightRelated.breakPoints.enable (default: `true`):: diff --git a/editors/code/package.json b/editors/code/package.json index 3af18dacd4..189f20fc0c 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -840,7 +840,7 @@ "minimum": 0 }, "rust-analyzer.findAllRefs.excludeImports": { - "markdownDescription": "Exclude imports from Find All References results", + "markdownDescription": "Exclude imports from find-all-references.", "default": false, "type": "boolean" }, From 773f9b38e39033576201a7901bb4b321871e8cb5 Mon Sep 17 00:00:00 2001 From: Stanislav Date: Fri, 9 Sep 2022 01:19:34 +0300 Subject: [PATCH 13/42] fix. round 4 --- docs/user/generated_config.adoc | 4 ++-- editors/code/package.json | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 517a73edd3..337629e17f 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -260,12 +260,12 @@ also need to add the folders to Code's `files.watcherExclude`. [[rust-analyzer.files.watcher]]rust-analyzer.files.watcher (default: `"client"`):: + -- -Find All References config. +Controls file watching implementation. -- [[rust-analyzer.findAllRefs.excludeImports]]rust-analyzer.findAllRefs.excludeImports (default: `false`):: + -- -Controls file watching implementation. +Exclude imports from find-all-references. -- [[rust-analyzer.highlightRelated.breakPoints.enable]]rust-analyzer.highlightRelated.breakPoints.enable (default: `true`):: + diff --git a/editors/code/package.json b/editors/code/package.json index 189f20fc0c..07e9a08e1b 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -706,6 +706,11 @@ "Use server-side file watching" ] }, + "rust-analyzer.findAllRefs.excludeImports": { + "markdownDescription": "Exclude imports from find-all-references.", + "default": false, + "type": "boolean" + }, "rust-analyzer.highlightRelated.breakPoints.enable": { "markdownDescription": "Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords.", "default": true, @@ -839,11 +844,6 @@ "type": "integer", "minimum": 0 }, - "rust-analyzer.findAllRefs.excludeImports": { - "markdownDescription": "Exclude imports from find-all-references.", - "default": false, - "type": "boolean" - }, "rust-analyzer.inlayHints.closureReturnTypeHints.enable": { "markdownDescription": "Whether to show inlay type hints for return types of closures.", "default": "never", From f7f4792f4f4492e62a9439bdf214acee797e0341 Mon Sep 17 00:00:00 2001 From: Stanislav Date: Fri, 9 Sep 2022 20:58:06 +0300 Subject: [PATCH 14/42] fixes --- crates/ide/src/references.rs | 2 -- crates/rust-analyzer/src/config.rs | 9 ++++----- docs/user/generated_config.adoc | 10 +++++----- editors/code/package.json | 10 +++++----- 4 files changed, 14 insertions(+), 17 deletions(-) diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 73d118d8bb..5b410c454d 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -118,8 +118,6 @@ pub(crate) fn find_all_refs( } fn filter_import_references(usages: &mut UsageSearchResult) { - // todo use this https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs#L432 - for (_file_id, refs) in &mut usages.references { refs.retain(|it| match it.name.as_name_ref() { Some(name_ref) => { diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 80a4b709e7..835eeb144a 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -219,10 +219,6 @@ config_data! { files_excludeDirs: Vec = "[]", /// Controls file watching implementation. files_watcher: FilesWatcherDef = "\"client\"", - - /// Exclude imports from find-all-references. - findAllRefs_excludeImports: bool = "false", - /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. highlightRelated_breakPoints_enable: bool = "true", /// Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`). @@ -362,6 +358,9 @@ config_data! { /// this is rust-analyzer itself, but we override this in tests). procMacro_server: Option = "null", + /// Exclude imports from find-all-references. + references_excludeImports: bool = "false", + /// Command to be executed instead of 'cargo' for runnables. runnables_command: Option = "null", /// Additional arguments to be passed to cargo for runnables such as @@ -1151,7 +1150,7 @@ impl Config { } pub fn find_all_refs_exclude_imports(&self) -> bool { - self.data.findAllRefs_excludeImports + self.data.references_excludeImports } pub fn snippet_cap(&self) -> bool { diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 337629e17f..0e301e5d67 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -262,11 +262,6 @@ also need to add the folders to Code's `files.watcherExclude`. -- Controls file watching implementation. -- -[[rust-analyzer.findAllRefs.excludeImports]]rust-analyzer.findAllRefs.excludeImports (default: `false`):: -+ --- -Exclude imports from find-all-references. --- [[rust-analyzer.highlightRelated.breakPoints.enable]]rust-analyzer.highlightRelated.breakPoints.enable (default: `true`):: + -- @@ -551,6 +546,11 @@ This config takes a map of crate names with the exported proc-macro names to ign Internal config, path to proc-macro server executable (typically, this is rust-analyzer itself, but we override this in tests). -- +[[rust-analyzer.references.excludeImports]]rust-analyzer.references.excludeImports (default: `false`):: ++ +-- +Exclude imports from find-all-references. +-- [[rust-analyzer.runnables.command]]rust-analyzer.runnables.command (default: `null`):: + -- diff --git a/editors/code/package.json b/editors/code/package.json index 07e9a08e1b..9d39c7c296 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -706,11 +706,6 @@ "Use server-side file watching" ] }, - "rust-analyzer.findAllRefs.excludeImports": { - "markdownDescription": "Exclude imports from find-all-references.", - "default": false, - "type": "boolean" - }, "rust-analyzer.highlightRelated.breakPoints.enable": { "markdownDescription": "Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords.", "default": true, @@ -1041,6 +1036,11 @@ "string" ] }, + "rust-analyzer.references.excludeImports": { + "markdownDescription": "Exclude imports from find-all-references.", + "default": false, + "type": "boolean" + }, "rust-analyzer.runnables.command": { "markdownDescription": "Command to be executed instead of 'cargo' for runnables.", "default": null, From 7d19971666d50a0719e9a88f7dc67822ba96f87c Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 9 Sep 2022 20:04:56 +0200 Subject: [PATCH 15/42] Add config to unconditionally prefer core imports over std Fixes https://github.com/rust-lang/rust-analyzer/issues/12979 --- crates/hir-def/src/find_path.rs | 36 +++++++++++++++---- crates/hir-ty/src/display.rs | 1 + crates/hir/src/lib.rs | 18 ++++++++-- crates/ide-assists/src/assist_config.rs | 1 + .../src/handlers/add_missing_match_arms.rs | 17 ++++++--- .../ide-assists/src/handlers/auto_import.rs | 7 ++-- .../src/handlers/convert_into_to_from.rs | 2 +- .../src/handlers/extract_function.rs | 1 + .../extract_struct_from_enum_variant.rs | 1 + .../src/handlers/generate_deref.rs | 6 ++-- .../ide-assists/src/handlers/generate_new.rs | 7 ++-- .../src/handlers/qualify_method_call.rs | 7 ++-- .../ide-assists/src/handlers/qualify_path.rs | 3 +- .../replace_derive_with_manual_impl.rs | 2 +- .../replace_qualified_name_with_use.rs | 1 + crates/ide-assists/src/tests.rs | 1 + crates/ide-completion/src/completions.rs | 4 ++- crates/ide-completion/src/completions/expr.rs | 8 +++-- .../src/completions/flyimport.rs | 14 ++++++-- crates/ide-completion/src/config.rs | 1 + crates/ide-completion/src/lib.rs | 7 +++- crates/ide-completion/src/snippet.rs | 8 +++-- crates/ide-completion/src/tests.rs | 1 + crates/ide-db/src/imports/import_assets.rs | 13 ++++--- crates/ide-db/src/path_transform.rs | 3 +- .../src/handlers/json_is_not_rust.rs | 2 ++ .../src/handlers/missing_fields.rs | 1 + crates/ide-diagnostics/src/lib.rs | 2 ++ crates/ide-ssr/src/matching.rs | 7 ++-- crates/rust-analyzer/src/config.rs | 5 +++ .../src/integrated_benchmarks.rs | 2 ++ docs/user/generated_config.adoc | 5 +++ editors/code/package.json | 5 +++ 33 files changed, 156 insertions(+), 43 deletions(-) diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index 89e961f84f..f46054e8cc 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -16,9 +16,14 @@ use crate::{ /// Find a path that can be used to refer to a certain item. This can depend on /// *from where* you're referring to the item, hence the `from` parameter. -pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option { +pub fn find_path( + db: &dyn DefDatabase, + item: ItemInNs, + from: ModuleId, + prefer_core: bool, +) -> Option { let _p = profile::span("find_path"); - find_path_inner(db, item, from, None) + find_path_inner(db, item, from, None, prefer_core) } pub fn find_path_prefixed( @@ -26,9 +31,10 @@ pub fn find_path_prefixed( item: ItemInNs, from: ModuleId, prefix_kind: PrefixKind, + prefer_core: bool, ) -> Option { let _p = profile::span("find_path_prefixed"); - find_path_inner(db, item, from, Some(prefix_kind)) + find_path_inner(db, item, from, Some(prefix_kind), prefer_core) } const MAX_PATH_LEN: usize = 15; @@ -100,12 +106,22 @@ fn find_path_inner( item: ItemInNs, from: ModuleId, prefixed: Option, + prefer_core: bool, ) -> Option { // FIXME: Do fast path for std/core libs? let mut visited_modules = FxHashSet::default(); let def_map = from.def_map(db); - find_path_inner_(db, &def_map, from, item, MAX_PATH_LEN, prefixed, &mut visited_modules) + find_path_inner_( + db, + &def_map, + from, + item, + MAX_PATH_LEN, + prefixed, + &mut visited_modules, + prefer_core, + ) } fn find_path_inner_( @@ -116,6 +132,7 @@ fn find_path_inner_( max_len: usize, mut prefixed: Option, visited_modules: &mut FxHashSet, + prefer_core: bool, ) -> Option { if max_len == 0 { return None; @@ -191,7 +208,9 @@ fn find_path_inner_( // Recursive case: // - if the item is an enum variant, refer to it via the enum if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() { - if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) { + if let Some(mut path) = + find_path(db, ItemInNs::Types(variant.parent.into()), from, prefer_core) + { let data = db.enum_data(variant.parent); path.push_segment(data.variants[variant.local_id].name.clone()); return Some(path); @@ -202,7 +221,7 @@ fn find_path_inner_( } // - otherwise, look for modules containing (reexporting) it and import it from one of those - let prefer_no_std = db.crate_supports_no_std(crate_root.krate); + let prefer_no_std = prefer_core || db.crate_supports_no_std(crate_root.krate); let mut best_path = None; let mut best_path_len = max_len; @@ -223,6 +242,7 @@ fn find_path_inner_( best_path_len - 1, prefixed, visited_modules, + prefer_core, ) { path.push_segment(name); @@ -253,6 +273,7 @@ fn find_path_inner_( best_path_len - 1, prefixed, visited_modules, + prefer_core, )?; cov_mark::hit!(partially_imported); path.push_segment(info.path.segments.last()?.clone()); @@ -428,7 +449,8 @@ mod tests { .take_types() .unwrap(); - let found_path = find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind); + let found_path = + find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind, false); assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind); } diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs index d2f9c2b8b1..874abdaea8 100644 --- a/crates/hir-ty/src/display.rs +++ b/crates/hir-ty/src/display.rs @@ -533,6 +533,7 @@ impl HirDisplay for Ty { f.db.upcast(), ItemInNs::Types((*def_id).into()), module_id, + false, ) { write!(f, "{}", path)?; } else { diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index e4bb63a864..5fa4c15162 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -582,8 +582,13 @@ impl Module { /// Finds a path that can be used to refer to the given item from within /// this module, if possible. - pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into) -> Option { - hir_def::find_path::find_path(db, item.into().into(), self.into()) + pub fn find_use_path( + self, + db: &dyn DefDatabase, + item: impl Into, + prefer_core: bool, + ) -> Option { + hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_core) } /// Finds a path that can be used to refer to the given item from within @@ -593,8 +598,15 @@ impl Module { db: &dyn DefDatabase, item: impl Into, prefix_kind: PrefixKind, + prefer_core: bool, ) -> Option { - hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind) + hir_def::find_path::find_path_prefixed( + db, + item.into().into(), + self.into(), + prefix_kind, + prefer_core, + ) } } diff --git a/crates/ide-assists/src/assist_config.rs b/crates/ide-assists/src/assist_config.rs index d4d148c774..fe2dfca6d5 100644 --- a/crates/ide-assists/src/assist_config.rs +++ b/crates/ide-assists/src/assist_config.rs @@ -13,4 +13,5 @@ pub struct AssistConfig { pub snippet_cap: Option, pub allowed: Option>, pub insert_use: InsertUseConfig, + pub prefer_core: bool, } diff --git a/crates/ide-assists/src/handlers/add_missing_match_arms.rs b/crates/ide-assists/src/handlers/add_missing_match_arms.rs index 1a7919a5a1..d4e21b778c 100644 --- a/crates/ide-assists/src/handlers/add_missing_match_arms.rs +++ b/crates/ide-assists/src/handlers/add_missing_match_arms.rs @@ -87,7 +87,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) .into_iter() .filter_map(|variant| { Some(( - build_pat(ctx.db(), module, variant)?, + build_pat(ctx.db(), module, variant, ctx.config.prefer_core)?, variant.should_be_hidden(ctx.db(), module.krate()), )) }) @@ -132,8 +132,9 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) let is_hidden = variants .iter() .any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); - let patterns = - variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant)); + let patterns = variants.into_iter().filter_map(|variant| { + build_pat(ctx.db(), module, variant, ctx.config.prefer_core) + }); (ast::Pat::from(make::tuple_pat(patterns)), is_hidden) }) @@ -349,10 +350,16 @@ fn resolve_tuple_of_enum_def( .collect() } -fn build_pat(db: &RootDatabase, module: hir::Module, var: ExtendedVariant) -> Option { +fn build_pat( + db: &RootDatabase, + module: hir::Module, + var: ExtendedVariant, + prefer_core: bool, +) -> Option { match var { ExtendedVariant::Variant(var) => { - let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?); + let path = + mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_core)?); // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though let pat: ast::Pat = match var.source(db)?.value.kind() { diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index 949cf3167a..88a6b8558c 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -89,8 +89,11 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; // ``` pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; - let mut proposed_imports = - import_assets.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind); + let mut proposed_imports = import_assets.search_for_imports( + &ctx.sema, + ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, + ); if proposed_imports.is_empty() { return None; } diff --git a/crates/ide-assists/src/handlers/convert_into_to_from.rs b/crates/ide-assists/src/handlers/convert_into_to_from.rs index 30f6dd41a1..e0c0e9a484 100644 --- a/crates/ide-assists/src/handlers/convert_into_to_from.rs +++ b/crates/ide-assists/src/handlers/convert_into_to_from.rs @@ -50,7 +50,7 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) - _ => return None, }; - mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def)?) + mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_core)?) }; let dest_type = match &ast_trait { diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index 52a55ead3a..749d94d5a9 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -152,6 +152,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op ctx.sema.db, ModuleDef::from(control_flow_enum), ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, ); if let Some(mod_path) = mod_path { diff --git a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs index ddc2052e7a..431f7b3c0f 100644 --- a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs @@ -409,6 +409,7 @@ fn process_references( ctx.sema.db, *enum_module_def, ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, ); if let Some(mut mod_path) = mod_path { mod_path.pop_segment(); diff --git a/crates/ide-assists/src/handlers/generate_deref.rs b/crates/ide-assists/src/handlers/generate_deref.rs index b484635121..cf4ed84281 100644 --- a/crates/ide-assists/src/handlers/generate_deref.rs +++ b/crates/ide-assists/src/handlers/generate_deref.rs @@ -58,7 +58,8 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<( let module = ctx.sema.to_def(&strukt)?.module(ctx.db()); let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?; - let trait_path = module.find_use_path(ctx.db(), ModuleDef::Trait(trait_))?; + let trait_path = + module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?; let field_type = field.ty()?; let field_name = field.name()?; @@ -98,7 +99,8 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<() let module = ctx.sema.to_def(&strukt)?.module(ctx.db()); let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?; - let trait_path = module.find_use_path(ctx.db(), ModuleDef::Trait(trait_))?; + let trait_path = + module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?; let field_type = field.ty()?; let target = field.syntax().text_range(); diff --git a/crates/ide-assists/src/handlers/generate_new.rs b/crates/ide-assists/src/handlers/generate_new.rs index 6c93875e9e..ceb7dac0fe 100644 --- a/crates/ide-assists/src/handlers/generate_new.rs +++ b/crates/ide-assists/src/handlers/generate_new.rs @@ -60,8 +60,11 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?)); - let type_path = current_module - .find_use_path(ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?)?; + let type_path = current_module.find_use_path( + ctx.sema.db, + item_for_path_search(ctx.sema.db, item_in_ns)?, + ctx.config.prefer_core, + )?; let expr = use_trivial_constructor( &ctx.sema.db, diff --git a/crates/ide-assists/src/handlers/qualify_method_call.rs b/crates/ide-assists/src/handlers/qualify_method_call.rs index 121f8b4a13..cb81ebd228 100644 --- a/crates/ide-assists/src/handlers/qualify_method_call.rs +++ b/crates/ide-assists/src/handlers/qualify_method_call.rs @@ -44,8 +44,11 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) -> let current_module = ctx.sema.scope(call.syntax())?.module(); let target_module_def = ModuleDef::from(resolved_call); let item_in_ns = ItemInNs::from(target_module_def); - let receiver_path = current_module - .find_use_path(ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?)?; + let receiver_path = current_module.find_use_path( + ctx.sema.db, + item_for_path_search(ctx.sema.db, item_in_ns)?, + ctx.config.prefer_core, + )?; let qualify_candidate = QualifyCandidate::ImplMethod(ctx.sema.db, call, resolved_call); diff --git a/crates/ide-assists/src/handlers/qualify_path.rs b/crates/ide-assists/src/handlers/qualify_path.rs index 0c2e9da386..232cd39e8b 100644 --- a/crates/ide-assists/src/handlers/qualify_path.rs +++ b/crates/ide-assists/src/handlers/qualify_path.rs @@ -37,7 +37,8 @@ use crate::{ // ``` pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; - let mut proposed_imports = import_assets.search_for_relative_paths(&ctx.sema); + let mut proposed_imports = + import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_core); if proposed_imports.is_empty() { return None; } diff --git a/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs b/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs index d139f78a6f..04a1366327 100644 --- a/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs +++ b/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs @@ -85,7 +85,7 @@ pub(crate) fn replace_derive_with_manual_impl( }) .flat_map(|trait_| { current_module - .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_)) + .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_core) .as_ref() .map(mod_path_to_ast) .zip(Some(trait_)) diff --git a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs index 2419fa11c1..533e1670a0 100644 --- a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs +++ b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs @@ -67,6 +67,7 @@ pub(crate) fn replace_qualified_name_with_use( ctx.sema.db, module, ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, ) }) .flatten(); diff --git a/crates/ide-assists/src/tests.rs b/crates/ide-assists/src/tests.rs index 9cd66c6b3b..4e589dc86a 100644 --- a/crates/ide-assists/src/tests.rs +++ b/crates/ide-assists/src/tests.rs @@ -29,6 +29,7 @@ pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig { group: true, skip_glob_imports: true, }, + prefer_core: false, }; pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) { diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs index 55c3e28392..89a971e544 100644 --- a/crates/ide-completion/src/completions.rs +++ b/crates/ide-completion/src/completions.rs @@ -551,7 +551,9 @@ fn enum_variants_with_paths( } for variant in variants { - if let Some(path) = ctx.module.find_use_path(ctx.db, hir::ModuleDef::from(variant)) { + if let Some(path) = + ctx.module.find_use_path(ctx.db, hir::ModuleDef::from(variant), ctx.config.prefer_core) + { // Variants with trivial paths are already added by the existing completion logic, // so we should avoid adding these twice if path.segments().len() > 1 { diff --git a/crates/ide-completion/src/completions/expr.rs b/crates/ide-completion/src/completions/expr.rs index 588b52cc1e..1ccf33a96b 100644 --- a/crates/ide-completion/src/completions/expr.rs +++ b/crates/ide-completion/src/completions/expr.rs @@ -165,7 +165,11 @@ pub(crate) fn complete_expr_path( hir::Adt::Struct(strukt) => { let path = ctx .module - .find_use_path(ctx.db, hir::ModuleDef::from(strukt)) + .find_use_path( + ctx.db, + hir::ModuleDef::from(strukt), + ctx.config.prefer_core, + ) .filter(|it| it.len() > 1); acc.add_struct_literal(ctx, path_ctx, strukt, path, None); @@ -183,7 +187,7 @@ pub(crate) fn complete_expr_path( hir::Adt::Union(un) => { let path = ctx .module - .find_use_path(ctx.db, hir::ModuleDef::from(un)) + .find_use_path(ctx.db, hir::ModuleDef::from(un), ctx.config.prefer_core) .filter(|it| it.len() > 1); acc.add_union_literal(ctx, un, path, None); diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index f04cc15d7f..528959943b 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -262,7 +262,11 @@ fn import_on_the_fly( acc.add_all( import_assets - .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind) + .search_for_imports( + &ctx.sema, + ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, + ) .into_iter() .filter(ns_filter) .filter(|import| { @@ -306,7 +310,11 @@ fn import_on_the_fly_pat_( acc.add_all( import_assets - .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind) + .search_for_imports( + &ctx.sema, + ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, + ) .into_iter() .filter(ns_filter) .filter(|import| { @@ -344,7 +352,7 @@ fn import_on_the_fly_method( let user_input_lowercased = potential_import_name.to_lowercase(); import_assets - .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind) + .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_core) .into_iter() .filter(|import| { !ctx.is_item_hidden(&import.item_to_import) diff --git a/crates/ide-completion/src/config.rs b/crates/ide-completion/src/config.rs index 80d6af2816..54ebce1eb7 100644 --- a/crates/ide-completion/src/config.rs +++ b/crates/ide-completion/src/config.rs @@ -17,6 +17,7 @@ pub struct CompletionConfig { pub callable: Option, pub snippet_cap: Option, pub insert_use: InsertUseConfig, + pub prefer_core: bool, pub snippets: Vec, } diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs index ae1a440d06..7cefb6bb4a 100644 --- a/crates/ide-completion/src/lib.rs +++ b/crates/ide-completion/src/lib.rs @@ -234,7 +234,12 @@ pub fn resolve_completion_edits( ); let import = items_with_name .filter_map(|candidate| { - current_module.find_use_path_prefixed(db, candidate, config.insert_use.prefix_kind) + current_module.find_use_path_prefixed( + db, + candidate, + config.insert_use.prefix_kind, + config.prefer_core, + ) }) .find(|mod_path| mod_path.to_string() == full_import_path); if let Some(import_path) = import { diff --git a/crates/ide-completion/src/snippet.rs b/crates/ide-completion/src/snippet.rs index dc1039fa62..2dc62bbdc6 100644 --- a/crates/ide-completion/src/snippet.rs +++ b/crates/ide-completion/src/snippet.rs @@ -174,8 +174,12 @@ fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option def.into(), _ => return None, }; - let path = - ctx.module.find_use_path_prefixed(ctx.db, item, ctx.config.insert_use.prefix_kind)?; + let path = ctx.module.find_use_path_prefixed( + ctx.db, + item, + ctx.config.insert_use.prefix_kind, + ctx.config.prefer_core, + )?; Some((path.len() > 1).then(|| LocatedImport::new(path.clone(), item, item, None))) }; let mut res = Vec::with_capacity(requires.len()); diff --git a/crates/ide-completion/src/tests.rs b/crates/ide-completion/src/tests.rs index cf826648dc..d24c914856 100644 --- a/crates/ide-completion/src/tests.rs +++ b/crates/ide-completion/src/tests.rs @@ -66,6 +66,7 @@ pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig { enable_private_editable: false, callable: Some(CallableSnippets::FillArguments), snippet_cap: SnippetCap::new(true), + prefer_core: false, insert_use: InsertUseConfig { granularity: ImportGranularity::Crate, prefix_kind: PrefixKind::Plain, diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs index 26ef86155e..53bc516109 100644 --- a/crates/ide-db/src/imports/import_assets.rs +++ b/crates/ide-db/src/imports/import_assets.rs @@ -212,18 +212,20 @@ impl ImportAssets { &self, sema: &Semantics<'_, RootDatabase>, prefix_kind: PrefixKind, + prefer_core: bool, ) -> Vec { let _p = profile::span("import_assets::search_for_imports"); - self.search_for(sema, Some(prefix_kind)) + self.search_for(sema, Some(prefix_kind), prefer_core) } /// This may return non-absolute paths if a part of the returned path is already imported into scope. pub fn search_for_relative_paths( &self, sema: &Semantics<'_, RootDatabase>, + prefer_core: bool, ) -> Vec { let _p = profile::span("import_assets::search_for_relative_paths"); - self.search_for(sema, None) + self.search_for(sema, None, prefer_core) } pub fn path_fuzzy_name_to_exact(&mut self, case_sensitive: bool) { @@ -242,6 +244,7 @@ impl ImportAssets { &self, sema: &Semantics<'_, RootDatabase>, prefixed: Option, + prefer_core: bool, ) -> Vec { let _p = profile::span("import_assets::search_for"); @@ -252,6 +255,7 @@ impl ImportAssets { item_for_path_search(sema.db, item)?, &self.module_with_candidate, prefixed, + prefer_core, ) }; @@ -564,11 +568,12 @@ fn get_mod_path( item_to_search: ItemInNs, module_with_candidate: &Module, prefixed: Option, + prefer_core: bool, ) -> Option { if let Some(prefix_kind) = prefixed { - module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind) + module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_core) } else { - module_with_candidate.find_use_path(db, item_to_search) + module_with_candidate.find_use_path(db, item_to_search, prefer_core) } } diff --git a/crates/ide-db/src/path_transform.rs b/crates/ide-db/src/path_transform.rs index 40af9e6fe2..12d873b4a0 100644 --- a/crates/ide-db/src/path_transform.rs +++ b/crates/ide-db/src/path_transform.rs @@ -173,6 +173,7 @@ impl<'a> Ctx<'a> { let found_path = self.target_module.find_use_path( self.source_scope.db.upcast(), hir::ModuleDef::Trait(trait_ref), + false, )?; match ast::make::ty_path(mod_path_to_ast(&found_path)) { ast::Type::PathType(path_ty) => Some(path_ty), @@ -209,7 +210,7 @@ impl<'a> Ctx<'a> { } let found_path = - self.target_module.find_use_path(self.source_scope.db.upcast(), def)?; + self.target_module.find_use_path(self.source_scope.db.upcast(), def, false)?; let res = mod_path_to_ast(&found_path).clone_for_update(); if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) { if let Some(segment) = res.segment() { diff --git a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs index a21db5b2ce..06073ca1b2 100644 --- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -137,6 +137,7 @@ pub(crate) fn json_in_items( sema.db, it, config.insert_use.prefix_kind, + config.prefer_core, ) { insert_use( &scope, @@ -152,6 +153,7 @@ pub(crate) fn json_in_items( sema.db, it, config.insert_use.prefix_kind, + config.prefer_core, ) { insert_use( &scope, diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index edb1fc0919..5a81a55d82 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -124,6 +124,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option ExprFillDefaultMode::Default, }, insert_use: self.insert_use_config(), + prefer_core: self.data.imports_prefer_core, } } @@ -1133,6 +1136,7 @@ impl Config { CallableCompletionDef::None => None, }, insert_use: self.insert_use_config(), + prefer_core: self.data.imports_prefer_core, snippet_cap: SnippetCap::new(try_or_def!( self.caps .text_document @@ -1156,6 +1160,7 @@ impl Config { snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")), allowed: None, insert_use: self.insert_use_config(), + prefer_core: self.data.imports_prefer_core, } } diff --git a/crates/rust-analyzer/src/integrated_benchmarks.rs b/crates/rust-analyzer/src/integrated_benchmarks.rs index e49a98685a..5dbb64d7df 100644 --- a/crates/rust-analyzer/src/integrated_benchmarks.rs +++ b/crates/rust-analyzer/src/integrated_benchmarks.rs @@ -145,6 +145,7 @@ fn integrated_completion_benchmark() { skip_glob_imports: true, }, snippets: Vec::new(), + prefer_core: false, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; @@ -182,6 +183,7 @@ fn integrated_completion_benchmark() { skip_glob_imports: true, }, snippets: Vec::new(), + prefer_core: false, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 72b9257264..6757624aea 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -353,6 +353,11 @@ Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-i -- Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. -- +[[rust-analyzer.imports.prefer.core]]rust-analyzer.imports.prefer.core (default: `false`):: ++ +-- +Prefer to use imports of the core crate over the std crate. +-- [[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`):: + -- diff --git a/editors/code/package.json b/editors/code/package.json index 767c5875bf..7e91d989f1 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -803,6 +803,11 @@ "default": true, "type": "boolean" }, + "rust-analyzer.imports.prefer.core": { + "markdownDescription": "Prefer to use imports of the core crate over the std crate.", + "default": false, + "type": "boolean" + }, "rust-analyzer.imports.prefix": { "markdownDescription": "The path structure for newly inserted paths to use.", "default": "plain", From 9c97997af939184d825b54cd25a0d0817a4fc8ac Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Sat, 10 Sep 2022 11:50:55 +0200 Subject: [PATCH 16/42] Remove the toggleInlayHints command from VSCode Inlay hints are no longer something specifc to r-a as it has been upstreamed into the LSP, we don't have a reason to give the config for this feature special treatment in regards to toggling. There are plenty of other options out there in the VSCode marketplace to create toggle commands/hotkeys for configurations in general which I believe we should nudge people towards instead. --- editors/code/package.json | 9 --------- editors/code/src/commands.ts | 24 ------------------------ editors/code/src/main.ts | 1 - 3 files changed, 34 deletions(-) diff --git a/editors/code/package.json b/editors/code/package.json index 767c5875bf..023b450209 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -206,11 +206,6 @@ "title": "Show RA Version", "category": "rust-analyzer" }, - { - "command": "rust-analyzer.toggleInlayHints", - "title": "Toggle inlay hints", - "category": "rust-analyzer" - }, { "command": "rust-analyzer.openDocs", "title": "Open docs under cursor", @@ -1633,10 +1628,6 @@ "command": "rust-analyzer.serverVersion", "when": "inRustProject" }, - { - "command": "rust-analyzer.toggleInlayHints", - "when": "inRustProject" - }, { "command": "rust-analyzer.openDocs", "when": "inRustProject" diff --git a/editors/code/src/commands.ts b/editors/code/src/commands.ts index a21b304bbd..b9ad525e36 100644 --- a/editors/code/src/commands.ts +++ b/editors/code/src/commands.ts @@ -321,30 +321,6 @@ export function serverVersion(ctx: Ctx): Cmd { }; } -export function toggleInlayHints(_ctx: Ctx): Cmd { - return async () => { - const config = vscode.workspace.getConfiguration("editor.inlayHints", { - languageId: "rust", - }); - - const value = config.get("enabled"); - let stringValue; - if (typeof value === "string") { - stringValue = value; - } else { - stringValue = value ? "on" : "off"; - } - const nextValues: Record = { - on: "off", - off: "on", - onUnlessPressed: "offUnlessPressed", - offUnlessPressed: "onUnlessPressed", - }; - const nextValue = nextValues[stringValue] ?? "on"; - await config.update("enabled", nextValue, vscode.ConfigurationTarget.Global); - }; -} - // Opens the virtual file that will show the syntax tree // // The contents of the file come from the `TextDocumentContentProvider` diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts index e9b62e0cc2..41bde4195e 100644 --- a/editors/code/src/main.ts +++ b/editors/code/src/main.ts @@ -180,7 +180,6 @@ async function initCommonContext(context: vscode.ExtensionContext, ctx: Ctx) { ctx.registerCommand("ssr", commands.ssr); ctx.registerCommand("serverVersion", commands.serverVersion); - ctx.registerCommand("toggleInlayHints", commands.toggleInlayHints); // Internal commands which are invoked by the server. ctx.registerCommand("runSingle", commands.runSingle); From 2584d48508a0a8cef8794eccfe30db583948eb96 Mon Sep 17 00:00:00 2001 From: Kartavya Vashishtha Date: Sat, 10 Sep 2022 19:06:50 +0530 Subject: [PATCH 17/42] wip --- .../src/handlers/move_format_string_arg.rs | 209 +++++++++++++++ crates/ide-assists/src/lib.rs | 1 + crates/ide-assists/src/tests/generated.rs | 17 ++ .../src/completions/postfix/format_like.rs | 242 +----------------- crates/ide-db/src/lib.rs | 1 + .../src/syntax_helpers/format_string_exprs.rs | 227 ++++++++++++++++ 6 files changed, 463 insertions(+), 234 deletions(-) create mode 100644 crates/ide-assists/src/handlers/move_format_string_arg.rs create mode 100644 crates/ide-db/src/syntax_helpers/format_string_exprs.rs diff --git a/crates/ide-assists/src/handlers/move_format_string_arg.rs b/crates/ide-assists/src/handlers/move_format_string_arg.rs new file mode 100644 index 0000000000..696fd50b5c --- /dev/null +++ b/crates/ide-assists/src/handlers/move_format_string_arg.rs @@ -0,0 +1,209 @@ +use ide_db::{syntax_helpers::{format_string::is_format_string, format_string_exprs::{parse_format_exprs, Arg}}, assists::{AssistId, AssistKind}}; +use itertools::Itertools; +use syntax::{ast, AstToken, AstNode, NodeOrToken, SyntaxKind::COMMA, TextRange}; + +// Assist: move_format_string_arg +// +// Move an expression out of a format string. +// +// ``` +// fn main() { +// println!("{x + 1}$0"); +// } +// ``` +// -> +// ``` +// fn main() { +// println!("{a}", a$0 = x + 1); +// } +// ``` + +use crate::{AssistContext, /* AssistId, AssistKind, */ Assists}; + +pub(crate) fn move_format_string_arg (acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + let t = ctx.find_token_at_offset::()?; + let tt = t.syntax().parent_ancestors().find_map(ast::TokenTree::cast)?; + + let expanded_t = ast::String::cast(ctx.sema.descend_into_macros_with_kind_preference(t.syntax().clone()))?; + + if !is_format_string(&expanded_t) { + return None; + } + + let target = tt.syntax().text_range(); + let extracted_args = parse_format_exprs(&t).ok()?; + let str_range = t.syntax().text_range(); + + let tokens = + tt.token_trees_and_tokens() + .filter_map(NodeOrToken::into_token) + .collect_vec(); + + acc.add(AssistId("move_format_string_arg", AssistKind::QuickFix), "Extract format args", target, |edit| { + let mut existing_args: Vec = vec![]; + let mut current_arg = String::new(); + + if let [_opening_bracket, format_string, _args_start_comma, tokens @ .., end_bracket] = tokens.as_slice() { + for t in tokens { + if t.kind() == COMMA { + existing_args.push(current_arg.trim().into()); + current_arg.clear(); + } else { + current_arg.push_str(t.text()); + } + } + existing_args.push(current_arg.trim().into()); + + // delete everything after the format string to the end bracket + // we're going to insert the new arguments later + edit.delete(TextRange::new(format_string.text_range().end(), end_bracket.text_range().start())); + } + + let mut existing_args = existing_args.into_iter(); + + // insert cursor at end of format string + edit.insert(str_range.end(), "$0"); + let mut placeholder_idx = 1; + let mut args = String::new(); + + for (text, extracted_args) in extracted_args { + // remove expr from format string + edit.delete(text); + + args.push_str(", "); + + match extracted_args { + Arg::Expr(s) => { + // insert arg + args.push_str(&s); + }, + Arg::Placeholder => { + // try matching with existing argument + match existing_args.next() { + Some(ea) => { + args.push_str(&ea); + }, + None => { + // insert placeholder + args.push_str(&format!("${placeholder_idx}")); + placeholder_idx += 1; + } + } + } + } + } + + edit.insert(str_range.end(), args); + }); + + Some(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::check_assist; + + const MACRO_DECL: &'static str = r#" +macro_rules! format_args { + ($lit:literal $(tt:tt)*) => { 0 }, +} +macro_rules! print { + ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*))); +} +"#; + + fn add_macro_decl (s: &'static str) -> String { + MACRO_DECL.to_string() + s + } + + #[test] + fn multiple_middle_arg() { + check_assist( + move_format_string_arg, + &add_macro_decl(r#" +fn main() { + print!("{} {x + 1:b} {}$0", y + 2, 2); +} +"#), + + &add_macro_decl(r#" +fn main() { + print!("{} {:b} {}"$0, y + 2, x + 1, 2); +} +"#), + ); + } + + #[test] + fn single_arg() { + check_assist( + move_format_string_arg, + &add_macro_decl(r#" +fn main() { + print!("{obj.value:b}$0",); +} +"#), + &add_macro_decl(r#" +fn main() { + print!("{:b}"$0, obj.value); +} +"#), + ); + } + + #[test] + fn multiple_middle_placeholders_arg() { + check_assist( + move_format_string_arg, + &add_macro_decl(r#" +fn main() { + print!("{} {x + 1:b} {} {}$0", y + 2, 2); +} +"#), + + &add_macro_decl(r#" +fn main() { + print!("{} {:b} {} {}"$0, y + 2, x + 1, 2, $1); +} +"#), + ); + } + + #[test] + fn multiple_trailing_args() { + check_assist( + move_format_string_arg, + &add_macro_decl(r#" +fn main() { + print!("{} {x + 1:b} {Struct(1, 2)}$0", 1); +} +"#), + + &add_macro_decl(r#" +fn main() { + print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2)); +} +"#), + ); + } + + #[test] + fn improper_commas() { + check_assist( + move_format_string_arg, + &add_macro_decl(r#" +fn main() { + print!("{} {x + 1:b} {Struct(1, 2)}$0", 1,); +} +"#), + + &add_macro_decl(r#" +fn main() { + print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2)); +} +"#), + ); + } + +} diff --git a/crates/ide-assists/src/lib.rs b/crates/ide-assists/src/lib.rs index e52544db5f..f881be9cf6 100644 --- a/crates/ide-assists/src/lib.rs +++ b/crates/ide-assists/src/lib.rs @@ -136,6 +136,7 @@ mod handlers { mod flip_binexpr; mod flip_comma; mod flip_trait_bound; + mod move_format_string_arg; mod generate_constant; mod generate_default_from_enum_variant; mod generate_default_from_new; diff --git a/crates/ide-assists/src/tests/generated.rs b/crates/ide-assists/src/tests/generated.rs index 227e2300f9..fa88abd6c5 100644 --- a/crates/ide-assists/src/tests/generated.rs +++ b/crates/ide-assists/src/tests/generated.rs @@ -1591,6 +1591,23 @@ fn apply(f: F, x: T) -> U where F: FnOnce(T) -> U { ) } +#[test] +fn doctest_move_format_string_arg() { + check_doc_test( + "move_format_string_arg", + r#####" +fn main() { + println!("{x + 1}$0"); +} +"#####, + r#####" +fn main() { + println!("{a}", a$0 = x + 1); +} +"#####, + ) +} + #[test] fn doctest_move_from_mod_rs() { check_doc_test( diff --git a/crates/ide-completion/src/completions/postfix/format_like.rs b/crates/ide-completion/src/completions/postfix/format_like.rs index b273a4cb53..89bfdac74d 100644 --- a/crates/ide-completion/src/completions/postfix/format_like.rs +++ b/crates/ide-completion/src/completions/postfix/format_like.rs @@ -16,7 +16,7 @@ // // image::https://user-images.githubusercontent.com/48062697/113020656-b560f500-917a-11eb-87de-02991f61beb8.gif[] -use ide_db::SnippetCap; +use ide_db::{syntax_helpers::format_string_exprs::{parse_format_exprs, add_placeholders}, SnippetCap}; use syntax::ast::{self, AstToken}; use crate::{ @@ -43,250 +43,24 @@ pub(crate) fn add_format_like_completions( cap: SnippetCap, receiver_text: &ast::String, ) { - let input = match string_literal_contents(receiver_text) { - // It's not a string literal, do not parse input. - Some(input) => input, - None => return, - }; - let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, dot_receiver) { Some(it) => it, None => return, }; - let mut parser = FormatStrParser::new(input); - if parser.parse().is_ok() { + if let Ok((out, exprs)) = parse_format_exprs(receiver_text) { + let exprs = add_placeholders(exprs.map(|e| e.1)).collect_vec(); for (label, macro_name) in KINDS { - let snippet = parser.to_suggestion(macro_name); + let snippet = format!(r#"{}("{}", {})"#, macro_name, out, exprs.join(", ")); postfix_snippet(label, macro_name, &snippet).add_to(acc); } } } -/// Checks whether provided item is a string literal. -fn string_literal_contents(item: &ast::String) -> Option { - let item = item.text(); - if item.len() >= 2 && item.starts_with('\"') && item.ends_with('\"') { - return Some(item[1..item.len() - 1].to_owned()); - } - - None -} - -/// Parser for a format-like string. It is more allowing in terms of string contents, -/// as we expect variable placeholders to be filled with expressions. -#[derive(Debug)] -pub(crate) struct FormatStrParser { - input: String, - output: String, - extracted_expressions: Vec, - state: State, - parsed: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum State { - NotExpr, - MaybeExpr, - Expr, - MaybeIncorrect, - FormatOpts, -} - -impl FormatStrParser { - pub(crate) fn new(input: String) -> Self { - Self { - input, - output: String::new(), - extracted_expressions: Vec::new(), - state: State::NotExpr, - parsed: false, - } - } - - pub(crate) fn parse(&mut self) -> Result<(), ()> { - let mut current_expr = String::new(); - - let mut placeholder_id = 1; - - // Count of open braces inside of an expression. - // We assume that user knows what they're doing, thus we treat it like a correct pattern, e.g. - // "{MyStruct { val_a: 0, val_b: 1 }}". - let mut inexpr_open_count = 0; - - // We need to escape '\' and '$'. See the comments on `get_receiver_text()` for detail. - let mut chars = self.input.chars().peekable(); - while let Some(chr) = chars.next() { - match (self.state, chr) { - (State::NotExpr, '{') => { - self.output.push(chr); - self.state = State::MaybeExpr; - } - (State::NotExpr, '}') => { - self.output.push(chr); - self.state = State::MaybeIncorrect; - } - (State::NotExpr, _) => { - if matches!(chr, '\\' | '$') { - self.output.push('\\'); - } - self.output.push(chr); - } - (State::MaybeIncorrect, '}') => { - // It's okay, we met "}}". - self.output.push(chr); - self.state = State::NotExpr; - } - (State::MaybeIncorrect, _) => { - // Error in the string. - return Err(()); - } - (State::MaybeExpr, '{') => { - self.output.push(chr); - self.state = State::NotExpr; - } - (State::MaybeExpr, '}') => { - // This is an empty sequence '{}'. Replace it with placeholder. - self.output.push(chr); - self.extracted_expressions.push(format!("${}", placeholder_id)); - placeholder_id += 1; - self.state = State::NotExpr; - } - (State::MaybeExpr, _) => { - if matches!(chr, '\\' | '$') { - current_expr.push('\\'); - } - current_expr.push(chr); - self.state = State::Expr; - } - (State::Expr, '}') => { - if inexpr_open_count == 0 { - self.output.push(chr); - self.extracted_expressions.push(current_expr.trim().into()); - current_expr = String::new(); - self.state = State::NotExpr; - } else { - // We're closing one brace met before inside of the expression. - current_expr.push(chr); - inexpr_open_count -= 1; - } - } - (State::Expr, ':') if chars.peek().copied() == Some(':') => { - // path separator - current_expr.push_str("::"); - chars.next(); - } - (State::Expr, ':') => { - if inexpr_open_count == 0 { - // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}" - self.output.push(chr); - self.extracted_expressions.push(current_expr.trim().into()); - current_expr = String::new(); - self.state = State::FormatOpts; - } else { - // We're inside of braced expression, assume that it's a struct field name/value delimiter. - current_expr.push(chr); - } - } - (State::Expr, '{') => { - current_expr.push(chr); - inexpr_open_count += 1; - } - (State::Expr, _) => { - if matches!(chr, '\\' | '$') { - current_expr.push('\\'); - } - current_expr.push(chr); - } - (State::FormatOpts, '}') => { - self.output.push(chr); - self.state = State::NotExpr; - } - (State::FormatOpts, _) => { - if matches!(chr, '\\' | '$') { - self.output.push('\\'); - } - self.output.push(chr); - } - } - } - - if self.state != State::NotExpr { - return Err(()); - } - - self.parsed = true; - Ok(()) - } - - pub(crate) fn to_suggestion(&self, macro_name: &str) -> String { - assert!(self.parsed, "Attempt to get a suggestion from not parsed expression"); - - let expressions_as_string = self.extracted_expressions.join(", "); - format!(r#"{}("{}", {})"#, macro_name, self.output, expressions_as_string) - } -} - #[cfg(test)] mod tests { use super::*; - use expect_test::{expect, Expect}; - - fn check(input: &str, expect: &Expect) { - let mut parser = FormatStrParser::new((*input).to_owned()); - let outcome_repr = if parser.parse().is_ok() { - // Parsing should be OK, expected repr is "string; expr_1, expr_2". - if parser.extracted_expressions.is_empty() { - parser.output - } else { - format!("{}; {}", parser.output, parser.extracted_expressions.join(", ")) - } - } else { - // Parsing should fail, expected repr is "-". - "-".to_owned() - }; - - expect.assert_eq(&outcome_repr); - } - - #[test] - fn format_str_parser() { - let test_vector = &[ - ("no expressions", expect![["no expressions"]]), - (r"no expressions with \$0$1", expect![r"no expressions with \\\$0\$1"]), - ("{expr} is {2 + 2}", expect![["{} is {}; expr, 2 + 2"]]), - ("{expr:?}", expect![["{:?}; expr"]]), - ("{expr:1$}", expect![[r"{:1\$}; expr"]]), - ("{$0}", expect![[r"{}; \$0"]]), - ("{malformed", expect![["-"]]), - ("malformed}", expect![["-"]]), - ("{{correct", expect![["{{correct"]]), - ("correct}}", expect![["correct}}"]]), - ("{correct}}}", expect![["{}}}; correct"]]), - ("{correct}}}}}", expect![["{}}}}}; correct"]]), - ("{incorrect}}", expect![["-"]]), - ("placeholders {} {}", expect![["placeholders {} {}; $1, $2"]]), - ("mixed {} {2 + 2} {}", expect![["mixed {} {} {}; $1, 2 + 2, $2"]]), - ( - "{SomeStruct { val_a: 0, val_b: 1 }}", - expect![["{}; SomeStruct { val_a: 0, val_b: 1 }"]], - ), - ("{expr:?} is {2.32f64:.5}", expect![["{:?} is {:.5}; expr, 2.32f64"]]), - ( - "{SomeStruct { val_a: 0, val_b: 1 }:?}", - expect![["{:?}; SomeStruct { val_a: 0, val_b: 1 }"]], - ), - ("{ 2 + 2 }", expect![["{}; 2 + 2"]]), - ("{strsim::jaro_winkle(a)}", expect![["{}; strsim::jaro_winkle(a)"]]), - ("{foo::bar::baz()}", expect![["{}; foo::bar::baz()"]]), - ("{foo::bar():?}", expect![["{:?}; foo::bar()"]]), - ]; - - for (input, output) in test_vector { - check(input, output) - } - } #[test] fn test_into_suggestion() { @@ -302,10 +76,10 @@ mod tests { ]; for (kind, input, output) in test_vector { - let mut parser = FormatStrParser::new((*input).to_owned()); - parser.parse().expect("Parsing must succeed"); - - assert_eq!(&parser.to_suggestion(*kind), output); + let (parsed_string, exprs) = parse_format_exprs(input).unwrap(); + let exprs = add_placeholders(exprs.map(|e| e.1)).collect_vec();; + let snippet = format!(r#"{}("{}", {})"#, kind, parsed_string, exprs.join(", ")); + assert_eq!(&snippet, output); } } } diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index 1ec62a8425..e0bc0f89f0 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -38,6 +38,7 @@ pub mod syntax_helpers { pub mod node_ext; pub mod insert_whitespace_into_node; pub mod format_string; + pub mod format_string_exprs; pub use parser::LexedStr; } diff --git a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs new file mode 100644 index 0000000000..b6b2eb268d --- /dev/null +++ b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs @@ -0,0 +1,227 @@ +use syntax::{ast, TextRange, AstToken}; + +#[derive(Debug)] +pub enum Arg { + Placeholder, + Expr(String) +} + +/** + Add placeholders like `$1` and `$2` in place of [`Arg::Placeholder`]. + ```rust + assert_eq!(vec![Arg::Expr("expr"), Arg::Placeholder, Arg::Expr("expr")], vec!["expr", "$1", "expr"]) + ``` +*/ + +pub fn add_placeholders (args: impl Iterator) -> impl Iterator { + let mut placeholder_id = 1; + args.map(move |a| + match a { + Arg::Expr(s) => s, + Arg::Placeholder => { + let s = format!("${placeholder_id}"); + placeholder_id += 1; + s + } + } + ) +} + +/** + Parser for a format-like string. It is more allowing in terms of string contents, + as we expect variable placeholders to be filled with expressions. + + Built for completions and assists, and escapes `\` and `$` in output. + (See the comments on `get_receiver_text()` for detail.) + Splits a format string that may contain expressions + like + ```rust + assert_eq!(parse("{expr} {} {expr} ").unwrap(), ("{} {} {}", vec![Arg::Expr("expr"), Arg::Placeholder, Arg::Expr("expr")])); + ``` +*/ +pub fn parse_format_exprs(input: &ast::String) -> Result, ()> { + #[derive(Debug, Clone, Copy, PartialEq)] + enum State { + NotExpr, + MaybeExpr, + Expr, + MaybeIncorrect, + FormatOpts, + } + + let start = input.syntax().text_range().start(); + + let mut expr_start = start; + let mut current_expr = String::new(); + let mut state = State::NotExpr; + let mut extracted_expressions = Vec::new(); + let mut output = String::new(); + + // Count of open braces inside of an expression. + // We assume that user knows what they're doing, thus we treat it like a correct pattern, e.g. + // "{MyStruct { val_a: 0, val_b: 1 }}". + let mut inexpr_open_count = 0; + + let mut chars = input.text().chars().zip(0u32..).peekable(); + while let Some((chr, idx )) = chars.next() { + match (state, chr) { + (State::NotExpr, '{') => { + output.push(chr); + state = State::MaybeExpr; + } + (State::NotExpr, '}') => { + output.push(chr); + state = State::MaybeIncorrect; + } + (State::NotExpr, _) => { + if matches!(chr, '\\' | '$') { + output.push('\\'); + } + output.push(chr); + } + (State::MaybeIncorrect, '}') => { + // It's okay, we met "}}". + output.push(chr); + state = State::NotExpr; + } + (State::MaybeIncorrect, _) => { + // Error in the string. + return Err(()); + } + (State::MaybeExpr, '{') => { + output.push(chr); + state = State::NotExpr; + } + (State::MaybeExpr, '}') => { + // This is an empty sequence '{}'. Replace it with placeholder. + output.push(chr); + extracted_expressions.push((TextRange::empty(expr_start), Arg::Placeholder)); + state = State::NotExpr; + } + (State::MaybeExpr, _) => { + if matches!(chr, '\\' | '$') { + current_expr.push('\\'); + } + current_expr.push(chr); + expr_start = start.checked_add(idx.into()).ok_or(())?; + state = State::Expr; + } + (State::Expr, '}') => { + if inexpr_open_count == 0 { + output.push(chr); + extracted_expressions.push((TextRange::new(expr_start, start.checked_add(idx.into()).ok_or(())?), Arg::Expr(current_expr.trim().into()))); + current_expr = String::new(); + state = State::NotExpr; + } else { + // We're closing one brace met before inside of the expression. + current_expr.push(chr); + inexpr_open_count -= 1; + } + } + (State::Expr, ':') if matches!(chars.peek(), Some((':', _))) => { + // path separator + current_expr.push_str("::"); + chars.next(); + } + (State::Expr, ':') => { + if inexpr_open_count == 0 { + // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}" + output.push(chr); + extracted_expressions.push((TextRange::new(expr_start, start.checked_add(idx.into()).ok_or(())?), Arg::Expr(current_expr.trim().into()))); + current_expr = String::new(); + state = State::FormatOpts; + } else { + // We're inside of braced expression, assume that it's a struct field name/value delimiter. + current_expr.push(chr); + } + } + (State::Expr, '{') => { + current_expr.push(chr); + inexpr_open_count += 1; + } + (State::Expr, _) => { + if matches!(chr, '\\' | '$') { + current_expr.push('\\'); + } + current_expr.push(chr); + } + (State::FormatOpts, '}') => { + output.push(chr); + state = State::NotExpr; + } + (State::FormatOpts, _) => { + if matches!(chr, '\\' | '$') { + output.push('\\'); + } + output.push(chr); + } + } + } + + if state != State::NotExpr { + return Err(()); + } + + Ok(extracted_expressions) +} + +#[cfg(test)] +mod tests { + use super::*; + use expect_test::{expect, Expect}; + + fn check(input: &str, expect: &Expect) { + let mut parser = FormatStrParser::new((*input).to_owned()); + let outcome_repr = if parser.parse().is_ok() { + // Parsing should be OK, expected repr is "string; expr_1, expr_2". + if parser.extracted_expressions.is_empty() { + parser.output + } else { + format!("{}; {}", parser.output, parser.extracted_expressions.join(", ")) + } + } else { + // Parsing should fail, expected repr is "-". + "-".to_owned() + }; + + expect.assert_eq(&outcome_repr); + } + + #[test] + fn format_str_parser() { + let test_vector = &[ + ("no expressions", expect![["no expressions"]]), + (r"no expressions with \$0$1", expect![r"no expressions with \\\$0\$1"]), + ("{expr} is {2 + 2}", expect![["{} is {}; expr, 2 + 2"]]), + ("{expr:?}", expect![["{:?}; expr"]]), + ("{expr:1$}", expect![[r"{:1\$}; expr"]]), + ("{$0}", expect![[r"{}; \$0"]]), + ("{malformed", expect![["-"]]), + ("malformed}", expect![["-"]]), + ("{{correct", expect![["{{correct"]]), + ("correct}}", expect![["correct}}"]]), + ("{correct}}}", expect![["{}}}; correct"]]), + ("{correct}}}}}", expect![["{}}}}}; correct"]]), + ("{incorrect}}", expect![["-"]]), + ("placeholders {} {}", expect![["placeholders {} {}; $1, $2"]]), + ("mixed {} {2 + 2} {}", expect![["mixed {} {} {}; $1, 2 + 2, $2"]]), + ( + "{SomeStruct { val_a: 0, val_b: 1 }}", + expect![["{}; SomeStruct { val_a: 0, val_b: 1 }"]], + ), + ("{expr:?} is {2.32f64:.5}", expect![["{:?} is {:.5}; expr, 2.32f64"]]), + ( + "{SomeStruct { val_a: 0, val_b: 1 }:?}", + expect![["{:?}; SomeStruct { val_a: 0, val_b: 1 }"]], + ), + ("{ 2 + 2 }", expect![["{}; 2 + 2"]]), + ("{strsim::jaro_winkle(a)}", expect![["{}; strsim::jaro_winkle(a)"]]), + ("{foo::bar::baz()}", expect![["{}; foo::bar::baz()"]]), + ("{foo::bar():?}", expect![["{:?}; foo::bar()"]]), + ]; + + for (input, output) in test_vector { + check(input, output) + } + } +} From cc7200891b3cf624f716b03ef24867650b485dca Mon Sep 17 00:00:00 2001 From: Kartavya Vashishtha Date: Sat, 10 Sep 2022 20:12:47 +0530 Subject: [PATCH 18/42] new lint: move_format_string_arg The name might need some improving. extract format_like's parser to it's own module in ide-db reworked the parser's API to be more direct added assist to extract expressions in format args --- .../src/handlers/move_format_string_arg.rs | 224 +++++++++++------- crates/ide-assists/src/lib.rs | 1 + crates/ide-assists/src/tests/generated.rs | 18 +- .../src/completions/postfix/format_like.rs | 15 +- .../src/syntax_helpers/format_string_exprs.rs | 52 ++-- 5 files changed, 185 insertions(+), 125 deletions(-) diff --git a/crates/ide-assists/src/handlers/move_format_string_arg.rs b/crates/ide-assists/src/handlers/move_format_string_arg.rs index 696fd50b5c..54b5bee9b7 100644 --- a/crates/ide-assists/src/handlers/move_format_string_arg.rs +++ b/crates/ide-assists/src/handlers/move_format_string_arg.rs @@ -1,100 +1,133 @@ -use ide_db::{syntax_helpers::{format_string::is_format_string, format_string_exprs::{parse_format_exprs, Arg}}, assists::{AssistId, AssistKind}}; +use crate::{AssistContext, Assists}; +use ide_db::{ + assists::{AssistId, AssistKind}, + syntax_helpers::{ + format_string::is_format_string, + format_string_exprs::{parse_format_exprs, Arg}, + }, +}; use itertools::Itertools; -use syntax::{ast, AstToken, AstNode, NodeOrToken, SyntaxKind::COMMA, TextRange}; +use syntax::{ast, AstNode, AstToken, NodeOrToken, SyntaxKind::COMMA, TextRange}; // Assist: move_format_string_arg // // Move an expression out of a format string. // // ``` +// macro_rules! format_args { +// ($lit:literal $(tt:tt)*) => { 0 }, +// } +// macro_rules! print { +// ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*))); +// } +// // fn main() { -// println!("{x + 1}$0"); +// print!("{x + 1}$0"); // } // ``` // -> // ``` +// macro_rules! format_args { +// ($lit:literal $(tt:tt)*) => { 0 }, +// } +// macro_rules! print { +// ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*))); +// } +// // fn main() { -// println!("{a}", a$0 = x + 1); +// print!("{}"$0, x + 1); // } // ``` -use crate::{AssistContext, /* AssistId, AssistKind, */ Assists}; - -pub(crate) fn move_format_string_arg (acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { - let t = ctx.find_token_at_offset::()?; - let tt = t.syntax().parent_ancestors().find_map(ast::TokenTree::cast)?; - - let expanded_t = ast::String::cast(ctx.sema.descend_into_macros_with_kind_preference(t.syntax().clone()))?; +pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + let fmt_string = ctx.find_token_at_offset::()?; + let tt = fmt_string.syntax().parent_ancestors().find_map(ast::TokenTree::cast)?; + let expanded_t = ast::String::cast( + ctx.sema.descend_into_macros_with_kind_preference(fmt_string.syntax().clone()), + )?; if !is_format_string(&expanded_t) { return None; } - let target = tt.syntax().text_range(); - let extracted_args = parse_format_exprs(&t).ok()?; - let str_range = t.syntax().text_range(); + let (new_fmt, extracted_args) = parse_format_exprs(fmt_string.text()).ok()?; - let tokens = - tt.token_trees_and_tokens() - .filter_map(NodeOrToken::into_token) - .collect_vec(); + acc.add( + AssistId("move_format_string_arg", AssistKind::QuickFix), + "Extract format args", + tt.syntax().text_range(), + |edit| { + let fmt_range = fmt_string.syntax().text_range(); - acc.add(AssistId("move_format_string_arg", AssistKind::QuickFix), "Extract format args", target, |edit| { - let mut existing_args: Vec = vec![]; - let mut current_arg = String::new(); + // Replace old format string with new format string whose arguments have been extracted + edit.replace(fmt_range, new_fmt); - if let [_opening_bracket, format_string, _args_start_comma, tokens @ .., end_bracket] = tokens.as_slice() { - for t in tokens { - if t.kind() == COMMA { - existing_args.push(current_arg.trim().into()); - current_arg.clear(); - } else { - current_arg.push_str(t.text()); + // Insert cursor at end of format string + edit.insert(fmt_range.end(), "$0"); + + // Extract existing arguments in macro + let tokens = + tt.token_trees_and_tokens().filter_map(NodeOrToken::into_token).collect_vec(); + + let mut existing_args: Vec = vec![]; + + let mut current_arg = String::new(); + if let [_opening_bracket, format_string, _args_start_comma, tokens @ .., end_bracket] = + tokens.as_slice() + { + for t in tokens { + if t.kind() == COMMA { + existing_args.push(current_arg.trim().into()); + current_arg.clear(); + } else { + current_arg.push_str(t.text()); + } } + existing_args.push(current_arg.trim().into()); + + // delete everything after the format string till end bracket + // we're going to insert the new arguments later + edit.delete(TextRange::new( + format_string.text_range().end(), + end_bracket.text_range().start(), + )); } - existing_args.push(current_arg.trim().into()); - // delete everything after the format string to the end bracket - // we're going to insert the new arguments later - edit.delete(TextRange::new(format_string.text_range().end(), end_bracket.text_range().start())); - } + // Start building the new args + let mut existing_args = existing_args.into_iter(); + let mut args = String::new(); - let mut existing_args = existing_args.into_iter(); + let mut placeholder_idx = 1; - // insert cursor at end of format string - edit.insert(str_range.end(), "$0"); - let mut placeholder_idx = 1; - let mut args = String::new(); + for extracted_args in extracted_args { + // remove expr from format string + args.push_str(", "); - for (text, extracted_args) in extracted_args { - // remove expr from format string - edit.delete(text); - - args.push_str(", "); - - match extracted_args { - Arg::Expr(s) => { - // insert arg - args.push_str(&s); - }, - Arg::Placeholder => { - // try matching with existing argument - match existing_args.next() { - Some(ea) => { - args.push_str(&ea); - }, - None => { - // insert placeholder - args.push_str(&format!("${placeholder_idx}")); - placeholder_idx += 1; + match extracted_args { + Arg::Expr(s) => { + // insert arg + args.push_str(&s); + } + Arg::Placeholder => { + // try matching with existing argument + match existing_args.next() { + Some(ea) => { + args.push_str(&ea); + } + None => { + // insert placeholder + args.push_str(&format!("${placeholder_idx}")); + placeholder_idx += 1; + } } } } } - } - edit.insert(str_range.end(), args); - }); + // Insert new args + edit.insert(fmt_range.end(), args); + }, + ); Some(()) } @@ -113,7 +146,7 @@ macro_rules! print { } "#; - fn add_macro_decl (s: &'static str) -> String { + fn add_macro_decl(s: &'static str) -> String { MACRO_DECL.to_string() + s } @@ -121,17 +154,20 @@ macro_rules! print { fn multiple_middle_arg() { check_assist( move_format_string_arg, - &add_macro_decl(r#" + &add_macro_decl( + r#" fn main() { print!("{} {x + 1:b} {}$0", y + 2, 2); } -"#), - - &add_macro_decl(r#" +"#, + ), + &add_macro_decl( + r#" fn main() { print!("{} {:b} {}"$0, y + 2, x + 1, 2); } -"#), +"#, + ), ); } @@ -139,16 +175,20 @@ fn main() { fn single_arg() { check_assist( move_format_string_arg, - &add_macro_decl(r#" + &add_macro_decl( + r#" fn main() { print!("{obj.value:b}$0",); } -"#), - &add_macro_decl(r#" +"#, + ), + &add_macro_decl( + r#" fn main() { print!("{:b}"$0, obj.value); } -"#), +"#, + ), ); } @@ -156,17 +196,20 @@ fn main() { fn multiple_middle_placeholders_arg() { check_assist( move_format_string_arg, - &add_macro_decl(r#" + &add_macro_decl( + r#" fn main() { print!("{} {x + 1:b} {} {}$0", y + 2, 2); } -"#), - - &add_macro_decl(r#" +"#, + ), + &add_macro_decl( + r#" fn main() { print!("{} {:b} {} {}"$0, y + 2, x + 1, 2, $1); } -"#), +"#, + ), ); } @@ -174,17 +217,20 @@ fn main() { fn multiple_trailing_args() { check_assist( move_format_string_arg, - &add_macro_decl(r#" + &add_macro_decl( + r#" fn main() { print!("{} {x + 1:b} {Struct(1, 2)}$0", 1); } -"#), - - &add_macro_decl(r#" +"#, + ), + &add_macro_decl( + r#" fn main() { print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2)); } -"#), +"#, + ), ); } @@ -192,18 +238,20 @@ fn main() { fn improper_commas() { check_assist( move_format_string_arg, - &add_macro_decl(r#" + &add_macro_decl( + r#" fn main() { print!("{} {x + 1:b} {Struct(1, 2)}$0", 1,); } -"#), - - &add_macro_decl(r#" +"#, + ), + &add_macro_decl( + r#" fn main() { print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2)); } -"#), +"#, + ), ); } - } diff --git a/crates/ide-assists/src/lib.rs b/crates/ide-assists/src/lib.rs index f881be9cf6..812d22efbd 100644 --- a/crates/ide-assists/src/lib.rs +++ b/crates/ide-assists/src/lib.rs @@ -255,6 +255,7 @@ mod handlers { merge_imports::merge_imports, merge_match_arms::merge_match_arms, move_bounds::move_bounds_to_where_clause, + move_format_string_arg::move_format_string_arg, move_guard::move_arm_cond_to_match_guard, move_guard::move_guard_to_arm_body, move_module_to_file::move_module_to_file, diff --git a/crates/ide-assists/src/tests/generated.rs b/crates/ide-assists/src/tests/generated.rs index fa88abd6c5..3a696635af 100644 --- a/crates/ide-assists/src/tests/generated.rs +++ b/crates/ide-assists/src/tests/generated.rs @@ -1596,13 +1596,27 @@ fn doctest_move_format_string_arg() { check_doc_test( "move_format_string_arg", r#####" +macro_rules! format_args { + ($lit:literal $(tt:tt)*) => { 0 }, +} +macro_rules! print { + ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*))); +} + fn main() { - println!("{x + 1}$0"); + print!("{x + 1}$0"); } "#####, r#####" +macro_rules! format_args { + ($lit:literal $(tt:tt)*) => { 0 }, +} +macro_rules! print { + ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*))); +} + fn main() { - println!("{a}", a$0 = x + 1); + print!("{}"$0, x + 1); } "#####, ) diff --git a/crates/ide-completion/src/completions/postfix/format_like.rs b/crates/ide-completion/src/completions/postfix/format_like.rs index 89bfdac74d..b43bdb9ab9 100644 --- a/crates/ide-completion/src/completions/postfix/format_like.rs +++ b/crates/ide-completion/src/completions/postfix/format_like.rs @@ -16,8 +16,11 @@ // // image::https://user-images.githubusercontent.com/48062697/113020656-b560f500-917a-11eb-87de-02991f61beb8.gif[] -use ide_db::{syntax_helpers::format_string_exprs::{parse_format_exprs, add_placeholders}, SnippetCap}; -use syntax::ast::{self, AstToken}; +use ide_db::{ + syntax_helpers::format_string_exprs::{parse_format_exprs, with_placeholders}, + SnippetCap, +}; +use syntax::{ast, AstToken}; use crate::{ completions::postfix::build_postfix_snippet_builder, context::CompletionContext, Completions, @@ -48,10 +51,10 @@ pub(crate) fn add_format_like_completions( None => return, }; - if let Ok((out, exprs)) = parse_format_exprs(receiver_text) { - let exprs = add_placeholders(exprs.map(|e| e.1)).collect_vec(); + if let Ok((out, exprs)) = parse_format_exprs(receiver_text.text()) { + let exprs = with_placeholders(exprs); for (label, macro_name) in KINDS { - let snippet = format!(r#"{}("{}", {})"#, macro_name, out, exprs.join(", ")); + let snippet = format!(r#"{}({}, {})"#, macro_name, out, exprs.join(", ")); postfix_snippet(label, macro_name, &snippet).add_to(acc); } @@ -77,7 +80,7 @@ mod tests { for (kind, input, output) in test_vector { let (parsed_string, exprs) = parse_format_exprs(input).unwrap(); - let exprs = add_placeholders(exprs.map(|e| e.1)).collect_vec();; + let exprs = with_placeholders(exprs); let snippet = format!(r#"{}("{}", {})"#, kind, parsed_string, exprs.join(", ")); assert_eq!(&snippet, output); } diff --git a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs index b6b2eb268d..e9006e06b1 100644 --- a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs +++ b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs @@ -1,9 +1,13 @@ -use syntax::{ast, TextRange, AstToken}; +//! Tools to work with expressions present in format string literals for the `format_args!` family of macros. +//! Primarily meant for assists and completions. +/// Enum for represenging extraced format string args. +/// Can either be extracted expressions (which includes identifiers), +/// or placeholders `{}`. #[derive(Debug)] pub enum Arg { Placeholder, - Expr(String) + Expr(String), } /** @@ -13,18 +17,18 @@ pub enum Arg { ``` */ -pub fn add_placeholders (args: impl Iterator) -> impl Iterator { +pub fn with_placeholders(args: Vec) -> Vec { let mut placeholder_id = 1; - args.map(move |a| - match a { + args.into_iter() + .map(move |a| match a { Arg::Expr(s) => s, Arg::Placeholder => { let s = format!("${placeholder_id}"); placeholder_id += 1; s } - } - ) + }) + .collect() } /** @@ -39,7 +43,7 @@ pub fn add_placeholders (args: impl Iterator) -> impl Iterator Result, ()> { +pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { #[derive(Debug, Clone, Copy, PartialEq)] enum State { NotExpr, @@ -49,9 +53,6 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, FormatOpts, } - let start = input.syntax().text_range().start(); - - let mut expr_start = start; let mut current_expr = String::new(); let mut state = State::NotExpr; let mut extracted_expressions = Vec::new(); @@ -62,8 +63,8 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, // "{MyStruct { val_a: 0, val_b: 1 }}". let mut inexpr_open_count = 0; - let mut chars = input.text().chars().zip(0u32..).peekable(); - while let Some((chr, idx )) = chars.next() { + let mut chars = input.chars().peekable(); + while let Some(chr) = chars.next() { match (state, chr) { (State::NotExpr, '{') => { output.push(chr); @@ -95,7 +96,7 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, (State::MaybeExpr, '}') => { // This is an empty sequence '{}'. Replace it with placeholder. output.push(chr); - extracted_expressions.push((TextRange::empty(expr_start), Arg::Placeholder)); + extracted_expressions.push(Arg::Placeholder); state = State::NotExpr; } (State::MaybeExpr, _) => { @@ -103,13 +104,12 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, current_expr.push('\\'); } current_expr.push(chr); - expr_start = start.checked_add(idx.into()).ok_or(())?; state = State::Expr; } (State::Expr, '}') => { if inexpr_open_count == 0 { output.push(chr); - extracted_expressions.push((TextRange::new(expr_start, start.checked_add(idx.into()).ok_or(())?), Arg::Expr(current_expr.trim().into()))); + extracted_expressions.push(Arg::Expr(current_expr.trim().into())); current_expr = String::new(); state = State::NotExpr; } else { @@ -118,7 +118,7 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, inexpr_open_count -= 1; } } - (State::Expr, ':') if matches!(chars.peek(), Some((':', _))) => { + (State::Expr, ':') if matches!(chars.peek(), Some(':')) => { // path separator current_expr.push_str("::"); chars.next(); @@ -127,7 +127,7 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, if inexpr_open_count == 0 { // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}" output.push(chr); - extracted_expressions.push((TextRange::new(expr_start, start.checked_add(idx.into()).ok_or(())?), Arg::Expr(current_expr.trim().into()))); + extracted_expressions.push(Arg::Expr(current_expr.trim().into())); current_expr = String::new(); state = State::FormatOpts; } else { @@ -162,7 +162,7 @@ pub fn parse_format_exprs(input: &ast::String) -> Result, return Err(()); } - Ok(extracted_expressions) + Ok((output, extracted_expressions)) } #[cfg(test)] @@ -171,17 +171,11 @@ mod tests { use expect_test::{expect, Expect}; fn check(input: &str, expect: &Expect) { - let mut parser = FormatStrParser::new((*input).to_owned()); - let outcome_repr = if parser.parse().is_ok() { - // Parsing should be OK, expected repr is "string; expr_1, expr_2". - if parser.extracted_expressions.is_empty() { - parser.output - } else { - format!("{}; {}", parser.output, parser.extracted_expressions.join(", ")) - } + let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_string(), vec![])); + let outcome_repr = if !exprs.is_empty() { + format!("{}; {}", output, with_placeholders(exprs).join(", ")) } else { - // Parsing should fail, expected repr is "-". - "-".to_owned() + output }; expect.assert_eq(&outcome_repr); From a5cbee4d11ff0c4fca00493d4015d9b8e7f82d6d Mon Sep 17 00:00:00 2001 From: Kartavya Vashishtha Date: Sat, 10 Sep 2022 21:04:25 +0530 Subject: [PATCH 19/42] remove false positive --- crates/ide-assists/src/handlers/move_format_string_arg.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ide-assists/src/handlers/move_format_string_arg.rs b/crates/ide-assists/src/handlers/move_format_string_arg.rs index 54b5bee9b7..4a5dd09c88 100644 --- a/crates/ide-assists/src/handlers/move_format_string_arg.rs +++ b/crates/ide-assists/src/handlers/move_format_string_arg.rs @@ -51,6 +51,9 @@ pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) } let (new_fmt, extracted_args) = parse_format_exprs(fmt_string.text()).ok()?; + if extracted_args.is_empty() { + return None; + } acc.add( AssistId("move_format_string_arg", AssistKind::QuickFix), From fb5ae9906ba7961c8b3c39512181c966b82d180c Mon Sep 17 00:00:00 2001 From: Kartavya Vashishtha Date: Sun, 11 Sep 2022 10:39:25 +0530 Subject: [PATCH 20/42] suggest ExtractRefactor if no expressions found Added `Ident` variant to arg enum. --- .../src/handlers/move_format_string_arg.rs | 12 +- .../src/syntax_helpers/format_string_exprs.rs | 106 +++++++++++++----- 2 files changed, 86 insertions(+), 32 deletions(-) diff --git a/crates/ide-assists/src/handlers/move_format_string_arg.rs b/crates/ide-assists/src/handlers/move_format_string_arg.rs index 4a5dd09c88..cb7c30b37d 100644 --- a/crates/ide-assists/src/handlers/move_format_string_arg.rs +++ b/crates/ide-assists/src/handlers/move_format_string_arg.rs @@ -56,7 +56,15 @@ pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) } acc.add( - AssistId("move_format_string_arg", AssistKind::QuickFix), + AssistId( + "move_format_string_arg", + // if there aren't any expressions, then make the assist a RefactorExtract + if extracted_args.iter().filter(|f| matches!(f, Arg::Expr(_))).count() == 0 { + AssistKind::RefactorExtract + } else { + AssistKind::QuickFix + }, + ), "Extract format args", tt.syntax().text_range(), |edit| { @@ -107,7 +115,7 @@ pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) args.push_str(", "); match extracted_args { - Arg::Expr(s) => { + Arg::Ident(s) | Arg::Expr(s) => { // insert arg args.push_str(&s); } diff --git a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs index e9006e06b1..ac6c6e8fee 100644 --- a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs +++ b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs @@ -4,16 +4,19 @@ /// Enum for represenging extraced format string args. /// Can either be extracted expressions (which includes identifiers), /// or placeholders `{}`. -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub enum Arg { Placeholder, + Ident(String), Expr(String), } /** - Add placeholders like `$1` and `$2` in place of [`Arg::Placeholder`]. + Add placeholders like `$1` and `$2` in place of [`Arg::Placeholder`], + and unwraps the [`Arg::Ident`] and [`Arg::Expr`] enums. ```rust - assert_eq!(vec![Arg::Expr("expr"), Arg::Placeholder, Arg::Expr("expr")], vec!["expr", "$1", "expr"]) + # use ide_db::syntax_helpers::format_string_exprs::*; + assert_eq!(with_placeholders(vec![Arg::Ident("ident".to_owned()), Arg::Placeholder, Arg::Expr("expr + 2".to_owned())]), vec!["ident".to_owned(), "$1".to_owned(), "expr + 2".to_owned()]) ``` */ @@ -21,7 +24,7 @@ pub fn with_placeholders(args: Vec) -> Vec { let mut placeholder_id = 1; args.into_iter() .map(move |a| match a { - Arg::Expr(s) => s, + Arg::Expr(s) | Arg::Ident(s) => s, Arg::Placeholder => { let s = format!("${placeholder_id}"); placeholder_id += 1; @@ -40,21 +43,22 @@ pub fn with_placeholders(args: Vec) -> Vec { Splits a format string that may contain expressions like ```rust - assert_eq!(parse("{expr} {} {expr} ").unwrap(), ("{} {} {}", vec![Arg::Expr("expr"), Arg::Placeholder, Arg::Expr("expr")])); + assert_eq!(parse("{ident} {} {expr + 42} ").unwrap(), ("{} {} {}", vec![Arg::Ident("ident"), Arg::Placeholder, Arg::Expr("expr + 42")])); ``` */ pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { #[derive(Debug, Clone, Copy, PartialEq)] enum State { - NotExpr, - MaybeExpr, + NotArg, + MaybeArg, Expr, + Ident, MaybeIncorrect, FormatOpts, } + let mut state = State::NotArg; let mut current_expr = String::new(); - let mut state = State::NotExpr; let mut extracted_expressions = Vec::new(); let mut output = String::new(); @@ -66,15 +70,15 @@ pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { let mut chars = input.chars().peekable(); while let Some(chr) = chars.next() { match (state, chr) { - (State::NotExpr, '{') => { + (State::NotArg, '{') => { output.push(chr); - state = State::MaybeExpr; + state = State::MaybeArg; } - (State::NotExpr, '}') => { + (State::NotArg, '}') => { output.push(chr); state = State::MaybeIncorrect; } - (State::NotExpr, _) => { + (State::NotArg, _) => { if matches!(chr, '\\' | '$') { output.push('\\'); } @@ -83,51 +87,72 @@ pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { (State::MaybeIncorrect, '}') => { // It's okay, we met "}}". output.push(chr); - state = State::NotExpr; + state = State::NotArg; } (State::MaybeIncorrect, _) => { // Error in the string. return Err(()); } - (State::MaybeExpr, '{') => { + // Escaped braces `{{` + (State::MaybeArg, '{') => { output.push(chr); - state = State::NotExpr; + state = State::NotArg; } - (State::MaybeExpr, '}') => { - // This is an empty sequence '{}'. Replace it with placeholder. + (State::MaybeArg, '}') => { + // This is an empty sequence '{}'. output.push(chr); extracted_expressions.push(Arg::Placeholder); - state = State::NotExpr; + state = State::NotArg; } - (State::MaybeExpr, _) => { + (State::MaybeArg, _) => { if matches!(chr, '\\' | '$') { current_expr.push('\\'); } current_expr.push(chr); - state = State::Expr; + + // While Rust uses the unicode sets of XID_start and XID_continue for Identifiers + // this is probably the best we can do to avoid a false positive + if chr.is_alphabetic() || chr == '_' { + state = State::Ident; + } else { + state = State::Expr; + } } - (State::Expr, '}') => { + (State::Ident | State::Expr, '}') => { if inexpr_open_count == 0 { output.push(chr); - extracted_expressions.push(Arg::Expr(current_expr.trim().into())); + + if matches!(state, State::Expr) { + extracted_expressions.push(Arg::Expr(current_expr.trim().into())); + } else { + extracted_expressions.push(Arg::Ident(current_expr.trim().into())); + } + current_expr = String::new(); - state = State::NotExpr; + state = State::NotArg; } else { // We're closing one brace met before inside of the expression. current_expr.push(chr); inexpr_open_count -= 1; } } - (State::Expr, ':') if matches!(chars.peek(), Some(':')) => { + (State::Ident | State::Expr, ':') if matches!(chars.peek(), Some(':')) => { // path separator + state = State::Expr; current_expr.push_str("::"); chars.next(); } - (State::Expr, ':') => { + (State::Ident | State::Expr, ':') => { if inexpr_open_count == 0 { // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}" output.push(chr); - extracted_expressions.push(Arg::Expr(current_expr.trim().into())); + + if matches!(state, State::Expr) { + extracted_expressions.push(Arg::Expr(current_expr.trim().into())); + } else { + extracted_expressions.push(Arg::Ident(current_expr.trim().into())); + } + current_expr = String::new(); state = State::FormatOpts; } else { @@ -135,11 +160,16 @@ pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { current_expr.push(chr); } } - (State::Expr, '{') => { + (State::Ident | State::Expr, '{') => { + state = State::Expr; current_expr.push(chr); inexpr_open_count += 1; } - (State::Expr, _) => { + (State::Ident | State::Expr, _) => { + if !(chr.is_alphanumeric() || chr == '_' || chr == '#') { + state = State::Expr; + } + if matches!(chr, '\\' | '$') { current_expr.push('\\'); } @@ -147,7 +177,7 @@ pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { } (State::FormatOpts, '}') => { output.push(chr); - state = State::NotExpr; + state = State::NotArg; } (State::FormatOpts, _) => { if matches!(chr, '\\' | '$') { @@ -158,7 +188,7 @@ pub fn parse_format_exprs(input: &str) -> Result<(String, Vec), ()> { } } - if state != State::NotExpr { + if state != State::NotArg { return Err(()); } @@ -218,4 +248,20 @@ mod tests { check(input, output) } } + + #[test] + fn arg_type() { + assert_eq!( + parse_format_exprs("{_ident} {r#raw_ident} {expr.obj} {name {thing: 42} } {}") + .unwrap() + .1, + vec![ + Arg::Ident("_ident".to_owned()), + Arg::Ident("r#raw_ident".to_owned()), + Arg::Expr("expr.obj".to_owned()), + Arg::Expr("name {thing: 42}".to_owned()), + Arg::Placeholder + ] + ); + } } From 8a2803d9aea5099fcbb2b7f7b32cb3de60ab9e01 Mon Sep 17 00:00:00 2001 From: Mathew Horner Date: Sun, 11 Sep 2022 22:40:33 -0500 Subject: [PATCH 21/42] Allow configuration of annotation location. Previously, annotations would only appear above the name of an item (function signature, struct declaration, etc). Now, rust-analyzer can be configured to show annotations either above the name or above the whole item (including doc comments and attributes). --- crates/ide/src/annotations.rs | 100 ++++++++++++++++++++++----- crates/ide/src/lib.rs | 2 +- crates/rust-analyzer/src/config.rs | 30 ++++++++ crates/rust-analyzer/src/handlers.rs | 1 + docs/user/generated_config.adoc | 5 ++ editors/code/package.json | 13 ++++ 6 files changed, 132 insertions(+), 19 deletions(-) diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index 210c5c7fac..7019658a16 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -41,6 +41,12 @@ pub struct AnnotationConfig { pub annotate_references: bool, pub annotate_method_references: bool, pub annotate_enum_variant_references: bool, + pub annotation_location: AnnotationLocation, +} + +pub enum AnnotationLocation { + AboveName, + AboveWholeItem, } pub(crate) fn annotations( @@ -65,10 +71,10 @@ pub(crate) fn annotations( visit_file_defs(&Semantics::new(db), file_id, &mut |def| { let range = match def { Definition::Const(konst) if config.annotate_references => { - konst.source(db).and_then(|node| name_range(db, node, file_id)) + konst.source(db).and_then(|node| name_range(db, config, node, file_id)) } Definition::Trait(trait_) if config.annotate_references || config.annotate_impls => { - trait_.source(db).and_then(|node| name_range(db, node, file_id)) + trait_.source(db).and_then(|node| name_range(db, config, node, file_id)) } Definition::Adt(adt) => match adt { hir::Adt::Enum(enum_) => { @@ -77,7 +83,9 @@ pub(crate) fn annotations( .variants(db) .into_iter() .map(|variant| { - variant.source(db).and_then(|node| name_range(db, node, file_id)) + variant + .source(db) + .and_then(|node| name_range(db, config, node, file_id)) }) .flatten() .for_each(|range| { @@ -88,14 +96,14 @@ pub(crate) fn annotations( }) } if config.annotate_references || config.annotate_impls { - enum_.source(db).and_then(|node| name_range(db, node, file_id)) + enum_.source(db).and_then(|node| name_range(db, config, node, file_id)) } else { None } } _ => { if config.annotate_references || config.annotate_impls { - adt.source(db).and_then(|node| name_range(db, node, file_id)) + adt.source(db).and_then(|node| name_range(db, config, node, file_id)) } else { None } @@ -113,6 +121,7 @@ pub(crate) fn annotations( annotations .push(Annotation { range, kind: AnnotationKind::HasImpls { file_id, data: None } }); } + if config.annotate_references { annotations.push(Annotation { range, @@ -122,12 +131,18 @@ pub(crate) fn annotations( fn name_range( db: &RootDatabase, + config: &AnnotationConfig, node: InFile, source_file_id: FileId, ) -> Option { if let Some(InFile { file_id, value }) = node.original_ast_node(db) { if file_id == source_file_id.into() { - return value.name().map(|it| it.syntax().text_range()); + return match config.annotation_location { + AnnotationLocation::AboveName => { + value.name().map(|name| name.syntax().text_range()) + } + AnnotationLocation::AboveWholeItem => Some(value.syntax().text_range()), + }; } } None @@ -188,21 +203,23 @@ mod tests { use crate::{fixture, Annotation, AnnotationConfig}; - fn check(ra_fixture: &str, expect: Expect) { + use super::AnnotationLocation; + + const DEFAULT_CONFIG: AnnotationConfig = AnnotationConfig { + binary_target: true, + annotate_runnables: true, + annotate_impls: true, + annotate_references: true, + annotate_method_references: true, + annotate_enum_variant_references: true, + annotation_location: AnnotationLocation::AboveName, + }; + + fn check(ra_fixture: &str, expect: Expect, config: &AnnotationConfig) { let (analysis, file_id) = fixture::file(ra_fixture); let annotations: Vec = analysis - .annotations( - &AnnotationConfig { - binary_target: true, - annotate_runnables: true, - annotate_impls: true, - annotate_references: true, - annotate_method_references: true, - annotate_enum_variant_references: true, - }, - file_id, - ) + .annotations(config, file_id) .unwrap() .into_iter() .map(|annotation| analysis.resolve_annotation(annotation).unwrap()) @@ -286,6 +303,7 @@ fn main() { }, ] "#]], + &DEFAULT_CONFIG, ); } @@ -362,6 +380,7 @@ fn main() { }, ] "#]], + &DEFAULT_CONFIG, ); } @@ -497,6 +516,7 @@ fn main() { }, ] "#]], + &DEFAULT_CONFIG, ); } @@ -540,6 +560,7 @@ fn main() {} }, ] "#]], + &DEFAULT_CONFIG, ); } @@ -654,6 +675,7 @@ fn main() { }, ] "#]], + &DEFAULT_CONFIG, ); } @@ -750,6 +772,7 @@ mod tests { }, ] "#]], + &DEFAULT_CONFIG, ); } @@ -765,6 +788,7 @@ struct Foo; expect![[r#" [] "#]], + &DEFAULT_CONFIG, ); } @@ -784,6 +808,46 @@ m!(); expect![[r#" [] "#]], + &DEFAULT_CONFIG, + ); + } + + #[test] + fn test_annotations_appear_above_whole_item_when_configured_to_do_so() { + check( + r#" +/// This is a struct named Foo, obviously. +#[derive(Clone)] +struct Foo; +"#, + expect![[r#" + [ + Annotation { + range: 0..71, + kind: HasImpls { + file_id: FileId( + 0, + ), + data: Some( + [], + ), + }, + }, + Annotation { + range: 0..71, + kind: HasReferences { + file_id: FileId( + 0, + ), + data: None, + }, + }, + ] + "#]], + &AnnotationConfig { + annotation_location: AnnotationLocation::AboveWholeItem, + ..DEFAULT_CONFIG + }, ); } } diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 0552330814..c1ef25b592 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -74,7 +74,7 @@ use syntax::SourceFile; use crate::navigation_target::{ToNav, TryToNav}; pub use crate::{ - annotations::{Annotation, AnnotationConfig, AnnotationKind}, + annotations::{Annotation, AnnotationConfig, AnnotationKind, AnnotationLocation}, call_hierarchy::CallItem, expand_macro::ExpandedMacro, file_structure::{StructureNode, StructureNodeKind}, diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 54dcb42d99..6c6ad5f43a 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -307,6 +307,8 @@ config_data! { /// Join lines unwraps trivial blocks. joinLines_unwrapTrivialBlock: bool = "true", + /// Where to render annotations. + lens_annotationLocation: AnnotationLocation = "\"above_name\"", /// Whether to show `Debug` lens. Only applies when /// `#rust-analyzer.lens.enable#` is set. lens_debug_enable: bool = "true", @@ -494,6 +496,25 @@ pub struct LensConfig { pub refs_adt: bool, // for Struct, Enum, Union and Trait pub refs_trait: bool, // for Struct, Enum, Union and Trait pub enum_variant_refs: bool, + + // annotations + pub annotation_location: AnnotationLocation, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AnnotationLocation { + AboveName, + AboveWholeItem, +} + +impl From for ide::AnnotationLocation { + fn from(location: AnnotationLocation) -> Self { + match location { + AnnotationLocation::AboveName => ide::AnnotationLocation::AboveName, + AnnotationLocation::AboveWholeItem => ide::AnnotationLocation::AboveWholeItem, + } + } } impl LensConfig { @@ -1185,6 +1206,7 @@ impl Config { refs_trait: self.data.lens_enable && self.data.lens_references_trait_enable, enum_variant_refs: self.data.lens_enable && self.data.lens_references_enumVariant_enable, + annotation_location: self.data.lens_annotationLocation, } } @@ -1921,6 +1943,14 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json "Use server-side file watching", ], }, + "AnnotationLocation" => set! { + "type": "string", + "enum": ["above_name", "above_whole_item"], + "enumDescriptions": [ + "Render annotations above the name of the item.", + "Render annotations above the whole item, including documentation comments and attributes." + ], + }, _ => panic!("missing entry for {}: {}", ty, default), } diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index e79cf3d3fd..edac9de69a 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs @@ -1234,6 +1234,7 @@ pub(crate) fn handle_code_lens( annotate_references: lens_config.refs_adt, annotate_method_references: lens_config.method_refs, annotate_enum_variant_references: lens_config.enum_variant_refs, + annotation_location: lens_config.annotation_location.into(), }, file_id, )?; diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 72b9257264..3cd49bc5d8 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -451,6 +451,11 @@ Join lines removes trailing commas. -- Join lines unwraps trivial blocks. -- +[[rust-analyzer.lens.annotation.location]]rust-analyzer.lens.annotation.location (default: `above_name`):: ++ +-- +Where to render annotations. +-- [[rust-analyzer.lens.debug.enable]]rust-analyzer.lens.debug.enable (default: `true`):: + -- diff --git a/editors/code/package.json b/editors/code/package.json index 767c5875bf..465d866021 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -943,6 +943,19 @@ "default": true, "type": "boolean" }, + "rust-analyzer.lens.annotationLocation": { + "markdownDescription": "Where to render annotations.", + "default": "above_name", + "type": "string", + "enum": [ + "above_name", + "above_whole_item" + ], + "enumDescriptions": [ + "Render annotations above the name of the item.", + "Render annotations above the whole item, including documentation comments and attributes." + ] + }, "rust-analyzer.lens.debug.enable": { "markdownDescription": "Whether to show `Debug` lens. Only applies when\n`#rust-analyzer.lens.enable#` is set.", "default": true, From 32603baac383c081e035cb4433105e9d431c9332 Mon Sep 17 00:00:00 2001 From: Borys Minaiev Date: Mon, 12 Sep 2022 11:03:44 +0100 Subject: [PATCH 22/42] Remove redundant 'resolve_obligations_as_possible' call --- crates/hir-ty/src/infer.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/hir-ty/src/infer.rs b/crates/hir-ty/src/infer.rs index 10ffde87ee..e37763e8ea 100644 --- a/crates/hir-ty/src/infer.rs +++ b/crates/hir-ty/src/infer.rs @@ -673,10 +673,6 @@ impl<'a> InferenceContext<'a> { ) } - fn resolve_obligations_as_possible(&mut self) { - self.table.resolve_obligations_as_possible(); - } - fn push_obligation(&mut self, o: DomainGoal) { self.table.register_obligation(o.cast(Interner)); } @@ -696,7 +692,6 @@ impl<'a> InferenceContext<'a> { } fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty { - self.resolve_obligations_as_possible(); self.table.resolve_ty_shallow(ty) } From 54e9324e93646433e8404af106223890ef52105c Mon Sep 17 00:00:00 2001 From: Kartavya Vashishtha Date: Mon, 12 Sep 2022 05:45:11 -0700 Subject: [PATCH 23/42] Update crates/ide-assists/src/handlers/move_format_string_arg.rs Co-authored-by: Lukas Wirth --- crates/ide-assists/src/handlers/move_format_string_arg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ide-assists/src/handlers/move_format_string_arg.rs b/crates/ide-assists/src/handlers/move_format_string_arg.rs index cb7c30b37d..92b2fa79d7 100644 --- a/crates/ide-assists/src/handlers/move_format_string_arg.rs +++ b/crates/ide-assists/src/handlers/move_format_string_arg.rs @@ -41,7 +41,7 @@ use syntax::{ast, AstNode, AstToken, NodeOrToken, SyntaxKind::COMMA, TextRange}; pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let fmt_string = ctx.find_token_at_offset::()?; - let tt = fmt_string.syntax().parent_ancestors().find_map(ast::TokenTree::cast)?; + let tt = fmt_string.syntax().parent().and_then(ast::TokenTree::cast)?; let expanded_t = ast::String::cast( ctx.sema.descend_into_macros_with_kind_preference(fmt_string.syntax().clone()), From efb56160c91f0c1db511423fad8cc09fdd73d618 Mon Sep 17 00:00:00 2001 From: Ryo Yoshida Date: Mon, 12 Sep 2022 21:56:46 +0900 Subject: [PATCH 24/42] fix: handle lifetime variables in projection normalization --- crates/hir-ty/src/db.rs | 8 +++++ crates/hir-ty/src/lib.rs | 14 -------- crates/hir-ty/src/traits.rs | 17 +++++++-- crates/hir/src/lib.rs | 29 +++------------ crates/ide/src/inlay_hints.rs | 68 +++++++++++++++++++++++++++++++++++ 5 files changed, 94 insertions(+), 42 deletions(-) diff --git a/crates/hir-ty/src/db.rs b/crates/hir-ty/src/db.rs index b385b1cafa..dd5639f00d 100644 --- a/crates/hir-ty/src/db.rs +++ b/crates/hir-ty/src/db.rs @@ -150,6 +150,14 @@ pub trait HirDatabase: DefDatabase + Upcast { id: chalk_db::AssociatedTyValueId, ) -> Arc; + #[salsa::invoke(crate::traits::normalize_projection_query)] + #[salsa::transparent] + fn normalize_projection( + &self, + projection: crate::ProjectionTy, + env: Arc, + ) -> Option; + #[salsa::invoke(trait_solve_wait)] #[salsa::transparent] fn trait_solve( diff --git a/crates/hir-ty/src/lib.rs b/crates/hir-ty/src/lib.rs index a82a331d4b..de4a5446e5 100644 --- a/crates/hir-ty/src/lib.rs +++ b/crates/hir-ty/src/lib.rs @@ -196,20 +196,6 @@ pub(crate) fn make_binders>( make_binders_with_count(db, usize::MAX, generics, value) } -// FIXME: get rid of this -pub fn make_canonical>( - value: T, - kinds: impl IntoIterator, -) -> Canonical { - let kinds = kinds.into_iter().map(|tk| { - chalk_ir::CanonicalVarKind::new( - chalk_ir::VariableKind::Ty(tk), - chalk_ir::UniverseIndex::ROOT, - ) - }); - Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(Interner, kinds) } -} - // FIXME: get rid of this, just replace it by FnPointer /// A function signature as seen by type inference: Several parameter types and /// one return type. diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index 77afeb3217..aaff894b34 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -1,6 +1,6 @@ //! Trait solving using Chalk. -use std::env::var; +use std::{env::var, sync::Arc}; use chalk_ir::GoalData; use chalk_recursive::Cache; @@ -12,8 +12,9 @@ use stdx::panic_context; use syntax::SmolStr; use crate::{ - db::HirDatabase, AliasEq, AliasTy, Canonical, DomainGoal, Goal, Guidance, InEnvironment, - Interner, Solution, TraitRefExt, Ty, TyKind, WhereClause, + db::HirDatabase, infer::unify::InferenceTable, AliasEq, AliasTy, Canonical, DomainGoal, Goal, + Guidance, InEnvironment, Interner, ProjectionTy, Solution, TraitRefExt, Ty, TyKind, + WhereClause, }; /// This controls how much 'time' we give the Chalk solver before giving up. @@ -64,6 +65,16 @@ impl TraitEnvironment { } } +pub(crate) fn normalize_projection_query( + db: &dyn HirDatabase, + projection: ProjectionTy, + env: Arc, +) -> Option { + let mut table = InferenceTable::new(db, env.clone()); + let ty = table.normalize_projection_ty(projection); + Some(table.resolve_completely(ty)) +} + /// Solve a trait goal using Chalk. pub(crate) fn trait_solve_query( db: &dyn HirDatabase, diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index e4bb63a864..d49d2e1ca3 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -63,10 +63,9 @@ use hir_ty::{ primitive::UintTy, subst_prefix, traits::FnTrait, - AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast, - ClosureId, DebruijnIndex, GenericArgData, InEnvironment, Interner, ParamKind, - QuantifiedWhereClause, Scalar, Solution, Substitution, TraitEnvironment, TraitRefExt, Ty, - TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind, WhereClause, + AliasTy, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast, ClosureId, + GenericArgData, Interner, ParamKind, QuantifiedWhereClause, Scalar, Substitution, + TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, WhereClause, }; use itertools::Itertools; use nameres::diagnostics::DefDiagnosticKind; @@ -2880,28 +2879,8 @@ impl Type { } }) .build(); - let goal = hir_ty::make_canonical( - InEnvironment::new( - &self.env.env, - AliasEq { - alias: AliasTy::Projection(projection), - ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)) - .intern(Interner), - } - .cast(Interner), - ), - [TyVariableKind::General].into_iter(), - ); - match db.trait_solve(self.env.krate, goal)? { - Solution::Unique(s) => s - .value - .subst - .as_slice(Interner) - .first() - .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone())), - Solution::Ambig(_) => None, - } + db.normalize_projection(projection, self.env.clone()).map(|ty| self.derived(ty)) } pub fn is_copy(&self, db: &dyn HirDatabase) -> bool { diff --git a/crates/ide/src/inlay_hints.rs b/crates/ide/src/inlay_hints.rs index d1b1d2c331..93fcd7cad7 100644 --- a/crates/ide/src/inlay_hints.rs +++ b/crates/ide/src/inlay_hints.rs @@ -1687,6 +1687,74 @@ fn main() { ); } + #[test] + fn iterator_hint_regression_issue_12674() { + // Ensure we don't crash while solving the projection type of iterators. + check_expect( + InlayHintsConfig { chaining_hints: true, ..DISABLED_CONFIG }, + r#" +//- minicore: iterators +struct S(T); +impl S { + fn iter(&self) -> Iter<'_, T> { loop {} } +} +struct Iter<'a, T: 'a>(&'a T); +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option { loop {} } +} +struct Container<'a> { + elements: S<&'a str>, +} +struct SliceIter<'a, T>(&'a T); +impl<'a, T> Iterator for SliceIter<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option { loop {} } +} + +fn main(a: SliceIter<'_, Container>) { + a + .filter_map(|c| Some(c.elements.iter().filter_map(|v| Some(v)))) + .map(|e| e); +} + "#, + expect![[r#" + [ + InlayHint { + range: 484..554, + kind: ChainingHint, + label: [ + "impl Iterator>", + ], + tooltip: Some( + HoverRanged( + FileId( + 0, + ), + 484..554, + ), + ), + }, + InlayHint { + range: 484..485, + kind: ChainingHint, + label: [ + "SliceIter", + ], + tooltip: Some( + HoverRanged( + FileId( + 0, + ), + 484..485, + ), + ), + }, + ] + "#]], + ); + } + #[test] fn infer_call_method_return_associated_types_with_generic() { check_types( From d223c28c7d89de5a6f040e254c8a602ae7d48814 Mon Sep 17 00:00:00 2001 From: Ryo Yoshida Date: Tue, 13 Sep 2022 01:52:16 +0900 Subject: [PATCH 25/42] Remove unnecessary `Option` --- crates/hir-ty/src/db.rs | 2 +- crates/hir-ty/src/traits.rs | 6 +++--- crates/hir/src/lib.rs | 7 ++++++- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/hir-ty/src/db.rs b/crates/hir-ty/src/db.rs index dd5639f00d..69283e55a4 100644 --- a/crates/hir-ty/src/db.rs +++ b/crates/hir-ty/src/db.rs @@ -156,7 +156,7 @@ pub trait HirDatabase: DefDatabase + Upcast { &self, projection: crate::ProjectionTy, env: Arc, - ) -> Option; + ) -> Ty; #[salsa::invoke(trait_solve_wait)] #[salsa::transparent] diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index aaff894b34..372c3a3cca 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -69,10 +69,10 @@ pub(crate) fn normalize_projection_query( db: &dyn HirDatabase, projection: ProjectionTy, env: Arc, -) -> Option { - let mut table = InferenceTable::new(db, env.clone()); +) -> Ty { + let mut table = InferenceTable::new(db, env); let ty = table.normalize_projection_ty(projection); - Some(table.resolve_completely(ty)) + table.resolve_completely(ty) } /// Solve a trait goal using Chalk. diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index d49d2e1ca3..c981ffbc78 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -2880,7 +2880,12 @@ impl Type { }) .build(); - db.normalize_projection(projection, self.env.clone()).map(|ty| self.derived(ty)) + let ty = db.normalize_projection(projection, self.env.clone()); + if ty.is_unknown() { + None + } else { + Some(self.derived(ty)) + } } pub fn is_copy(&self, db: &dyn HirDatabase) -> bool { From f57c15f3e9843ad6b220d5f75f3e0b2cb126098a Mon Sep 17 00:00:00 2001 From: Mathew Horner Date: Mon, 12 Sep 2022 16:34:13 -0500 Subject: [PATCH 26/42] Address comments and fix build. --- crates/ide/src/annotations.rs | 27 ++++++++++----------------- crates/rust-analyzer/src/config.rs | 9 +++++---- crates/rust-analyzer/src/handlers.rs | 2 +- docs/user/generated_config.adoc | 10 +++++----- editors/code/package.json | 26 +++++++++++++------------- 5 files changed, 34 insertions(+), 40 deletions(-) diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index 7019658a16..bfbe0db6e4 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -41,7 +41,7 @@ pub struct AnnotationConfig { pub annotate_references: bool, pub annotate_method_references: bool, pub annotate_enum_variant_references: bool, - pub annotation_location: AnnotationLocation, + pub location: AnnotationLocation, } pub enum AnnotationLocation { @@ -137,7 +137,7 @@ pub(crate) fn annotations( ) -> Option { if let Some(InFile { file_id, value }) = node.original_ast_node(db) { if file_id == source_file_id.into() { - return match config.annotation_location { + return match config.location { AnnotationLocation::AboveName => { value.name().map(|name| name.syntax().text_range()) } @@ -212,10 +212,10 @@ mod tests { annotate_references: true, annotate_method_references: true, annotate_enum_variant_references: true, - annotation_location: AnnotationLocation::AboveName, + location: AnnotationLocation::AboveName, }; - fn check(ra_fixture: &str, expect: Expect, config: &AnnotationConfig) { + fn check_with_config(ra_fixture: &str, expect: Expect, config: &AnnotationConfig) { let (analysis, file_id) = fixture::file(ra_fixture); let annotations: Vec = analysis @@ -228,6 +228,10 @@ mod tests { expect.assert_debug_eq(&annotations); } + fn check(ra_fixture: &str, expect: Expect) { + check_with_config(ra_fixture, expect, &DEFAULT_CONFIG); + } + #[test] fn const_annotations() { check( @@ -303,7 +307,6 @@ fn main() { }, ] "#]], - &DEFAULT_CONFIG, ); } @@ -380,7 +383,6 @@ fn main() { }, ] "#]], - &DEFAULT_CONFIG, ); } @@ -516,7 +518,6 @@ fn main() { }, ] "#]], - &DEFAULT_CONFIG, ); } @@ -560,7 +561,6 @@ fn main() {} }, ] "#]], - &DEFAULT_CONFIG, ); } @@ -675,7 +675,6 @@ fn main() { }, ] "#]], - &DEFAULT_CONFIG, ); } @@ -772,7 +771,6 @@ mod tests { }, ] "#]], - &DEFAULT_CONFIG, ); } @@ -788,7 +786,6 @@ struct Foo; expect![[r#" [] "#]], - &DEFAULT_CONFIG, ); } @@ -808,13 +805,12 @@ m!(); expect![[r#" [] "#]], - &DEFAULT_CONFIG, ); } #[test] fn test_annotations_appear_above_whole_item_when_configured_to_do_so() { - check( + check_with_config( r#" /// This is a struct named Foo, obviously. #[derive(Clone)] @@ -844,10 +840,7 @@ struct Foo; }, ] "#]], - &AnnotationConfig { - annotation_location: AnnotationLocation::AboveWholeItem, - ..DEFAULT_CONFIG - }, + &AnnotationConfig { location: AnnotationLocation::AboveWholeItem, ..DEFAULT_CONFIG }, ); } } diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 6c6ad5f43a..68b4c20140 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -307,8 +307,7 @@ config_data! { /// Join lines unwraps trivial blocks. joinLines_unwrapTrivialBlock: bool = "true", - /// Where to render annotations. - lens_annotationLocation: AnnotationLocation = "\"above_name\"", + /// Whether to show `Debug` lens. Only applies when /// `#rust-analyzer.lens.enable#` is set. lens_debug_enable: bool = "true", @@ -320,6 +319,8 @@ config_data! { /// Whether to show `Implementations` lens. Only applies when /// `#rust-analyzer.lens.enable#` is set. lens_implementations_enable: bool = "true", + /// Where to render annotations. + lens_location: AnnotationLocation = "\"above_name\"", /// Whether to show `References` lens for Struct, Enum, and Union. /// Only applies when `#rust-analyzer.lens.enable#` is set. lens_references_adt_enable: bool = "false", @@ -498,7 +499,7 @@ pub struct LensConfig { pub enum_variant_refs: bool, // annotations - pub annotation_location: AnnotationLocation, + pub location: AnnotationLocation, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)] @@ -1206,7 +1207,7 @@ impl Config { refs_trait: self.data.lens_enable && self.data.lens_references_trait_enable, enum_variant_refs: self.data.lens_enable && self.data.lens_references_enumVariant_enable, - annotation_location: self.data.lens_annotationLocation, + location: self.data.lens_location, } } diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index edac9de69a..a1eb972f78 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs @@ -1234,7 +1234,7 @@ pub(crate) fn handle_code_lens( annotate_references: lens_config.refs_adt, annotate_method_references: lens_config.method_refs, annotate_enum_variant_references: lens_config.enum_variant_refs, - annotation_location: lens_config.annotation_location.into(), + location: lens_config.location.into(), }, file_id, )?; diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 3cd49bc5d8..6e6d40e3ff 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -451,11 +451,6 @@ Join lines removes trailing commas. -- Join lines unwraps trivial blocks. -- -[[rust-analyzer.lens.annotation.location]]rust-analyzer.lens.annotation.location (default: `above_name`):: -+ --- -Where to render annotations. --- [[rust-analyzer.lens.debug.enable]]rust-analyzer.lens.debug.enable (default: `true`):: + -- @@ -479,6 +474,11 @@ client doesn't set the corresponding capability. Whether to show `Implementations` lens. Only applies when `#rust-analyzer.lens.enable#` is set. -- +[[rust-analyzer.lens.location]]rust-analyzer.lens.location (default: `"above_name"`):: ++ +-- +Where to render annotations. +-- [[rust-analyzer.lens.references.adt.enable]]rust-analyzer.lens.references.adt.enable (default: `false`):: + -- diff --git a/editors/code/package.json b/editors/code/package.json index 465d866021..3696c99624 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -943,19 +943,6 @@ "default": true, "type": "boolean" }, - "rust-analyzer.lens.annotationLocation": { - "markdownDescription": "Where to render annotations.", - "default": "above_name", - "type": "string", - "enum": [ - "above_name", - "above_whole_item" - ], - "enumDescriptions": [ - "Render annotations above the name of the item.", - "Render annotations above the whole item, including documentation comments and attributes." - ] - }, "rust-analyzer.lens.debug.enable": { "markdownDescription": "Whether to show `Debug` lens. Only applies when\n`#rust-analyzer.lens.enable#` is set.", "default": true, @@ -976,6 +963,19 @@ "default": true, "type": "boolean" }, + "rust-analyzer.lens.location": { + "markdownDescription": "Where to render annotations.", + "default": "above_name", + "type": "string", + "enum": [ + "above_name", + "above_whole_item" + ], + "enumDescriptions": [ + "Render annotations above the name of the item.", + "Render annotations above the whole item, including documentation comments and attributes." + ] + }, "rust-analyzer.lens.references.adt.enable": { "markdownDescription": "Whether to show `References` lens for Struct, Enum, and Union.\nOnly applies when `#rust-analyzer.lens.enable#` is set.", "default": false, From cadb01c3155fe1df4ab3d59659ae22fc477c6734 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 13 Sep 2022 14:47:26 +0200 Subject: [PATCH 27/42] Move reference imports filtering into to_proto layer --- crates/ide-db/src/search.rs | 15 +++++++++-- crates/ide/src/annotations.rs | 1 - crates/ide/src/highlight_related.rs | 11 ++++---- crates/ide/src/lib.rs | 5 +--- crates/ide/src/references.rs | 38 ++++++++-------------------- crates/rust-analyzer/src/handlers.rs | 18 +++++++------ crates/rust-analyzer/src/to_proto.rs | 7 ++--- 7 files changed, 45 insertions(+), 50 deletions(-) diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs index 7deffe8e0f..6f885fba78 100644 --- a/crates/ide-db/src/search.rs +++ b/crates/ide-db/src/search.rs @@ -9,6 +9,7 @@ use std::{mem, sync::Arc}; use base_db::{FileId, FileRange, SourceDatabase, SourceDatabaseExt}; use hir::{DefWithBody, HasAttrs, HasSource, InFile, ModuleSource, Semantics, Visibility}; use once_cell::unsync::Lazy; +use parser::SyntaxKind; use stdx::hash::NoHashHashMap; use syntax::{ast, match_ast, AstNode, TextRange, TextSize}; @@ -67,6 +68,7 @@ pub enum ReferenceCategory { // Create Write, Read, + Import, // FIXME: Some day should be able to search in doc comments. Would probably // need to switch from enum to bitflags then? // DocComment @@ -577,7 +579,7 @@ impl<'a> FindUsages<'a> { let reference = FileReference { range, name: ast::NameLike::NameRef(name_ref.clone()), - category: None, + category: is_name_ref_in_import(name_ref).then(|| ReferenceCategory::Import), }; sink(file_id, reference) } @@ -756,7 +758,7 @@ impl ReferenceCategory { fn new(def: &Definition, r: &ast::NameRef) -> Option { // Only Locals and Fields have accesses for now. if !matches!(def, Definition::Local(_) | Definition::Field(_)) { - return None; + return is_name_ref_in_import(r).then(|| ReferenceCategory::Import); } let mode = r.syntax().ancestors().find_map(|node| { @@ -783,3 +785,12 @@ impl ReferenceCategory { mode.or(Some(ReferenceCategory::Read)) } } + +fn is_name_ref_in_import(name_ref: &ast::NameRef) -> bool { + name_ref + .syntax() + .parent() + .and_then(ast::PathSegment::cast) + .and_then(|it| it.parent_path().top_path().syntax().parent()) + .map_or(false, |it| it.kind() == SyntaxKind::USE_TREE) +} diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs index ba4c330bf3..210c5c7fac 100644 --- a/crates/ide/src/annotations.rs +++ b/crates/ide/src/annotations.rs @@ -158,7 +158,6 @@ pub(crate) fn resolve_annotation(db: &RootDatabase, mut annotation: Annotation) &Semantics::new(db), FilePosition { file_id, offset: annotation.range.start() }, None, - false, ) .map(|result| { result diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs index f190da326e..1bdd626f1e 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -377,6 +377,7 @@ mod tests { match it { ReferenceCategory::Read => "read", ReferenceCategory::Write => "write", + ReferenceCategory::Import => "import", } .to_string() }), @@ -423,12 +424,12 @@ struct Foo; check( r#" use crate$0; - //^^^^^ + //^^^^^ import use self; - //^^^^ + //^^^^ import mod __ { use super; - //^^^^^ + //^^^^^ import } "#, ); @@ -436,7 +437,7 @@ mod __ { r#" //- /main.rs crate:main deps:lib use lib$0; - //^^^ + //^^^ import //- /lib.rs crate:lib "#, ); @@ -450,7 +451,7 @@ use lib$0; mod foo; //- /foo.rs use self$0; - // ^^^^ + // ^^^^ import "#, ); } diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs index 065b48378b..0552330814 100644 --- a/crates/ide/src/lib.rs +++ b/crates/ide/src/lib.rs @@ -425,11 +425,8 @@ impl Analysis { &self, position: FilePosition, search_scope: Option, - exclude_imports: bool, ) -> Cancellable>> { - self.with_db(|db| { - references::find_all_refs(&Semantics::new(db), position, search_scope, exclude_imports) - }) + self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope)) } /// Finds all methods and free functions for the file. Does not return tests! diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 5b410c454d..e942413c11 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -54,7 +54,6 @@ pub(crate) fn find_all_refs( sema: &Semantics<'_, RootDatabase>, position: FilePosition, search_scope: Option, - exclude_imports: bool, ) -> Option> { let _p = profile::span("find_all_refs"); let syntax = sema.parse(position.file_id).syntax().clone(); @@ -80,10 +79,6 @@ pub(crate) fn find_all_refs( retain_adt_literal_usages(&mut usages, def, sema); } - if exclude_imports { - filter_import_references(&mut usages); - } - let references = usages .into_iter() .map(|(file_id, refs)| { @@ -117,17 +112,6 @@ pub(crate) fn find_all_refs( } } -fn filter_import_references(usages: &mut UsageSearchResult) { - for (_file_id, refs) in &mut usages.references { - refs.retain(|it| match it.name.as_name_ref() { - Some(name_ref) => { - !name_ref.syntax().ancestors().any(|it_ref| matches!(it_ref.kind(), USE)) - } - None => true, - }); - } -} - pub(crate) fn find_defs<'a>( sema: &'a Semantics<'_, RootDatabase>, syntax: &SyntaxNode, @@ -758,7 +742,7 @@ pub struct Foo { expect![[r#" foo Module FileId(0) 0..8 4..7 - FileId(0) 14..17 + FileId(0) 14..17 Import "#]], ); } @@ -776,7 +760,7 @@ use self$0; expect![[r#" foo Module FileId(0) 0..8 4..7 - FileId(1) 4..8 + FileId(1) 4..8 Import "#]], ); } @@ -791,7 +775,7 @@ use self$0; expect![[r#" Module FileId(0) 0..10 - FileId(0) 4..8 + FileId(0) 4..8 Import "#]], ); } @@ -819,7 +803,7 @@ pub(super) struct Foo$0 { expect![[r#" Foo Struct FileId(2) 0..41 18..21 - FileId(1) 20..23 + FileId(1) 20..23 Import FileId(1) 47..50 "#]], ); @@ -982,7 +966,7 @@ fn g() { f(); } expect![[r#" f Function FileId(0) 22..31 25..26 - FileId(1) 11..12 + FileId(1) 11..12 Import FileId(1) 24..25 "#]], ); @@ -1110,7 +1094,7 @@ impl Foo { fn check_with_scope(ra_fixture: &str, search_scope: Option, expect: Expect) { let (analysis, pos) = fixture::position(ra_fixture); - let refs = analysis.find_all_refs(pos, search_scope, false).unwrap().unwrap(); + let refs = analysis.find_all_refs(pos, search_scope).unwrap().unwrap(); let mut actual = String::new(); for refs in refs { @@ -1440,9 +1424,9 @@ pub use level1::Foo; expect![[r#" Foo Struct FileId(0) 0..15 11..14 - FileId(1) 16..19 - FileId(2) 16..19 - FileId(3) 16..19 + FileId(1) 16..19 Import + FileId(2) 16..19 Import + FileId(3) 16..19 Import "#]], ); } @@ -1470,7 +1454,7 @@ lib::foo!(); expect![[r#" foo Macro FileId(1) 0..61 29..32 - FileId(0) 46..49 + FileId(0) 46..49 Import FileId(2) 0..3 FileId(3) 5..8 "#]], @@ -1633,7 +1617,7 @@ struct Foo; expect![[r#" derive_identity Derive FileId(2) 1..107 45..60 - FileId(0) 17..31 + FileId(0) 17..31 Import FileId(0) 56..70 "#]], ); diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index 7b486744da..baf6dd7488 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs @@ -10,8 +10,8 @@ use std::{ use anyhow::Context; use ide::{ AnnotationConfig, AssistKind, AssistResolveStrategy, FileId, FilePosition, FileRange, - HoverAction, HoverGotoTypeData, Query, RangeInfo, Runnable, RunnableKind, SingleResolve, - SourceChange, TextEdit, + HoverAction, HoverGotoTypeData, Query, RangeInfo, ReferenceCategory, Runnable, RunnableKind, + SingleResolve, SourceChange, TextEdit, }; use ide_db::SymbolKind; use lsp_server::ErrorCode; @@ -1014,7 +1014,7 @@ pub(crate) fn handle_references( let exclude_imports = snap.config.find_all_refs_exclude_imports(); - let refs = match snap.analysis.find_all_refs(position, None, exclude_imports)? { + let refs = match snap.analysis.find_all_refs(position, None)? { None => return Ok(None), Some(refs) => refs, }; @@ -1034,7 +1034,11 @@ pub(crate) fn handle_references( refs.references .into_iter() .flat_map(|(file_id, refs)| { - refs.into_iter().map(move |(range, _)| FileRange { file_id, range }) + refs.into_iter() + .filter(|&(_, category)| { + !exclude_imports || category != Some(ReferenceCategory::Import) + }) + .map(move |(range, _)| FileRange { file_id, range }) }) .chain(decl) }) @@ -1285,7 +1289,7 @@ pub(crate) fn handle_document_highlight( .into_iter() .map(|ide::HighlightedRange { range, category }| lsp_types::DocumentHighlight { range: to_proto::range(&line_index, range), - kind: category.map(to_proto::document_highlight_kind), + kind: category.and_then(to_proto::document_highlight_kind), }) .collect(); Ok(Some(res)) @@ -1654,9 +1658,7 @@ fn show_ref_command_link( position: &FilePosition, ) -> Option { if snap.config.hover_actions().references && snap.config.client_commands().show_reference { - if let Some(ref_search_res) = - snap.analysis.find_all_refs(*position, None, false).unwrap_or(None) - { + if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) { let uri = to_proto::url(snap, position.file_id); let line_index = snap.file_line_index(position.file_id).ok()?; let position = to_proto::position(&line_index, position.offset); diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs index e083b9d0e3..1de801e23e 100644 --- a/crates/rust-analyzer/src/to_proto.rs +++ b/crates/rust-analyzer/src/to_proto.rs @@ -83,10 +83,11 @@ pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolK pub(crate) fn document_highlight_kind( category: ReferenceCategory, -) -> lsp_types::DocumentHighlightKind { +) -> Option { match category { - ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ, - ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE, + ReferenceCategory::Read => Some(lsp_types::DocumentHighlightKind::READ), + ReferenceCategory::Write => Some(lsp_types::DocumentHighlightKind::WRITE), + ReferenceCategory::Import => None, } } From a8ecaa19796e6d302f82b05f533ab99bd9522644 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 13 Sep 2022 15:09:40 +0200 Subject: [PATCH 28/42] Restructure `find_path` into a separate functions for modules and non-module items Also renames `prefer_core` imports config to `prefer_no_std` and changes the behavior of no_std path searching by preferring `core` paths `over` alloc --- crates/hir-def/src/find_path.rs | 422 +++++++++++------- crates/hir-def/src/item_scope.rs | 9 +- crates/hir/src/lib.rs | 8 +- crates/ide-assists/src/assist_config.rs | 2 +- .../src/handlers/add_missing_match_arms.rs | 8 +- .../ide-assists/src/handlers/auto_import.rs | 2 +- .../src/handlers/convert_into_to_from.rs | 2 +- .../src/handlers/extract_function.rs | 2 +- .../extract_struct_from_enum_variant.rs | 2 +- .../src/handlers/generate_deref.rs | 4 +- .../ide-assists/src/handlers/generate_new.rs | 2 +- .../src/handlers/qualify_method_call.rs | 2 +- .../ide-assists/src/handlers/qualify_path.rs | 2 +- .../replace_derive_with_manual_impl.rs | 2 +- .../replace_qualified_name_with_use.rs | 2 +- crates/ide-assists/src/tests.rs | 2 +- crates/ide-completion/src/completions.rs | 8 +- crates/ide-completion/src/completions/expr.rs | 8 +- .../src/completions/flyimport.rs | 6 +- crates/ide-completion/src/config.rs | 2 +- crates/ide-completion/src/lib.rs | 2 +- crates/ide-completion/src/snippet.rs | 2 +- crates/ide-completion/src/tests.rs | 2 +- crates/ide-db/src/imports/import_assets.rs | 18 +- .../src/handlers/json_is_not_rust.rs | 4 +- .../src/handlers/missing_fields.rs | 2 +- crates/ide-diagnostics/src/lib.rs | 4 +- crates/rust-analyzer/src/config.rs | 10 +- .../src/integrated_benchmarks.rs | 4 +- docs/user/generated_config.adoc | 4 +- editors/code/package.json | 4 +- 31 files changed, 322 insertions(+), 231 deletions(-) diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index f46054e8cc..b94b500040 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -1,6 +1,6 @@ //! An algorithm to find a path to refer to a certain item. -use std::iter; +use std::{cmp::Ordering, iter}; use hir_expand::name::{known, AsName, Name}; use rustc_hash::FxHashSet; @@ -20,10 +20,10 @@ pub fn find_path( db: &dyn DefDatabase, item: ItemInNs, from: ModuleId, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { let _p = profile::span("find_path"); - find_path_inner(db, item, from, None, prefer_core) + find_path_inner(db, item, from, None, prefer_no_std) } pub fn find_path_prefixed( @@ -31,48 +31,14 @@ pub fn find_path_prefixed( item: ItemInNs, from: ModuleId, prefix_kind: PrefixKind, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { let _p = profile::span("find_path_prefixed"); - find_path_inner(db, item, from, Some(prefix_kind), prefer_core) + find_path_inner(db, item, from, Some(prefix_kind), prefer_no_std) } const MAX_PATH_LEN: usize = 15; -trait ModPathExt { - fn starts_with_std(&self) -> bool; - fn can_start_with_std(&self) -> bool; -} - -impl ModPathExt for ModPath { - fn starts_with_std(&self) -> bool { - self.segments().first() == Some(&known::std) - } - - // Can we replace the first segment with `std::` and still get a valid, identical path? - fn can_start_with_std(&self) -> bool { - let first_segment = self.segments().first(); - first_segment == Some(&known::alloc) || first_segment == Some(&known::core) - } -} - -fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option { - if item == ItemInNs::Types(from.into()) { - // - if the item is the module we're in, use `self` - Some(ModPath::from_segments(PathKind::Super(0), None)) - } else if let Some(parent_id) = def_map[from.local_id].parent { - // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly) - let parent_id = def_map.module_id(parent_id); - if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) { - Some(ModPath::from_segments(PathKind::Super(1), None)) - } else { - None - } - } else { - None - } -} - #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum PrefixKind { /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name. @@ -100,117 +66,60 @@ impl PrefixKind { self == &PrefixKind::ByCrate } } + /// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId fn find_path_inner( db: &dyn DefDatabase, item: ItemInNs, from: ModuleId, prefixed: Option, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { - // FIXME: Do fast path for std/core libs? - - let mut visited_modules = FxHashSet::default(); - let def_map = from.def_map(db); - find_path_inner_( - db, - &def_map, - from, - item, - MAX_PATH_LEN, - prefixed, - &mut visited_modules, - prefer_core, - ) -} - -fn find_path_inner_( - db: &dyn DefDatabase, - def_map: &DefMap, - from: ModuleId, - item: ItemInNs, - max_len: usize, - mut prefixed: Option, - visited_modules: &mut FxHashSet, - prefer_core: bool, -) -> Option { - if max_len == 0 { - return None; + // - if the item is a builtin, it's in scope + if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item { + return Some(ModPath::from_segments(PathKind::Plain, Some(builtin.as_name()))); } - // Base cases: + let def_map = from.def_map(db); + let crate_root = def_map.crate_root(db); + // - if the item is a module, jump straight to module search + if let ItemInNs::Types(ModuleDefId::ModuleId(module_id)) = item { + let mut visited_modules = FxHashSet::default(); + return find_path_for_module( + db, + &def_map, + &mut visited_modules, + crate_root, + from, + module_id, + MAX_PATH_LEN, + prefixed, + prefer_no_std || db.crate_supports_no_std(crate_root.krate), + ); + } // - if the item is already in scope, return the name under which it is - let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| { - def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone()) - }); + let scope_name = find_in_scope(db, &def_map, from, item); if prefixed.is_none() { if let Some(scope_name) = scope_name { return Some(ModPath::from_segments(PathKind::Plain, Some(scope_name))); } } - // - if the item is a builtin, it's in scope - if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item { - return Some(ModPath::from_segments(PathKind::Plain, Some(builtin.as_name()))); - } - - // - if the item is the crate root, return `crate` - let crate_root = def_map.crate_root(db); - if item == ItemInNs::Types(ModuleDefId::ModuleId(crate_root)) { - return Some(ModPath::from_segments(PathKind::Crate, None)); - } - - if prefixed.filter(PrefixKind::is_absolute).is_none() { - if let modpath @ Some(_) = check_self_super(&def_map, item, from) { - return modpath; - } - } - - // - if the item is the crate root of a dependency crate, return the name from the extern prelude - let root_def_map = crate_root.def_map(db); - if let ItemInNs::Types(ModuleDefId::ModuleId(item)) = item { - for (name, &def_id) in root_def_map.extern_prelude() { - if item == def_id { - let name = scope_name.unwrap_or_else(|| name.clone()); - - let name_already_occupied_in_type_ns = def_map - .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| { - def_map[local_id] - .scope - .type_(&name) - .filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id)) - }) - .is_some(); - let kind = if name_already_occupied_in_type_ns { - cov_mark::hit!(ambiguous_crate_start); - PathKind::Abs - } else { - PathKind::Plain - }; - return Some(ModPath::from_segments(kind, Some(name))); - } - } - } - // - if the item is in the prelude, return the name from there - if let Some(prelude_module) = root_def_map.prelude() { - // Preludes in block DefMaps are ignored, only the crate DefMap is searched - let prelude_def_map = prelude_module.def_map(db); - let prelude_scope = &prelude_def_map[prelude_module.local_id].scope; - if let Some((name, vis)) = prelude_scope.name_of(item) { - if vis.is_visible_from(db, from) { - return Some(ModPath::from_segments(PathKind::Plain, Some(name.clone()))); - } - } + if let Some(value) = find_in_prelude(db, &crate_root.def_map(db), item, from) { + return value; } - // Recursive case: - // - if the item is an enum variant, refer to it via the enum if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() { - if let Some(mut path) = - find_path(db, ItemInNs::Types(variant.parent.into()), from, prefer_core) - { + // - if the item is an enum variant, refer to it via the enum + if let Some(mut path) = find_path_inner( + db, + ItemInNs::Types(variant.parent.into()), + from, + prefixed, + prefer_no_std, + ) { let data = db.enum_data(variant.parent); path.push_segment(data.variants[variant.local_id].name.clone()); return Some(path); @@ -220,29 +129,184 @@ fn find_path_inner_( // variant somewhere } - // - otherwise, look for modules containing (reexporting) it and import it from one of those - let prefer_no_std = prefer_core || db.crate_supports_no_std(crate_root.krate); - let mut best_path = None; - let mut best_path_len = max_len; + let mut visited_modules = FxHashSet::default(); + calculate_best_path( + db, + &def_map, + &mut visited_modules, + crate_root, + MAX_PATH_LEN, + item, + from, + prefixed, + prefer_no_std || db.crate_supports_no_std(crate_root.krate), + scope_name, + ) +} + +fn find_path_for_module( + db: &dyn DefDatabase, + def_map: &DefMap, + visited_modules: &mut FxHashSet, + crate_root: ModuleId, + from: ModuleId, + module_id: ModuleId, + max_len: usize, + prefixed: Option, + prefer_no_std: bool, +) -> Option { + if max_len == 0 { + return None; + } + + // Base cases: + // - if the item is already in scope, return the name under which it is + let scope_name = find_in_scope(db, def_map, from, ItemInNs::Types(module_id.into())); + if prefixed.is_none() { + if let Some(scope_name) = scope_name { + return Some(ModPath::from_segments(PathKind::Plain, Some(scope_name))); + } + } + + // - if the item is the crate root, return `crate` + if module_id == crate_root { + return Some(ModPath::from_segments(PathKind::Crate, None)); + } + + // - if relative paths are fine, check if we are searching for a parent + if prefixed.filter(PrefixKind::is_absolute).is_none() { + if let modpath @ Some(_) = find_self_super(&def_map, module_id, from) { + return modpath; + } + } + + // - if the item is the crate root of a dependency crate, return the name from the extern prelude + let root_def_map = crate_root.def_map(db); + for (name, &def_id) in root_def_map.extern_prelude() { + if module_id == def_id { + let name = scope_name.unwrap_or_else(|| name.clone()); + + let name_already_occupied_in_type_ns = def_map + .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| { + def_map[local_id] + .scope + .type_(&name) + .filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id)) + }) + .is_some(); + let kind = if name_already_occupied_in_type_ns { + cov_mark::hit!(ambiguous_crate_start); + PathKind::Abs + } else { + PathKind::Plain + }; + return Some(ModPath::from_segments(kind, Some(name))); + } + } + + if let Some(value) = find_in_prelude(db, &root_def_map, ItemInNs::Types(module_id.into()), from) + { + return value; + } + calculate_best_path( + db, + def_map, + visited_modules, + crate_root, + max_len, + ItemInNs::Types(module_id.into()), + from, + prefixed, + prefer_no_std, + scope_name, + ) +} + +fn find_in_scope( + db: &dyn DefDatabase, + def_map: &DefMap, + from: ModuleId, + item: ItemInNs, +) -> Option { + def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| { + def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone()) + }) +} + +fn find_in_prelude( + db: &dyn DefDatabase, + root_def_map: &DefMap, + item: ItemInNs, + from: ModuleId, +) -> Option> { + if let Some(prelude_module) = root_def_map.prelude() { + // Preludes in block DefMaps are ignored, only the crate DefMap is searched + let prelude_def_map = prelude_module.def_map(db); + let prelude_scope = &prelude_def_map[prelude_module.local_id].scope; + if let Some((name, vis)) = prelude_scope.name_of(item) { + if vis.is_visible_from(db, from) { + return Some(Some(ModPath::from_segments(PathKind::Plain, Some(name.clone())))); + } + } + } + None +} + +fn find_self_super(def_map: &DefMap, item: ModuleId, from: ModuleId) -> Option { + if item == from { + // - if the item is the module we're in, use `self` + Some(ModPath::from_segments(PathKind::Super(0), None)) + } else if let Some(parent_id) = def_map[from.local_id].parent { + // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly) + let parent_id = def_map.module_id(parent_id); + if item == parent_id { + Some(ModPath::from_segments(PathKind::Super(1), None)) + } else { + None + } + } else { + None + } +} + +fn calculate_best_path( + db: &dyn DefDatabase, + def_map: &DefMap, + visited_modules: &mut FxHashSet, + crate_root: ModuleId, + max_len: usize, + item: ItemInNs, + from: ModuleId, + mut prefixed: Option, + prefer_no_std: bool, + scope_name: Option, +) -> Option { + if max_len <= 1 { + return None; + } + let mut best_path = None; + // Recursive case: + // - otherwise, look for modules containing (reexporting) it and import it from one of those if item.krate(db) == Some(from.krate) { + let mut best_path_len = max_len; // Item was defined in the same crate that wants to import it. It cannot be found in any // dependency in this case. - // FIXME: this should have a fast path that doesn't look through the prelude again? for (module_id, name) in find_local_import_locations(db, item, from) { if !visited_modules.insert(module_id) { cov_mark::hit!(recursive_imports); continue; } - if let Some(mut path) = find_path_inner_( + if let Some(mut path) = find_path_for_module( db, def_map, + visited_modules, + crate_root, from, - ItemInNs::Types(ModuleDefId::ModuleId(module_id)), + module_id, best_path_len - 1, prefixed, - visited_modules, - prefer_core, + prefer_no_std, ) { path.push_segment(name); @@ -265,15 +329,16 @@ fn find_path_inner_( import_map.import_info_for(item).and_then(|info| { // Determine best path for containing module and append last segment from `info`. // FIXME: we should guide this to look up the path locally, or from the same crate again? - let mut path = find_path_inner_( + let mut path = find_path_for_module( db, def_map, - from, - ItemInNs::Types(ModuleDefId::ModuleId(info.container)), - best_path_len - 1, - prefixed, visited_modules, - prefer_core, + from, + crate_root, + info.container, + max_len - 1, + prefixed, + prefer_no_std, )?; cov_mark::hit!(partially_imported); path.push_segment(info.path.segments.last()?.clone()); @@ -289,16 +354,12 @@ fn find_path_inner_( best_path = Some(new_path); } } - - // If the item is declared inside a block expression, don't use a prefix, as we don't handle - // that correctly (FIXME). - if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) { - if item_module.def_map(db).block_id().is_some() && prefixed.is_some() { + if let Some(module) = item.module(db) { + if module.def_map(db).block_id().is_some() && prefixed.is_some() { cov_mark::hit!(prefixed_in_block_expression); prefixed = Some(PrefixKind::Plain); } } - match prefixed.map(PrefixKind::prefix) { Some(prefix) => best_path.or_else(|| { scope_name.map(|scope_name| ModPath::from_segments(prefix, Some(scope_name))) @@ -308,29 +369,48 @@ fn find_path_inner_( } fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath { - if old_path.starts_with_std() && new_path.can_start_with_std() { - if prefer_no_std { - cov_mark::hit!(prefer_no_std_paths); - new_path - } else { - cov_mark::hit!(prefer_std_paths); - old_path + const STD_CRATES: [Name; 3] = [known::std, known::core, known::alloc]; + match (old_path.segments().first(), new_path.segments().first()) { + (Some(old), Some(new)) if STD_CRATES.contains(old) && STD_CRATES.contains(new) => { + let rank = match prefer_no_std { + false => |name: &Name| match name { + name if name == &known::core => 0, + name if name == &known::alloc => 0, + name if name == &known::std => 1, + _ => unreachable!(), + }, + true => |name: &Name| match name { + name if name == &known::core => 2, + name if name == &known::alloc => 1, + name if name == &known::std => 0, + _ => unreachable!(), + }, + }; + let nrank = rank(new); + let orank = rank(old); + match nrank.cmp(&orank) { + Ordering::Less => old_path, + Ordering::Equal => { + if new_path.len() < old_path.len() { + new_path + } else { + old_path + } + } + Ordering::Greater => new_path, + } } - } else if new_path.starts_with_std() && old_path.can_start_with_std() { - if prefer_no_std { - cov_mark::hit!(prefer_no_std_paths); - old_path - } else { - cov_mark::hit!(prefer_std_paths); - new_path + _ => { + if new_path.len() < old_path.len() { + new_path + } else { + old_path + } } - } else if new_path.len() < old_path.len() { - new_path - } else { - old_path } } +// FIXME: Remove allocations /// Finds locations in `from.krate` from which `item` can be imported by `from`. fn find_local_import_locations( db: &dyn DefDatabase, @@ -490,8 +570,8 @@ $0 "#, "E::A", "E::A", - "E::A", - "E::A", + "crate::E::A", + "self::E::A", ); } @@ -810,7 +890,6 @@ pub use super::foo; #[test] fn prefer_std_paths_over_alloc() { - cov_mark::check!(prefer_std_paths); check_found_path( r#" //- /main.rs crate:main deps:alloc,std @@ -835,7 +914,6 @@ pub mod sync { #[test] fn prefer_core_paths_over_std() { - cov_mark::check!(prefer_no_std_paths); check_found_path( r#" //- /main.rs crate:main deps:core,std diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index a11a92204c..a40656fd6a 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -457,8 +457,15 @@ impl ItemInNs { /// Returns the crate defining this item (or `None` if `self` is built-in). pub fn krate(&self, db: &dyn DefDatabase) -> Option { match self { - ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate), + ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db).map(|m| m.krate), ItemInNs::Macros(id) => Some(id.module(db).krate), } } + + pub fn module(&self, db: &dyn DefDatabase) -> Option { + match self { + ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db), + ItemInNs::Macros(id) => Some(id.module(db)), + } + } } diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 7dd891c86e..b5974a0cfc 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -585,9 +585,9 @@ impl Module { self, db: &dyn DefDatabase, item: impl Into, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { - hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_core) + hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_no_std) } /// Finds a path that can be used to refer to the given item from within @@ -597,14 +597,14 @@ impl Module { db: &dyn DefDatabase, item: impl Into, prefix_kind: PrefixKind, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { hir_def::find_path::find_path_prefixed( db, item.into().into(), self.into(), prefix_kind, - prefer_core, + prefer_no_std, ) } } diff --git a/crates/ide-assists/src/assist_config.rs b/crates/ide-assists/src/assist_config.rs index fe2dfca6d5..60d1588a44 100644 --- a/crates/ide-assists/src/assist_config.rs +++ b/crates/ide-assists/src/assist_config.rs @@ -13,5 +13,5 @@ pub struct AssistConfig { pub snippet_cap: Option, pub allowed: Option>, pub insert_use: InsertUseConfig, - pub prefer_core: bool, + pub prefer_no_std: bool, } diff --git a/crates/ide-assists/src/handlers/add_missing_match_arms.rs b/crates/ide-assists/src/handlers/add_missing_match_arms.rs index d4e21b778c..73f4db4e5f 100644 --- a/crates/ide-assists/src/handlers/add_missing_match_arms.rs +++ b/crates/ide-assists/src/handlers/add_missing_match_arms.rs @@ -87,7 +87,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) .into_iter() .filter_map(|variant| { Some(( - build_pat(ctx.db(), module, variant, ctx.config.prefer_core)?, + build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std)?, variant.should_be_hidden(ctx.db(), module.krate()), )) }) @@ -133,7 +133,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) .iter() .any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); let patterns = variants.into_iter().filter_map(|variant| { - build_pat(ctx.db(), module, variant, ctx.config.prefer_core) + build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std) }); (ast::Pat::from(make::tuple_pat(patterns)), is_hidden) @@ -354,12 +354,12 @@ fn build_pat( db: &RootDatabase, module: hir::Module, var: ExtendedVariant, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { match var { ExtendedVariant::Variant(var) => { let path = - mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_core)?); + mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_no_std)?); // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though let pat: ast::Pat = match var.source(db)?.value.kind() { diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index 88a6b8558c..e257218ba9 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -92,7 +92,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option< let mut proposed_imports = import_assets.search_for_imports( &ctx.sema, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_core, + ctx.config.prefer_no_std, ); if proposed_imports.is_empty() { return None; diff --git a/crates/ide-assists/src/handlers/convert_into_to_from.rs b/crates/ide-assists/src/handlers/convert_into_to_from.rs index e0c0e9a484..95d11abe8b 100644 --- a/crates/ide-assists/src/handlers/convert_into_to_from.rs +++ b/crates/ide-assists/src/handlers/convert_into_to_from.rs @@ -50,7 +50,7 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) - _ => return None, }; - mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_core)?) + mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_no_std)?) }; let dest_type = match &ast_trait { diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index 749d94d5a9..d6c8ea785f 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -152,7 +152,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op ctx.sema.db, ModuleDef::from(control_flow_enum), ctx.config.insert_use.prefix_kind, - ctx.config.prefer_core, + ctx.config.prefer_no_std, ); if let Some(mod_path) = mod_path { diff --git a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs index 431f7b3c0f..8d5cab283d 100644 --- a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs @@ -409,7 +409,7 @@ fn process_references( ctx.sema.db, *enum_module_def, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_core, + ctx.config.prefer_no_std, ); if let Some(mut mod_path) = mod_path { mod_path.pop_segment(); diff --git a/crates/ide-assists/src/handlers/generate_deref.rs b/crates/ide-assists/src/handlers/generate_deref.rs index cf4ed84281..8f4405a8c8 100644 --- a/crates/ide-assists/src/handlers/generate_deref.rs +++ b/crates/ide-assists/src/handlers/generate_deref.rs @@ -59,7 +59,7 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<( let module = ctx.sema.to_def(&strukt)?.module(ctx.db()); let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?; let trait_path = - module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?; + module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_no_std)?; let field_type = field.ty()?; let field_name = field.name()?; @@ -100,7 +100,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<() let module = ctx.sema.to_def(&strukt)?.module(ctx.db()); let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?; let trait_path = - module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?; + module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_no_std)?; let field_type = field.ty()?; let target = field.syntax().text_range(); diff --git a/crates/ide-assists/src/handlers/generate_new.rs b/crates/ide-assists/src/handlers/generate_new.rs index ceb7dac0fe..9cda74d9e0 100644 --- a/crates/ide-assists/src/handlers/generate_new.rs +++ b/crates/ide-assists/src/handlers/generate_new.rs @@ -63,7 +63,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option let type_path = current_module.find_use_path( ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?, - ctx.config.prefer_core, + ctx.config.prefer_no_std, )?; let expr = use_trivial_constructor( diff --git a/crates/ide-assists/src/handlers/qualify_method_call.rs b/crates/ide-assists/src/handlers/qualify_method_call.rs index cb81ebd228..e57d1d065d 100644 --- a/crates/ide-assists/src/handlers/qualify_method_call.rs +++ b/crates/ide-assists/src/handlers/qualify_method_call.rs @@ -47,7 +47,7 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) -> let receiver_path = current_module.find_use_path( ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?, - ctx.config.prefer_core, + ctx.config.prefer_no_std, )?; let qualify_candidate = QualifyCandidate::ImplMethod(ctx.sema.db, call, resolved_call); diff --git a/crates/ide-assists/src/handlers/qualify_path.rs b/crates/ide-assists/src/handlers/qualify_path.rs index 232cd39e8b..4b2af550bc 100644 --- a/crates/ide-assists/src/handlers/qualify_path.rs +++ b/crates/ide-assists/src/handlers/qualify_path.rs @@ -38,7 +38,7 @@ use crate::{ pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; let mut proposed_imports = - import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_core); + import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_no_std); if proposed_imports.is_empty() { return None; } diff --git a/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs b/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs index 04a1366327..9fd5e1886d 100644 --- a/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs +++ b/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs @@ -85,7 +85,7 @@ pub(crate) fn replace_derive_with_manual_impl( }) .flat_map(|trait_| { current_module - .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_core) + .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_no_std) .as_ref() .map(mod_path_to_ast) .zip(Some(trait_)) diff --git a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs index 533e1670a0..dbbc56958f 100644 --- a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs +++ b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs @@ -67,7 +67,7 @@ pub(crate) fn replace_qualified_name_with_use( ctx.sema.db, module, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_core, + ctx.config.prefer_no_std, ) }) .flatten(); diff --git a/crates/ide-assists/src/tests.rs b/crates/ide-assists/src/tests.rs index 4e589dc86a..258144bae3 100644 --- a/crates/ide-assists/src/tests.rs +++ b/crates/ide-assists/src/tests.rs @@ -29,7 +29,7 @@ pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig { group: true, skip_glob_imports: true, }, - prefer_core: false, + prefer_no_std: false, }; pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) { diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs index 89a971e544..97b90c62dd 100644 --- a/crates/ide-completion/src/completions.rs +++ b/crates/ide-completion/src/completions.rs @@ -551,9 +551,11 @@ fn enum_variants_with_paths( } for variant in variants { - if let Some(path) = - ctx.module.find_use_path(ctx.db, hir::ModuleDef::from(variant), ctx.config.prefer_core) - { + if let Some(path) = ctx.module.find_use_path( + ctx.db, + hir::ModuleDef::from(variant), + ctx.config.prefer_no_std, + ) { // Variants with trivial paths are already added by the existing completion logic, // so we should avoid adding these twice if path.segments().len() > 1 { diff --git a/crates/ide-completion/src/completions/expr.rs b/crates/ide-completion/src/completions/expr.rs index 1ccf33a96b..3192b21cfb 100644 --- a/crates/ide-completion/src/completions/expr.rs +++ b/crates/ide-completion/src/completions/expr.rs @@ -168,7 +168,7 @@ pub(crate) fn complete_expr_path( .find_use_path( ctx.db, hir::ModuleDef::from(strukt), - ctx.config.prefer_core, + ctx.config.prefer_no_std, ) .filter(|it| it.len() > 1); @@ -187,7 +187,11 @@ pub(crate) fn complete_expr_path( hir::Adt::Union(un) => { let path = ctx .module - .find_use_path(ctx.db, hir::ModuleDef::from(un), ctx.config.prefer_core) + .find_use_path( + ctx.db, + hir::ModuleDef::from(un), + ctx.config.prefer_no_std, + ) .filter(|it| it.len() > 1); acc.add_union_literal(ctx, un, path, None); diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index 528959943b..364969af9c 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -265,7 +265,7 @@ fn import_on_the_fly( .search_for_imports( &ctx.sema, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_core, + ctx.config.prefer_no_std, ) .into_iter() .filter(ns_filter) @@ -313,7 +313,7 @@ fn import_on_the_fly_pat_( .search_for_imports( &ctx.sema, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_core, + ctx.config.prefer_no_std, ) .into_iter() .filter(ns_filter) @@ -352,7 +352,7 @@ fn import_on_the_fly_method( let user_input_lowercased = potential_import_name.to_lowercase(); import_assets - .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_core) + .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_no_std) .into_iter() .filter(|import| { !ctx.is_item_hidden(&import.item_to_import) diff --git a/crates/ide-completion/src/config.rs b/crates/ide-completion/src/config.rs index 54ebce1eb7..a0f5e81b4f 100644 --- a/crates/ide-completion/src/config.rs +++ b/crates/ide-completion/src/config.rs @@ -17,7 +17,7 @@ pub struct CompletionConfig { pub callable: Option, pub snippet_cap: Option, pub insert_use: InsertUseConfig, - pub prefer_core: bool, + pub prefer_no_std: bool, pub snippets: Vec, } diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs index 7cefb6bb4a..8d21f4fce0 100644 --- a/crates/ide-completion/src/lib.rs +++ b/crates/ide-completion/src/lib.rs @@ -238,7 +238,7 @@ pub fn resolve_completion_edits( db, candidate, config.insert_use.prefix_kind, - config.prefer_core, + config.prefer_no_std, ) }) .find(|mod_path| mod_path.to_string() == full_import_path); diff --git a/crates/ide-completion/src/snippet.rs b/crates/ide-completion/src/snippet.rs index 2dc62bbdc6..f3b8eae4fe 100644 --- a/crates/ide-completion/src/snippet.rs +++ b/crates/ide-completion/src/snippet.rs @@ -178,7 +178,7 @@ fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option 1).then(|| LocatedImport::new(path.clone(), item, item, None))) }; diff --git a/crates/ide-completion/src/tests.rs b/crates/ide-completion/src/tests.rs index d24c914856..9e2beb9ee3 100644 --- a/crates/ide-completion/src/tests.rs +++ b/crates/ide-completion/src/tests.rs @@ -66,7 +66,7 @@ pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig { enable_private_editable: false, callable: Some(CallableSnippets::FillArguments), snippet_cap: SnippetCap::new(true), - prefer_core: false, + prefer_no_std: false, insert_use: InsertUseConfig { granularity: ImportGranularity::Crate, prefix_kind: PrefixKind::Plain, diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs index 53bc516109..40a6a3e897 100644 --- a/crates/ide-db/src/imports/import_assets.rs +++ b/crates/ide-db/src/imports/import_assets.rs @@ -212,20 +212,20 @@ impl ImportAssets { &self, sema: &Semantics<'_, RootDatabase>, prefix_kind: PrefixKind, - prefer_core: bool, + prefer_no_std: bool, ) -> Vec { let _p = profile::span("import_assets::search_for_imports"); - self.search_for(sema, Some(prefix_kind), prefer_core) + self.search_for(sema, Some(prefix_kind), prefer_no_std) } /// This may return non-absolute paths if a part of the returned path is already imported into scope. pub fn search_for_relative_paths( &self, sema: &Semantics<'_, RootDatabase>, - prefer_core: bool, + prefer_no_std: bool, ) -> Vec { let _p = profile::span("import_assets::search_for_relative_paths"); - self.search_for(sema, None, prefer_core) + self.search_for(sema, None, prefer_no_std) } pub fn path_fuzzy_name_to_exact(&mut self, case_sensitive: bool) { @@ -244,7 +244,7 @@ impl ImportAssets { &self, sema: &Semantics<'_, RootDatabase>, prefixed: Option, - prefer_core: bool, + prefer_no_std: bool, ) -> Vec { let _p = profile::span("import_assets::search_for"); @@ -255,7 +255,7 @@ impl ImportAssets { item_for_path_search(sema.db, item)?, &self.module_with_candidate, prefixed, - prefer_core, + prefer_no_std, ) }; @@ -568,12 +568,12 @@ fn get_mod_path( item_to_search: ItemInNs, module_with_candidate: &Module, prefixed: Option, - prefer_core: bool, + prefer_no_std: bool, ) -> Option { if let Some(prefix_kind) = prefixed { - module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_core) + module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_no_std) } else { - module_with_candidate.find_use_path(db, item_to_search, prefer_core) + module_with_candidate.find_use_path(db, item_to_search, prefer_no_std) } } diff --git a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs index 06073ca1b2..3034295196 100644 --- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -137,7 +137,7 @@ pub(crate) fn json_in_items( sema.db, it, config.insert_use.prefix_kind, - config.prefer_core, + config.prefer_no_std, ) { insert_use( &scope, @@ -153,7 +153,7 @@ pub(crate) fn json_in_items( sema.db, it, config.insert_use.prefix_kind, - config.prefer_core, + config.prefer_no_std, ) { insert_use( &scope, diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index 5a81a55d82..7f140eb6a7 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -124,7 +124,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option ExprFillDefaultMode::Default, }, insert_use: self.insert_use_config(), - prefer_core: self.data.imports_prefer_core, + prefer_no_std: self.data.imports_prefer_no_std, } } @@ -1138,7 +1138,7 @@ impl Config { CallableCompletionDef::None => None, }, insert_use: self.insert_use_config(), - prefer_core: self.data.imports_prefer_core, + prefer_no_std: self.data.imports_prefer_no_std, snippet_cap: SnippetCap::new(try_or_def!( self.caps .text_document @@ -1166,7 +1166,7 @@ impl Config { snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")), allowed: None, insert_use: self.insert_use_config(), - prefer_core: self.data.imports_prefer_core, + prefer_no_std: self.data.imports_prefer_no_std, } } diff --git a/crates/rust-analyzer/src/integrated_benchmarks.rs b/crates/rust-analyzer/src/integrated_benchmarks.rs index 5dbb64d7df..96b1cb6b12 100644 --- a/crates/rust-analyzer/src/integrated_benchmarks.rs +++ b/crates/rust-analyzer/src/integrated_benchmarks.rs @@ -145,7 +145,7 @@ fn integrated_completion_benchmark() { skip_glob_imports: true, }, snippets: Vec::new(), - prefer_core: false, + prefer_no_std: false, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; @@ -183,7 +183,7 @@ fn integrated_completion_benchmark() { skip_glob_imports: true, }, snippets: Vec::new(), - prefer_core: false, + prefer_no_std: false, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 2b02c64b66..e596e08f2c 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -353,10 +353,10 @@ Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-i -- Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. -- -[[rust-analyzer.imports.prefer.core]]rust-analyzer.imports.prefer.core (default: `false`):: +[[rust-analyzer.imports.prefer.no.std]]rust-analyzer.imports.prefer.no.std (default: `false`):: + -- -Prefer to use imports of the core crate over the std crate. +Prefer to unconditionally use imports of the core and alloc crate, over the std crate. -- [[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`):: + diff --git a/editors/code/package.json b/editors/code/package.json index cfba00d3ed..6aa74ce92a 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -798,8 +798,8 @@ "default": true, "type": "boolean" }, - "rust-analyzer.imports.prefer.core": { - "markdownDescription": "Prefer to use imports of the core crate over the std crate.", + "rust-analyzer.imports.prefer.no.std": { + "markdownDescription": "Prefer to unconditionally use imports of the core and alloc crate, over the std crate.", "default": false, "type": "boolean" }, From c407cc554ee8657081ae5357a05025d3eaca1184 Mon Sep 17 00:00:00 2001 From: Daniel Paoliello Date: Thu, 18 Aug 2022 14:41:17 -0700 Subject: [PATCH 29/42] Add cargo.extraEnv setting --- Cargo.lock | 1 + crates/flycheck/Cargo.toml | 1 + crates/flycheck/src/lib.rs | 10 ++++-- crates/project-model/src/build_scripts.rs | 2 ++ crates/project-model/src/cargo_workspace.rs | 36 +++++++++++++++---- crates/project-model/src/rustc_cfg.rs | 18 +++++++--- crates/project-model/src/sysroot.rs | 19 ++++++---- crates/project-model/src/tests.rs | 22 +++++++----- crates/project-model/src/workspace.rs | 24 ++++++++----- .../rust-analyzer/src/cli/analysis_stats.rs | 3 +- crates/rust-analyzer/src/cli/load_cargo.rs | 4 ++- crates/rust-analyzer/src/cli/lsif.rs | 3 +- crates/rust-analyzer/src/cli/scip.rs | 2 +- crates/rust-analyzer/src/config.rs | 23 +++++++++++- crates/rust-analyzer/src/handlers.rs | 2 ++ crates/rust-analyzer/src/reload.rs | 7 +++- docs/user/generated_config.adoc | 11 ++++++ editors/code/package.json | 10 ++++++ 18 files changed, 155 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9f10d92c4e..8c6d25f7e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -394,6 +394,7 @@ dependencies = [ "crossbeam-channel", "jod-thread", "paths", + "rustc-hash", "serde", "serde_json", "stdx", diff --git a/crates/flycheck/Cargo.toml b/crates/flycheck/Cargo.toml index d3d180ece5..688e790c53 100644 --- a/crates/flycheck/Cargo.toml +++ b/crates/flycheck/Cargo.toml @@ -13,6 +13,7 @@ doctest = false crossbeam-channel = "0.5.5" tracing = "0.1.35" cargo_metadata = "0.15.0" +rustc-hash = "1.1.0" serde = { version = "1.0.137", features = ["derive"] } serde_json = "1.0.81" jod-thread = "0.1.2" diff --git a/crates/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs index d9f4ef5b7f..fdc03f4053 100644 --- a/crates/flycheck/src/lib.rs +++ b/crates/flycheck/src/lib.rs @@ -12,6 +12,7 @@ use std::{ use crossbeam_channel::{never, select, unbounded, Receiver, Sender}; use paths::AbsPathBuf; +use rustc_hash::FxHashMap; use serde::Deserialize; use stdx::{process::streaming_output, JodChild}; @@ -30,10 +31,12 @@ pub enum FlycheckConfig { all_features: bool, features: Vec, extra_args: Vec, + extra_env: FxHashMap, }, CustomCommand { command: String, args: Vec, + extra_env: FxHashMap, }, } @@ -41,7 +44,7 @@ impl fmt::Display for FlycheckConfig { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command), - FlycheckConfig::CustomCommand { command, args } => { + FlycheckConfig::CustomCommand { command, args, .. } => { write!(f, "{} {}", command, args.join(" ")) } } @@ -256,6 +259,7 @@ impl FlycheckActor { all_features, extra_args, features, + extra_env, } => { let mut cmd = Command::new(toolchain::cargo()); cmd.arg(command); @@ -281,11 +285,13 @@ impl FlycheckActor { } } cmd.args(extra_args); + cmd.envs(extra_env); cmd } - FlycheckConfig::CustomCommand { command, args } => { + FlycheckConfig::CustomCommand { command, args, extra_env } => { let mut cmd = Command::new(command); cmd.args(args); + cmd.envs(extra_env); cmd } }; diff --git a/crates/project-model/src/build_scripts.rs b/crates/project-model/src/build_scripts.rs index 84e772d168..837ea01619 100644 --- a/crates/project-model/src/build_scripts.rs +++ b/crates/project-model/src/build_scripts.rs @@ -43,10 +43,12 @@ impl WorkspaceBuildScripts { if let Some([program, args @ ..]) = config.run_build_script_command.as_deref() { let mut cmd = Command::new(program); cmd.args(args); + cmd.envs(&config.extra_env); return cmd; } let mut cmd = Command::new(toolchain::cargo()); + cmd.envs(&config.extra_env); cmd.args(&["check", "--quiet", "--workspace", "--message-format=json"]); diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs index eed955b42d..736d80041b 100644 --- a/crates/project-model/src/cargo_workspace.rs +++ b/crates/project-model/src/cargo_workspace.rs @@ -2,6 +2,7 @@ use std::iter; use std::path::PathBuf; +use std::str::from_utf8; use std::{ops, process::Command}; use anyhow::{Context, Result}; @@ -98,6 +99,8 @@ pub struct CargoConfig { pub wrap_rustc_in_build_scripts: bool, pub run_build_script_command: Option>, + + pub extra_env: FxHashMap, } impl CargoConfig { @@ -263,8 +266,8 @@ impl CargoWorkspace { let target = config .target .clone() - .or_else(|| cargo_config_build_target(cargo_toml)) - .or_else(|| rustc_discover_host_triple(cargo_toml)); + .or_else(|| cargo_config_build_target(cargo_toml, config)) + .or_else(|| rustc_discover_host_triple(cargo_toml, config)); let mut meta = MetadataCommand::new(); meta.cargo_path(toolchain::cargo()); @@ -292,8 +295,27 @@ impl CargoWorkspace { // unclear whether cargo itself supports it. progress("metadata".to_string()); - let meta = - meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?; + fn exec_with_env( + command: &cargo_metadata::MetadataCommand, + extra_env: &FxHashMap, + ) -> Result { + let mut command = command.cargo_command(); + command.envs(extra_env); + let output = command.output()?; + if !output.status.success() { + return Err(cargo_metadata::Error::CargoMetadata { + stderr: String::from_utf8(output.stderr)?, + }); + } + let stdout = from_utf8(&output.stdout)? + .lines() + .find(|line| line.starts_with('{')) + .ok_or(cargo_metadata::Error::NoJson)?; + cargo_metadata::MetadataCommand::parse(stdout) + } + + let meta = exec_with_env(&meta, &config.extra_env) + .with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?; Ok(meta) } @@ -463,8 +485,9 @@ impl CargoWorkspace { } } -fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option { +fn rustc_discover_host_triple(cargo_toml: &ManifestPath, config: &CargoConfig) -> Option { let mut rustc = Command::new(toolchain::rustc()); + rustc.envs(&config.extra_env); rustc.current_dir(cargo_toml.parent()).arg("-vV"); tracing::debug!("Discovering host platform by {:?}", rustc); match utf8_stdout(rustc) { @@ -486,8 +509,9 @@ fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option { } } -fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option { +fn cargo_config_build_target(cargo_toml: &ManifestPath, config: &CargoConfig) -> Option { let mut cargo_config = Command::new(toolchain::cargo()); + cargo_config.envs(&config.extra_env); cargo_config .current_dir(cargo_toml.parent()) .args(&["-Z", "unstable-options", "config", "get", "build.target"]) diff --git a/crates/project-model/src/rustc_cfg.rs b/crates/project-model/src/rustc_cfg.rs index 17e244d064..486cb143b8 100644 --- a/crates/project-model/src/rustc_cfg.rs +++ b/crates/project-model/src/rustc_cfg.rs @@ -4,9 +4,13 @@ use std::process::Command; use anyhow::Result; -use crate::{cfg_flag::CfgFlag, utf8_stdout, ManifestPath}; +use crate::{cfg_flag::CfgFlag, utf8_stdout, CargoConfig, ManifestPath}; -pub(crate) fn get(cargo_toml: Option<&ManifestPath>, target: Option<&str>) -> Vec { +pub(crate) fn get( + cargo_toml: Option<&ManifestPath>, + target: Option<&str>, + config: &CargoConfig, +) -> Vec { let _p = profile::span("rustc_cfg::get"); let mut res = Vec::with_capacity(6 * 2 + 1); @@ -18,7 +22,7 @@ pub(crate) fn get(cargo_toml: Option<&ManifestPath>, target: Option<&str>) -> Ve } } - match get_rust_cfgs(cargo_toml, target) { + match get_rust_cfgs(cargo_toml, target, config) { Ok(rustc_cfgs) => { tracing::debug!( "rustc cfgs found: {:?}", @@ -35,9 +39,14 @@ pub(crate) fn get(cargo_toml: Option<&ManifestPath>, target: Option<&str>) -> Ve res } -fn get_rust_cfgs(cargo_toml: Option<&ManifestPath>, target: Option<&str>) -> Result { +fn get_rust_cfgs( + cargo_toml: Option<&ManifestPath>, + target: Option<&str>, + config: &CargoConfig, +) -> Result { if let Some(cargo_toml) = cargo_toml { let mut cargo_config = Command::new(toolchain::cargo()); + cargo_config.envs(&config.extra_env); cargo_config .current_dir(cargo_toml.parent()) .args(&["-Z", "unstable-options", "rustc", "--print", "cfg"]) @@ -52,6 +61,7 @@ fn get_rust_cfgs(cargo_toml: Option<&ManifestPath>, target: Option<&str>) -> Res } // using unstable cargo features failed, fall back to using plain rustc let mut cmd = Command::new(toolchain::rustc()); + cmd.envs(&config.extra_env); cmd.args(&["--print", "cfg", "-O"]); if let Some(target) = target { cmd.args(&["--target", target]); diff --git a/crates/project-model/src/sysroot.rs b/crates/project-model/src/sysroot.rs index 362bb0f5e7..3282719fef 100644 --- a/crates/project-model/src/sysroot.rs +++ b/crates/project-model/src/sysroot.rs @@ -10,7 +10,7 @@ use anyhow::{format_err, Result}; use la_arena::{Arena, Idx}; use paths::{AbsPath, AbsPathBuf}; -use crate::{utf8_stdout, ManifestPath}; +use crate::{utf8_stdout, CargoConfig, ManifestPath}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct Sysroot { @@ -67,18 +67,20 @@ impl Sysroot { self.crates.iter().map(|(id, _data)| id) } - pub fn discover(dir: &AbsPath) -> Result { + pub fn discover(dir: &AbsPath, config: &CargoConfig) -> Result { tracing::debug!("Discovering sysroot for {}", dir.display()); - let sysroot_dir = discover_sysroot_dir(dir)?; - let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir, dir)?; + let sysroot_dir = discover_sysroot_dir(dir, config)?; + let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir, dir, config)?; let res = Sysroot::load(sysroot_dir, sysroot_src_dir)?; Ok(res) } - pub fn discover_rustc(cargo_toml: &ManifestPath) -> Option { + pub fn discover_rustc(cargo_toml: &ManifestPath, config: &CargoConfig) -> Option { tracing::debug!("Discovering rustc source for {}", cargo_toml.display()); let current_dir = cargo_toml.parent(); - discover_sysroot_dir(current_dir).ok().and_then(|sysroot_dir| get_rustc_src(&sysroot_dir)) + discover_sysroot_dir(current_dir, config) + .ok() + .and_then(|sysroot_dir| get_rustc_src(&sysroot_dir)) } pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Result { @@ -144,8 +146,9 @@ impl Sysroot { } } -fn discover_sysroot_dir(current_dir: &AbsPath) -> Result { +fn discover_sysroot_dir(current_dir: &AbsPath, config: &CargoConfig) -> Result { let mut rustc = Command::new(toolchain::rustc()); + rustc.envs(&config.extra_env); rustc.current_dir(current_dir).args(&["--print", "sysroot"]); tracing::debug!("Discovering sysroot by {:?}", rustc); let stdout = utf8_stdout(rustc)?; @@ -155,6 +158,7 @@ fn discover_sysroot_dir(current_dir: &AbsPath) -> Result { fn discover_sysroot_src_dir( sysroot_path: &AbsPathBuf, current_dir: &AbsPath, + config: &CargoConfig, ) -> Result { if let Ok(path) = env::var("RUST_SRC_PATH") { let path = AbsPathBuf::try_from(path.as_str()) @@ -170,6 +174,7 @@ fn discover_sysroot_src_dir( get_rust_src(sysroot_path) .or_else(|| { let mut rustup = Command::new(toolchain::rustup()); + rustup.envs(&config.extra_env); rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]); utf8_stdout(rustup).ok()?; get_rust_src(sysroot_path) diff --git a/crates/project-model/src/tests.rs b/crates/project-model/src/tests.rs index 9ccb6e9101..bea624bd54 100644 --- a/crates/project-model/src/tests.rs +++ b/crates/project-model/src/tests.rs @@ -10,8 +10,8 @@ use paths::{AbsPath, AbsPathBuf}; use serde::de::DeserializeOwned; use crate::{ - CargoWorkspace, CfgOverrides, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot, - WorkspaceBuildScripts, + CargoConfig, CargoWorkspace, CfgOverrides, ProjectJson, ProjectJsonData, ProjectWorkspace, + Sysroot, WorkspaceBuildScripts, }; fn load_cargo(file: &str) -> CrateGraph { @@ -92,13 +92,17 @@ fn rooted_project_json(data: ProjectJsonData) -> ProjectJson { } fn to_crate_graph(project_workspace: ProjectWorkspace) -> CrateGraph { - project_workspace.to_crate_graph(&mut |_, _| Ok(Vec::new()), &mut { - let mut counter = 0; - move |_path| { - counter += 1; - Some(FileId(counter)) - } - }) + project_workspace.to_crate_graph( + &mut |_, _| Ok(Vec::new()), + &mut { + let mut counter = 0; + move |_path| { + counter += 1; + Some(FileId(counter)) + } + }, + &CargoConfig::default(), + ) } fn check_crate_graph(crate_graph: CrateGraph, expect: Expect) { diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs index 818bbed6af..bc4ab45dae 100644 --- a/crates/project-model/src/workspace.rs +++ b/crates/project-model/src/workspace.rs @@ -156,11 +156,12 @@ impl ProjectWorkspace { })?; let project_location = project_json.parent().to_path_buf(); let project_json = ProjectJson::new(&project_location, data); - ProjectWorkspace::load_inline(project_json, config.target.as_deref())? + ProjectWorkspace::load_inline(project_json, config.target.as_deref(), config)? } ProjectManifest::CargoToml(cargo_toml) => { let cargo_version = utf8_stdout({ let mut cmd = Command::new(toolchain::cargo()); + cmd.envs(&config.extra_env); cmd.arg("--version"); cmd })?; @@ -186,7 +187,7 @@ impl ProjectWorkspace { let sysroot = if config.no_sysroot { None } else { - Some(Sysroot::discover(cargo_toml.parent()).with_context(|| { + Some(Sysroot::discover(cargo_toml.parent(), config).with_context(|| { format!( "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?", cargo_toml.display() @@ -196,7 +197,7 @@ impl ProjectWorkspace { let rustc_dir = match &config.rustc_source { Some(RustcSource::Path(path)) => ManifestPath::try_from(path.clone()).ok(), - Some(RustcSource::Discover) => Sysroot::discover_rustc(&cargo_toml), + Some(RustcSource::Discover) => Sysroot::discover_rustc(&cargo_toml, config), None => None, }; @@ -216,7 +217,7 @@ impl ProjectWorkspace { None => None, }; - let rustc_cfg = rustc_cfg::get(Some(&cargo_toml), config.target.as_deref()); + let rustc_cfg = rustc_cfg::get(Some(&cargo_toml), config.target.as_deref(), config); let cfg_overrides = config.cfg_overrides(); ProjectWorkspace::Cargo { @@ -237,6 +238,7 @@ impl ProjectWorkspace { pub fn load_inline( project_json: ProjectJson, target: Option<&str>, + config: &CargoConfig, ) -> Result { let sysroot = match (project_json.sysroot.clone(), project_json.sysroot_src.clone()) { (Some(sysroot), Some(sysroot_src)) => Some(Sysroot::load(sysroot, sysroot_src)?), @@ -258,7 +260,7 @@ impl ProjectWorkspace { (None, None) => None, }; - let rustc_cfg = rustc_cfg::get(None, target); + let rustc_cfg = rustc_cfg::get(None, target, config); Ok(ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg }) } @@ -268,8 +270,9 @@ impl ProjectWorkspace { .first() .and_then(|it| it.parent()) .ok_or_else(|| format_err!("No detached files to load"))?, + &CargoConfig::default(), )?; - let rustc_cfg = rustc_cfg::get(None, None); + let rustc_cfg = rustc_cfg::get(None, None, &CargoConfig::default()); Ok(ProjectWorkspace::DetachedFiles { files: detached_files, sysroot, rustc_cfg }) } @@ -416,6 +419,7 @@ impl ProjectWorkspace { &self, load_proc_macro: &mut dyn FnMut(&str, &AbsPath) -> ProcMacroLoadResult, load: &mut dyn FnMut(&AbsPath) -> Option, + config: &CargoConfig, ) -> CrateGraph { let _p = profile::span("ProjectWorkspace::to_crate_graph"); @@ -426,6 +430,7 @@ impl ProjectWorkspace { load, project, sysroot, + config, ), ProjectWorkspace::Cargo { cargo, @@ -464,6 +469,7 @@ fn project_json_to_crate_graph( load: &mut dyn FnMut(&AbsPath) -> Option, project: &ProjectJson, sysroot: &Option, + config: &CargoConfig, ) -> CrateGraph { let mut crate_graph = CrateGraph::default(); let sysroot_deps = sysroot @@ -489,9 +495,9 @@ fn project_json_to_crate_graph( }; let target_cfgs = match krate.target.as_deref() { - Some(target) => { - cfg_cache.entry(target).or_insert_with(|| rustc_cfg::get(None, Some(target))) - } + Some(target) => cfg_cache + .entry(target) + .or_insert_with(|| rustc_cfg::get(None, Some(target), config)), None => &rustc_cfg, }; diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index f52e1e7512..80128e43fd 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -80,7 +80,8 @@ impl flags::AnalysisStats { Some(build_scripts_sw.elapsed()) }; - let (host, vfs, _proc_macro) = load_workspace(workspace, &load_cargo_config)?; + let (host, vfs, _proc_macro) = + load_workspace(workspace, &cargo_config, &load_cargo_config)?; let db = host.raw_database(); eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed()); eprint!(" (metadata {}", metadata_time); diff --git a/crates/rust-analyzer/src/cli/load_cargo.rs b/crates/rust-analyzer/src/cli/load_cargo.rs index 5d1c013c32..88953096e2 100644 --- a/crates/rust-analyzer/src/cli/load_cargo.rs +++ b/crates/rust-analyzer/src/cli/load_cargo.rs @@ -38,7 +38,7 @@ pub fn load_workspace_at( workspace.set_build_scripts(build_scripts) } - load_workspace(workspace, load_config) + load_workspace(workspace, cargo_config, load_config) } // Note: Since this function is used by external tools that use rust-analyzer as a library @@ -48,6 +48,7 @@ pub fn load_workspace_at( // these tools need access to `ProjectWorkspace`, too, which `load_workspace_at` hides. pub fn load_workspace( ws: ProjectWorkspace, + cargo_config: &CargoConfig, load_config: &LoadCargoConfig, ) -> Result<(AnalysisHost, vfs::Vfs, Option)> { let (sender, receiver) = unbounded(); @@ -75,6 +76,7 @@ pub fn load_workspace( vfs.set_file_contents(path.clone(), contents); vfs.file_id(&path) }, + cargo_config, ); let project_folders = ProjectFolders::new(&[ws], &[]); diff --git a/crates/rust-analyzer/src/cli/lsif.rs b/crates/rust-analyzer/src/cli/lsif.rs index 491c55a04f..79577bf78c 100644 --- a/crates/rust-analyzer/src/cli/lsif.rs +++ b/crates/rust-analyzer/src/cli/lsif.rs @@ -299,7 +299,8 @@ impl flags::Lsif { let workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?; - let (host, vfs, _proc_macro) = load_workspace(workspace, &load_cargo_config)?; + let (host, vfs, _proc_macro) = + load_workspace(workspace, &cargo_config, &load_cargo_config)?; let db = host.raw_database(); let analysis = host.analysis(); diff --git a/crates/rust-analyzer/src/cli/scip.rs b/crates/rust-analyzer/src/cli/scip.rs index 65cc993c45..05c16bb39e 100644 --- a/crates/rust-analyzer/src/cli/scip.rs +++ b/crates/rust-analyzer/src/cli/scip.rs @@ -40,7 +40,7 @@ impl flags::Scip { let workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?; - let (host, vfs, _) = load_workspace(workspace, &load_cargo_config)?; + let (host, vfs, _) = load_workspace(workspace, &cargo_config, &load_cargo_config)?; let db = host.raw_database(); let analysis = host.analysis(); diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index e0384e67d4..2cf7a3c85b 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -84,6 +84,9 @@ config_data! { /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to /// avoid checking unnecessary things. cargo_buildScripts_useRustcWrapper: bool = "true", + /// Extra environment variables that will be set when running cargo, rustc + /// or other commands within the workspace. Useful for setting RUSTFLAGS. + cargo_extraEnv: FxHashMap = "{}", /// List of features to activate. /// /// Set this to `"all"` to pass `--all-features` to cargo. @@ -105,6 +108,8 @@ config_data! { checkOnSave_enable: bool = "true", /// Extra arguments for `cargo check`. checkOnSave_extraArgs: Vec = "[]", + /// Extra environment variables that will be set when running `cargo check`. + checkOnSave_extraEnv: FxHashMap = "{}", /// List of features to activate. Defaults to /// `#rust-analyzer.cargo.features#`. /// @@ -934,6 +939,16 @@ impl Config { } } + pub fn extra_env(&self) -> &FxHashMap { + &self.data.cargo_extraEnv + } + + pub fn check_on_save_extra_env(&self) -> FxHashMap { + let mut extra_env = self.data.cargo_extraEnv.clone(); + extra_env.extend(self.data.checkOnSave_extraEnv.clone()); + extra_env + } + pub fn lru_capacity(&self) -> Option { self.data.lru_capacity } @@ -1003,6 +1018,7 @@ impl Config { unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()), wrap_rustc_in_build_scripts: self.data.cargo_buildScripts_useRustcWrapper, run_build_script_command: self.data.cargo_buildScripts_overrideCommand.clone(), + extra_env: self.data.cargo_extraEnv.clone(), } } @@ -1028,7 +1044,11 @@ impl Config { Some(args) if !args.is_empty() => { let mut args = args.clone(); let command = args.remove(0); - FlycheckConfig::CustomCommand { command, args } + FlycheckConfig::CustomCommand { + command, + args, + extra_env: self.check_on_save_extra_env(), + } } Some(_) | None => FlycheckConfig::CargoCommand { command: self.data.checkOnSave_command.clone(), @@ -1056,6 +1076,7 @@ impl Config { CargoFeatures::Listed(it) => it, }, extra_args: self.data.checkOnSave_extraArgs.clone(), + extra_env: self.check_on_save_extra_env(), }, }; Some(flycheck_config) diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index 7b486744da..d511ba347a 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs @@ -1786,6 +1786,7 @@ fn run_rustfmt( let mut command = match snap.config.rustfmt() { RustfmtConfig::Rustfmt { extra_args, enable_range_formatting } => { let mut cmd = process::Command::new(toolchain::rustfmt()); + cmd.envs(snap.config.extra_env()); cmd.args(extra_args); // try to chdir to the file so we can respect `rustfmt.toml` // FIXME: use `rustfmt --config-path` once @@ -1843,6 +1844,7 @@ fn run_rustfmt( } RustfmtConfig::CustomCommand { command, args } => { let mut cmd = process::Command::new(command); + cmd.envs(snap.config.extra_env()); cmd.args(args); cmd } diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs index e47f70fff3..4cf5de46c4 100644 --- a/crates/rust-analyzer/src/reload.rs +++ b/crates/rust-analyzer/src/reload.rs @@ -143,6 +143,7 @@ impl GlobalState { project_model::ProjectWorkspace::load_inline( it.clone(), cargo_config.target.as_deref(), + &cargo_config, ) } }) @@ -398,7 +399,11 @@ impl GlobalState { dummy_replacements.get(crate_name).map(|v| &**v).unwrap_or_default(), ) }; - crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load)); + crate_graph.extend(ws.to_crate_graph( + &mut load_proc_macro, + &mut load, + &self.config.cargo(), + )); } crate_graph }; diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc index 2b02c64b66..ffae3c105c 100644 --- a/docs/user/generated_config.adoc +++ b/docs/user/generated_config.adoc @@ -46,6 +46,12 @@ cargo check --quiet --workspace --message-format=json --all-targets Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to avoid checking unnecessary things. -- +[[rust-analyzer.cargo.extraEnv]]rust-analyzer.cargo.extraEnv (default: `{}`):: ++ +-- +Extra environment variables that will be set when running cargo, rustc +or other commands within the workspace. Useful for setting RUSTFLAGS. +-- [[rust-analyzer.cargo.features]]rust-analyzer.cargo.features (default: `[]`):: + -- @@ -93,6 +99,11 @@ Run specified `cargo check` command for diagnostics on save. -- Extra arguments for `cargo check`. -- +[[rust-analyzer.checkOnSave.extraEnv]]rust-analyzer.checkOnSave.extraEnv (default: `{}`):: ++ +-- +Extra environment variables that will be set when running `cargo check`. +-- [[rust-analyzer.checkOnSave.features]]rust-analyzer.checkOnSave.features (default: `null`):: + -- diff --git a/editors/code/package.json b/editors/code/package.json index cfba00d3ed..394222e73a 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -437,6 +437,11 @@ "default": true, "type": "boolean" }, + "rust-analyzer.cargo.extraEnv": { + "markdownDescription": "Extra environment variables that will be set when running cargo, rustc\nor other commands within the workspace. Useful for setting RUSTFLAGS.", + "default": {}, + "type": "object" + }, "rust-analyzer.cargo.features": { "markdownDescription": "List of features to activate.\n\nSet this to `\"all\"` to pass `--all-features` to cargo.", "default": [], @@ -509,6 +514,11 @@ "type": "string" } }, + "rust-analyzer.checkOnSave.extraEnv": { + "markdownDescription": "Extra environment variables that will be set when running `cargo check`.", + "default": {}, + "type": "object" + }, "rust-analyzer.checkOnSave.features": { "markdownDescription": "List of features to activate. Defaults to\n`#rust-analyzer.cargo.features#`.\n\nSet to `\"all\"` to pass `--all-features` to Cargo.", "default": null, From 5e2f9e322fbb886c51b0baf8c0653acd56329d48 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 14 Sep 2022 23:22:38 +0200 Subject: [PATCH 30/42] mbe: Return Bindings from build_inner --- crates/mbe/src/expander/matcher.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index c1aa14d6b7..0d970504da 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -203,12 +203,11 @@ impl BindingsBuilder { } fn build(self, idx: &BindingsIdx) -> Bindings { - let mut bindings = Bindings::default(); - self.build_inner(&mut bindings, &self.nodes[idx.0]); - bindings + self.build_inner(&self.nodes[idx.0]) } - fn build_inner(&self, bindings: &mut Bindings, link_nodes: &[LinkNode>]) { + fn build_inner(&self, link_nodes: &[LinkNode>]) -> Bindings { + let mut bindings = Bindings::default(); let mut nodes = Vec::new(); self.collect_nodes(link_nodes, &mut nodes); @@ -246,6 +245,8 @@ impl BindingsBuilder { } } } + + bindings } fn collect_nested_ref<'a>( @@ -270,8 +271,7 @@ impl BindingsBuilder { nested_refs.push(last); nested_refs.into_iter().for_each(|iter| { - let mut child_bindings = Bindings::default(); - self.build_inner(&mut child_bindings, iter); + let child_bindings = self.build_inner(iter); nested.push(child_bindings) }) } From f7f6d2870fb930a67fe5622704953822521ddeb9 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 14 Sep 2022 23:26:24 +0200 Subject: [PATCH 31/42] mbe: Use extend instead of push in loop --- crates/mbe/src/expander/matcher.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index 0d970504da..05b8636b8c 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -269,11 +269,7 @@ impl BindingsBuilder { LinkNode::Parent { idx, len } => self.collect_nested_ref(idx, len, &mut nested_refs), }); nested_refs.push(last); - - nested_refs.into_iter().for_each(|iter| { - let child_bindings = self.build_inner(iter); - nested.push(child_bindings) - }) + nested.extend(nested_refs.into_iter().map(|iter| self.build_inner(iter))); } fn collect_nodes_ref<'a>( From b6aed7914d8172937664caf089ebe723504413cc Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 14 Sep 2022 23:30:44 +0200 Subject: [PATCH 32/42] mbe: Remove double reference in container --- crates/mbe/src/expander/matcher.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index 05b8636b8c..7157d8b432 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -212,7 +212,7 @@ impl BindingsBuilder { self.collect_nodes(link_nodes, &mut nodes); for cmd in nodes { - match &**cmd { + match cmd { BindingKind::Empty(name) => { bindings.push_empty(name); } @@ -272,12 +272,7 @@ impl BindingsBuilder { nested.extend(nested_refs.into_iter().map(|iter| self.build_inner(iter))); } - fn collect_nodes_ref<'a>( - &'a self, - id: usize, - len: usize, - nodes: &mut Vec<&'a Rc>, - ) { + fn collect_nodes_ref<'a>(&'a self, id: usize, len: usize, nodes: &mut Vec<&'a BindingKind>) { self.nodes[id].iter().take(len).for_each(|it| match it { LinkNode::Node(it) => nodes.push(it), LinkNode::Parent { idx, len } => self.collect_nodes_ref(*idx, *len, nodes), @@ -287,7 +282,7 @@ impl BindingsBuilder { fn collect_nodes<'a>( &'a self, link_nodes: &'a [LinkNode>], - nodes: &mut Vec<&'a Rc>, + nodes: &mut Vec<&'a BindingKind>, ) { link_nodes.iter().for_each(|it| match it { LinkNode::Node(it) => nodes.push(it), From 54305545a5c67484f13eb659ed7900d6a1cd6aec Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 14 Sep 2022 23:35:12 +0200 Subject: [PATCH 33/42] mbe: Remove Vec reference in container --- crates/mbe/src/expander/matcher.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index 7157d8b432..e9b0aff661 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -253,7 +253,7 @@ impl BindingsBuilder { &'a self, id: usize, len: usize, - nested_refs: &mut Vec<&'a Vec>>>, + nested_refs: &mut Vec<&'a [LinkNode>]>, ) { self.nested[id].iter().take(len).for_each(|it| match it { LinkNode::Node(id) => nested_refs.push(&self.nodes[*id]), @@ -263,7 +263,7 @@ impl BindingsBuilder { fn collect_nested(&self, idx: usize, nested_idx: usize, nested: &mut Vec) { let last = &self.nodes[idx]; - let mut nested_refs = Vec::new(); + let mut nested_refs: Vec<&[_]> = Vec::new(); self.nested[nested_idx].iter().for_each(|it| match *it { LinkNode::Node(idx) => nested_refs.push(&self.nodes[idx]), LinkNode::Parent { idx, len } => self.collect_nested_ref(idx, len, &mut nested_refs), From d6f0fd04ee2b6afcb93912f7531fbf2957f93909 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 14 Sep 2022 23:42:11 +0200 Subject: [PATCH 34/42] mbe: Remove unnecessary reference to usize --- crates/mbe/src/expander/matcher.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index e9b0aff661..7308280280 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -393,7 +393,7 @@ fn match_loop_inner<'t>( // Check if we need a separator. // We check the separator one by one - let sep_idx = *item.sep_parsed.as_ref().unwrap_or(&0); + let sep_idx = item.sep_parsed.unwrap_or(0); let sep_len = item.sep.as_ref().map_or(0, Separator::tt_count); if item.sep.is_some() && sep_idx != sep_len { let sep = item.sep.as_ref().unwrap(); From c4a87ee0cefb57640a9d5219d221e8578a1e6733 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 14 Sep 2022 23:49:08 +0200 Subject: [PATCH 35/42] mbe: Remove unneeded unwrap --- crates/mbe/src/expander/matcher.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs index 7308280280..139a8cb8cb 100644 --- a/crates/mbe/src/expander/matcher.rs +++ b/crates/mbe/src/expander/matcher.rs @@ -377,10 +377,10 @@ fn match_loop_inner<'t>( let op = match item.dot.peek() { None => { // We are at or past the end of the matcher of `item`. - if item.up.is_some() { + if let Some(up) = &item.up { if item.sep_parsed.is_none() { // Get the `up` matcher - let mut new_pos = *item.up.clone().unwrap(); + let mut new_pos = (**up).clone(); new_pos.bindings = bindings_builder.copy(&new_pos.bindings); // Add matches from this repetition to the `matches` of `up` bindings_builder.push_nested(&mut new_pos.bindings, &item.bindings); From a9f103e2fa1451ca13cd9393f6634301492d4621 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 15 Sep 2022 12:12:22 +0200 Subject: [PATCH 36/42] Fix prelude injection --- crates/hir-def/src/nameres/collector.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs index 495bbe4579..9242b48c59 100644 --- a/crates/hir-def/src/nameres/collector.rs +++ b/crates/hir-def/src/nameres/collector.rs @@ -534,6 +534,7 @@ impl DefCollector<'_> { match per_ns.types { Some((ModuleDefId::ModuleId(m), _)) => { self.def_map.prelude = Some(m); + break; } types => { tracing::debug!( From e7abf34c1984196aadc3b3ee6e95887e22b68dea Mon Sep 17 00:00:00 2001 From: Mathew Horner Date: Thu, 15 Sep 2022 20:25:29 -0500 Subject: [PATCH 37/42] Fix add reference action on macros. --- .../src/handlers/type_mismatch.rs | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/crates/ide-diagnostics/src/handlers/type_mismatch.rs index 6bf90e645b..937f98f479 100644 --- a/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -59,9 +59,6 @@ fn add_reference( d: &hir::TypeMismatch, acc: &mut Vec, ) -> Option<()> { - let root = ctx.sema.db.parse_or_expand(d.expr.file_id)?; - let expr_node = d.expr.value.to_node(&root); - let range = ctx.sema.diagnostics_display_range(d.expr.clone().map(|it| it.into())).range; let (_, mutability) = d.expected.as_reference()?; @@ -72,7 +69,7 @@ fn add_reference( let ampersands = format!("&{}", mutability.as_keyword_for_ref()); - let edit = TextEdit::insert(expr_node.syntax().text_range().start(), ampersands); + let edit = TextEdit::insert(range.start(), ampersands); let source_change = SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), edit); acc.push(fix("add_reference_here", "Add reference here", source_change, range)); @@ -314,6 +311,34 @@ fn main() { ); } + #[test] + fn test_add_reference_to_macro_call() { + check_fix( + r#" +macro_rules! hello_world { + () => { + "Hello World".to_string() + }; +} +fn test(foo: &String) {} +fn main() { + test($0hello_world!()); +} + "#, + r#" +macro_rules! hello_world { + () => { + "Hello World".to_string() + }; +} +fn test(foo: &String) {} +fn main() { + test(&hello_world!()); +} + "#, + ); + } + #[test] fn test_add_mutable_reference_to_let_stmt() { check_fix( From ad17ba12d1a9985a7b8bc52060942149ffb18b69 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 16 Sep 2022 16:11:58 +0200 Subject: [PATCH 38/42] Complete variants and assoc items in path pattern through type aliases --- .../ide-completion/src/completions/pattern.rs | 1 + crates/ide-completion/src/tests/pattern.rs | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/crates/ide-completion/src/completions/pattern.rs b/crates/ide-completion/src/completions/pattern.rs index 71d2d9d434..58d5bf114c 100644 --- a/crates/ide-completion/src/completions/pattern.rs +++ b/crates/ide-completion/src/completions/pattern.rs @@ -145,6 +145,7 @@ pub(crate) fn complete_pattern_path( u.ty(ctx.db) } hir::PathResolution::Def(hir::ModuleDef::BuiltinType(ty)) => ty.ty(ctx.db), + hir::PathResolution::Def(hir::ModuleDef::TypeAlias(ty)) => ty.ty(ctx.db), _ => return, }; diff --git a/crates/ide-completion/src/tests/pattern.rs b/crates/ide-completion/src/tests/pattern.rs index 85c4dbd662..db8bef6640 100644 --- a/crates/ide-completion/src/tests/pattern.rs +++ b/crates/ide-completion/src/tests/pattern.rs @@ -714,3 +714,30 @@ impl Ty { "#]], ); } + +#[test] +fn through_alias() { + check_empty( + r#" +enum Enum { + Unit, + Tuple(T), +} + +type EnumAlias = Enum; + +fn f(x: EnumAlias) { + match x { + EnumAlias::$0 => (), + _ => (), + } + +} + +"#, + expect![[r#" + bn Tuple(…) Tuple($1)$0 + bn Unit Unit$0 + "#]], + ); +} From b73fa0be9c4f7e36e37443bcc35453a44ce24c92 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 16 Sep 2022 16:26:54 +0200 Subject: [PATCH 39/42] Use memmem when searching for usages in ide-db --- Cargo.lock | 1 + crates/ide-db/Cargo.toml | 1 + crates/ide-db/src/search.rs | 30 +++++++++++++++++++----------- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9f10d92c4e..eaadcc8b8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -660,6 +660,7 @@ dependencies = [ "indexmap", "itertools", "limit", + "memchr", "once_cell", "parser", "profile", diff --git a/crates/ide-db/Cargo.toml b/crates/ide-db/Cargo.toml index a1b0bd6cb3..30272bc16f 100644 --- a/crates/ide-db/Cargo.toml +++ b/crates/ide-db/Cargo.toml @@ -20,6 +20,7 @@ either = "1.7.0" itertools = "0.10.3" arrayvec = "0.7.2" indexmap = "1.9.1" +memchr = "2.5.0" stdx = { path = "../stdx", version = "0.0.0" } parser = { path = "../parser", version = "0.0.0" } diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs index 6f885fba78..7cabdb55e8 100644 --- a/crates/ide-db/src/search.rs +++ b/crates/ide-db/src/search.rs @@ -8,6 +8,7 @@ use std::{mem, sync::Arc}; use base_db::{FileId, FileRange, SourceDatabase, SourceDatabaseExt}; use hir::{DefWithBody, HasAttrs, HasSource, InFile, ModuleSource, Semantics, Visibility}; +use memchr::memmem::Finder; use once_cell::unsync::Lazy; use parser::SyntaxKind; use stdx::hash::NoHashHashMap; @@ -411,14 +412,17 @@ impl<'a> FindUsages<'a> { Some(s) => s.as_str(), None => return, }; + let finder = &Finder::new(name); + let include_self_kw_refs = + self.include_self_kw_refs.as_ref().map(|ty| (ty, Finder::new("Self"))); - // these can't be closures because rust infers the lifetimes wrong ... + // for<'a> |text: &'a str, name: &'a str, search_range: TextRange| -> impl Iterator + 'a { ... } fn match_indices<'a>( text: &'a str, - name: &'a str, + finder: &'a Finder<'a>, search_range: TextRange, ) -> impl Iterator + 'a { - text.match_indices(name).filter_map(move |(idx, _)| { + finder.find_iter(text.as_bytes()).filter_map(move |idx| { let offset: TextSize = idx.try_into().unwrap(); if !search_range.contains_inclusive(offset) { return None; @@ -427,6 +431,7 @@ impl<'a> FindUsages<'a> { }) } + // for<'a> |scope: &'a SearchScope| -> impl Iterator, FileId, TextRange)> + 'a { ... } fn scope_files<'a>( sema: &'a Semantics<'_, RootDatabase>, scope: &'a SearchScope, @@ -450,7 +455,7 @@ impl<'a> FindUsages<'a> { let tree = Lazy::new(move || sema.parse(file_id).syntax().clone()); // Search for occurrences of the items name - for offset in match_indices(&text, name, search_range) { + for offset in match_indices(&text, finder, search_range) { for name in sema.find_nodes_at_offset_with_descend(&tree, offset) { if match name { ast::NameLike::NameRef(name_ref) => self.found_name_ref(&name_ref, sink), @@ -462,8 +467,8 @@ impl<'a> FindUsages<'a> { } } // Search for occurrences of the `Self` referring to our type - if let Some(self_ty) = &self.include_self_kw_refs { - for offset in match_indices(&text, "Self", search_range) { + if let Some((self_ty, finder)) = &include_self_kw_refs { + for offset in match_indices(&text, finder, search_range) { for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) { if self.found_self_ty_name_ref(self_ty, &name_ref, sink) { return; @@ -479,20 +484,22 @@ impl<'a> FindUsages<'a> { let scope = search_scope .intersection(&SearchScope::module_and_children(self.sema.db, module)); - let is_crate_root = module.is_crate_root(self.sema.db); + let is_crate_root = + module.is_crate_root(self.sema.db).then(|| Finder::new("crate")); + let finder = &Finder::new("super"); for (text, file_id, search_range) in scope_files(sema, &scope) { let tree = Lazy::new(move || sema.parse(file_id).syntax().clone()); - for offset in match_indices(&text, "super", search_range) { + for offset in match_indices(&text, finder, search_range) { for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) { if self.found_name_ref(&name_ref, sink) { return; } } } - if is_crate_root { - for offset in match_indices(&text, "crate", search_range) { + if let Some(finder) = &is_crate_root { + for offset in match_indices(&text, finder, search_range) { for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) { if self.found_name_ref(&name_ref, sink) { return; @@ -533,8 +540,9 @@ impl<'a> FindUsages<'a> { search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(text.as_str()))); let tree = Lazy::new(|| sema.parse(file_id).syntax().clone()); + let finder = &Finder::new("self"); - for offset in match_indices(&text, "self", search_range) { + for offset in match_indices(&text, finder, search_range) { for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) { if self.found_self_module_name_ref(&name_ref, sink) { return; From a65ca20210b4cf82c32f11249208f990af3fb816 Mon Sep 17 00:00:00 2001 From: Mathew Horner Date: Fri, 16 Sep 2022 16:56:19 -0500 Subject: [PATCH 40/42] Fix tests by using primitive rather than String. --- .../src/handlers/type_mismatch.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/crates/ide-diagnostics/src/handlers/type_mismatch.rs index 937f98f479..62c69f90ba 100644 --- a/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -315,25 +315,25 @@ fn main() { fn test_add_reference_to_macro_call() { check_fix( r#" -macro_rules! hello_world { +macro_rules! thousand { () => { - "Hello World".to_string() + 1000_u64 }; } -fn test(foo: &String) {} +fn test(foo: &u64) {} fn main() { - test($0hello_world!()); + test($0thousand!()); } "#, r#" -macro_rules! hello_world { +macro_rules! thousand { () => { - "Hello World".to_string() + 1000_u64 }; } -fn test(foo: &String) {} +fn test(foo: &u64) {} fn main() { - test(&hello_world!()); + test(&thousand!()); } "#, ); From 0d9f97166ba546ceaded21dc62450859d3dc9f92 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Sun, 18 Sep 2022 19:44:38 +0200 Subject: [PATCH 41/42] Simplify --- crates/hir-def/src/item_scope.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index a40656fd6a..7721221c44 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -18,7 +18,7 @@ use crate::{ ConstId, HasModule, ImplId, LocalModuleId, MacroId, ModuleDefId, ModuleId, TraitId, }; -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub(crate) enum ImportType { Glob, Named, @@ -302,13 +302,13 @@ impl ItemScope { $changed = true; } Entry::Occupied(mut entry) - if $glob_imports.$field.contains(&$lookup) - && matches!($def_import_type, ImportType::Named) => + if matches!($def_import_type, ImportType::Named) => { - cov_mark::hit!(import_shadowed); - $glob_imports.$field.remove(&$lookup); - entry.insert(fld); - $changed = true; + if $glob_imports.$field.remove(&$lookup) { + cov_mark::hit!(import_shadowed); + entry.insert(fld); + $changed = true; + } } _ => {} } From e54f61dbdb9183cc5fdf58cd098dd783178bc3b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Mon, 19 Sep 2022 12:45:38 +0300 Subject: [PATCH 42/42] Try to fix crash introduced in #13147 --- crates/hir-ty/src/method_resolution.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index dbf2750032..41fcef73d9 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -989,17 +989,18 @@ fn iterate_inherent_methods( )?; } TyKind::Dyn(_) => { - let principal_trait = self_ty.dyn_trait().unwrap(); - let traits = all_super_traits(db.upcast(), principal_trait); - iterate_inherent_trait_methods( - self_ty, - table, - name, - receiver_ty, - receiver_adjustments.clone(), - callback, - traits.into_iter(), - )?; + if let Some(principal_trait) = self_ty.dyn_trait() { + let traits = all_super_traits(db.upcast(), principal_trait); + iterate_inherent_trait_methods( + self_ty, + table, + name, + receiver_ty, + receiver_adjustments.clone(), + callback, + traits.into_iter(), + )?; + } } _ => {} }