Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
44612c5
docs: add documentation for find_all_refs constructor search (#10725)
vremyavnikuda May 25, 2025
1e8eacd
fix: the lines are formatted according to clippy
vremyavnikuda May 25, 2025
693ff34
fix: the lines are formatted according to clippy
vremyavnikuda May 25, 2025
57707c2
fix: formated to clippy
vremyavnikuda May 26, 2025
430f75a
docs:deleting duplicate documentation
vremyavnikuda May 28, 2025
d2bc368
fix: Recognize salsa cycles in `thread_result_to_response`
Veykril May 28, 2025
f06e376
Merge pull request #19888 from Veykril/push-wylsryzpnnop
Veykril May 29, 2025
087cfe3
fix: Fix import insertion not being fully cfg aware
Veykril May 28, 2025
23738b5
Merge pull request #19890 from Veykril/push-kzzntrpllsqx
Veykril May 29, 2025
8d958aa
Merge pull request #19861 from vremyavnikuda/docs/find-all-refs-const…
Veykril May 30, 2025
1b809b7
Add some more `hir_expand::files` conversions
Veykril May 30, 2025
1383bca
internal: Restructure some semantics APIs for virtual macro files
Veykril May 30, 2025
deeb464
Merge pull request #19896 from Veykril/push-qyutrlxyznum
Veykril May 30, 2025
ed508c7
refactor: Remove unncessary duplication in highlight_related
Veykril May 31, 2025
9c45a45
Merge pull request #19898 from Veykril/push-ykumpuwmuvmu
Veykril May 31, 2025
1b9fb33
Account for `Generate` actions when filtering the allowed ones
SomeoneToIgnore May 31, 2025
cac7468
Merge pull request #19899 from SomeoneToIgnore/generate-actions
Veykril May 31, 2025
2428070
fix: Fix manual not containing diagnostics documentation
Veykril May 31, 2025
01a1908
Merge pull request #19900 from Veykril/push-zurosouxqxzz
Veykril May 31, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
format!("Import `{import_name}`"),
range,
|builder| {
let scope = match scope.clone() {
ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
};
let scope = builder.make_import_scope_mut(scope.clone());
insert_use(&scope, mod_path_to_ast(&import_path, edition), &ctx.config.insert_use);
},
);
Expand All @@ -153,11 +149,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
format!("Import `{import_name} as _`"),
range,
|builder| {
let scope = match scope.clone() {
ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
};
let scope = builder.make_import_scope_mut(scope.clone());
insert_use_as_alias(
&scope,
mod_path_to_ast(&import_path, edition),
Expand Down Expand Up @@ -1877,4 +1869,30 @@ fn main() {
",
);
}

#[test]
fn carries_cfg_attr() {
check_assist(
auto_import,
r#"
mod m {
pub struct S;
}
#[cfg(test)]
fn foo(_: S$0) {}
"#,
r#"
#[cfg(test)]
use m::S;
mod m {
pub struct S;
}
#[cfg(test)]
fn foo(_: S) {}
"#,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -312,12 +312,8 @@ fn replace_usages(
}

// add imports across modules where needed
if let Some((import_scope, path)) = import_data {
let scope = match import_scope {
ImportScope::File(it) => ImportScope::File(edit.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(edit.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(edit.make_mut(it)),
};
if let Some((scope, path)) = import_data {
let scope = edit.make_import_scope_mut(scope);
delayed_mutations.push((scope, path));
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -996,7 +996,8 @@ pub struct $0Foo {
}
"#,
r#"
pub struct Foo(#[my_custom_attr] u32);
pub struct Foo(#[my_custom_attr]
u32);
"#,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -923,7 +923,8 @@ where
pub struct $0Foo(#[my_custom_attr] u32);
"#,
r#"
pub struct Foo { #[my_custom_attr] field1: u32 }
pub struct Foo { #[my_custom_attr]
field1: u32 }
"#,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
.kind
.is_some_and(|kind| matches!(kind, FlowKind::Break(_, _) | FlowKind::Continue(_)))
{
let scope = match scope {
ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
};

let scope = builder.make_import_scope_mut(scope);
let control_flow_enum =
FamousDefs(&ctx.sema, module.krate()).core_ops_ControlFlow();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,7 @@ pub(crate) fn replace_qualified_name_with_use(
|builder| {
// Now that we've brought the name into scope, re-qualify all paths that could be
// affected (that is, all paths inside the node we added the `use` to).
let scope = match scope {
ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
};
let scope = builder.make_import_scope_mut(scope);
shorten_paths(scope.as_syntax_node(), &original_path);
let path = drop_generic_args(&original_path);
let edition = ctx
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use ide_db::imports::insert_use::ImportScope;
use syntax::{
TextRange,
ast::{self, AstNode, HasArgList, prec::ExprPrecedence},
Expand Down Expand Up @@ -114,11 +113,7 @@ fn add_import(
);

if let Some(scope) = scope {
let scope = match scope {
ImportScope::File(it) => ImportScope::File(edit.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(edit.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(edit.make_mut(it)),
};
let scope = edit.make_import_scope_mut(scope);
ide_db::imports::insert_use::insert_use(&scope, import, &ctx.config.insert_use);
}
}
Expand Down
144 changes: 64 additions & 80 deletions src/tools/rust-analyzer/crates/ide-db/src/imports/insert_use.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,107 +60,87 @@ pub struct InsertUseConfig {
}

#[derive(Debug, Clone)]
pub enum ImportScope {
pub struct ImportScope {
pub kind: ImportScopeKind,
pub required_cfgs: Vec<ast::Attr>,
}

#[derive(Debug, Clone)]
pub enum ImportScopeKind {
File(ast::SourceFile),
Module(ast::ItemList),
Block(ast::StmtList),
}

impl ImportScope {
// FIXME: Remove this?
#[cfg(test)]
fn from(syntax: SyntaxNode) -> Option<Self> {
use syntax::match_ast;
fn contains_cfg_attr(attrs: &dyn HasAttrs) -> bool {
attrs.attrs().any(|attr| attr.as_simple_call().is_some_and(|(ident, _)| ident == "cfg"))
}
match_ast! {
match syntax {
ast::Module(module) => module.item_list().map(ImportScope::Module),
ast::SourceFile(file) => Some(ImportScope::File(file)),
ast::Fn(func) => contains_cfg_attr(&func).then(|| func.body().and_then(|it| it.stmt_list().map(ImportScope::Block))).flatten(),
ast::Const(konst) => contains_cfg_attr(&konst).then(|| match konst.body()? {
ast::Expr::BlockExpr(block) => Some(block),
_ => None,
}).flatten().and_then(|it| it.stmt_list().map(ImportScope::Block)),
ast::Static(statik) => contains_cfg_attr(&statik).then(|| match statik.body()? {
ast::Expr::BlockExpr(block) => Some(block),
_ => None,
}).flatten().and_then(|it| it.stmt_list().map(ImportScope::Block)),
_ => None,

}
}
}

/// Determines the containing syntax node in which to insert a `use` statement affecting `position`.
/// Returns the original source node inside attributes.
pub fn find_insert_use_container(
position: &SyntaxNode,
sema: &Semantics<'_, RootDatabase>,
) -> Option<Self> {
fn contains_cfg_attr(attrs: &dyn HasAttrs) -> bool {
attrs.attrs().any(|attr| attr.as_simple_call().is_some_and(|(ident, _)| ident == "cfg"))
}

// The closest block expression ancestor
let mut block = None;
let mut required_cfgs = Vec::new();
// Walk up the ancestor tree searching for a suitable node to do insertions on
// with special handling on cfg-gated items, in which case we want to insert imports locally
// or FIXME: annotate inserted imports with the same cfg
for syntax in sema.ancestors_with_macros(position.clone()) {
if let Some(file) = ast::SourceFile::cast(syntax.clone()) {
return Some(ImportScope::File(file));
} else if let Some(item) = ast::Item::cast(syntax) {
return match item {
ast::Item::Const(konst) if contains_cfg_attr(&konst) => {
// FIXME: Instead of bailing out with None, we should note down that
// this import needs an attribute added
match sema.original_ast_node(konst)?.body()? {
ast::Expr::BlockExpr(block) => block,
_ => return None,
return Some(ImportScope { kind: ImportScopeKind::File(file), required_cfgs });
} else if let Some(module) = ast::Module::cast(syntax.clone()) {
// early return is important here, if we can't find the original module
// in the input there is no way for us to insert an import anywhere.
return sema
.original_ast_node(module)?
.item_list()
.map(ImportScopeKind::Module)
.map(|kind| ImportScope { kind, required_cfgs });
} else if let Some(has_attrs) = ast::AnyHasAttrs::cast(syntax) {
if block.is_none() {
if let Some(b) = ast::BlockExpr::cast(has_attrs.syntax().clone()) {
if let Some(b) = sema.original_ast_node(b) {
block = b.stmt_list();
}
.stmt_list()
.map(ImportScope::Block)
}
ast::Item::Fn(func) if contains_cfg_attr(&func) => {
// FIXME: Instead of bailing out with None, we should note down that
// this import needs an attribute added
sema.original_ast_node(func)?.body()?.stmt_list().map(ImportScope::Block)
}
ast::Item::Static(statik) if contains_cfg_attr(&statik) => {
// FIXME: Instead of bailing out with None, we should note down that
// this import needs an attribute added
match sema.original_ast_node(statik)?.body()? {
ast::Expr::BlockExpr(block) => block,
_ => return None,
}
.stmt_list()
.map(ImportScope::Block)
}
ast::Item::Module(module) => {
// early return is important here, if we can't find the original module
// in the input there is no way for us to insert an import anywhere.
sema.original_ast_node(module)?.item_list().map(ImportScope::Module)
}
if has_attrs
.attrs()
.any(|attr| attr.as_simple_call().is_some_and(|(ident, _)| ident == "cfg"))
{
if let Some(b) = block {
return Some(ImportScope {
kind: ImportScopeKind::Block(b),
required_cfgs,
});
}
_ => continue,
};
required_cfgs.extend(has_attrs.attrs().filter(|attr| {
attr.as_simple_call().is_some_and(|(ident, _)| ident == "cfg")
}));
}
}
}
None
}

pub fn as_syntax_node(&self) -> &SyntaxNode {
match self {
ImportScope::File(file) => file.syntax(),
ImportScope::Module(item_list) => item_list.syntax(),
ImportScope::Block(block) => block.syntax(),
match &self.kind {
ImportScopeKind::File(file) => file.syntax(),
ImportScopeKind::Module(item_list) => item_list.syntax(),
ImportScopeKind::Block(block) => block.syntax(),
}
}

pub fn clone_for_update(&self) -> Self {
match self {
ImportScope::File(file) => ImportScope::File(file.clone_for_update()),
ImportScope::Module(item_list) => ImportScope::Module(item_list.clone_for_update()),
ImportScope::Block(block) => ImportScope::Block(block.clone_for_update()),
Self {
kind: match &self.kind {
ImportScopeKind::File(file) => ImportScopeKind::File(file.clone_for_update()),
ImportScopeKind::Module(item_list) => {
ImportScopeKind::Module(item_list.clone_for_update())
}
ImportScopeKind::Block(block) => ImportScopeKind::Block(block.clone_for_update()),
},
required_cfgs: self.required_cfgs.iter().map(|attr| attr.clone_for_update()).collect(),
}
}
}
Expand Down Expand Up @@ -216,6 +196,11 @@ fn insert_use_with_alias_option(
use_tree.wrap_in_tree_list();
}
let use_item = make::use_(None, use_tree).clone_for_update();
for attr in
scope.required_cfgs.iter().map(|attr| attr.syntax().clone_subtree().clone_for_update())
{
ted::insert(ted::Position::first_child_of(use_item.syntax()), attr);
}

// merge into existing imports if possible
if let Some(mb) = mb {
Expand All @@ -229,7 +214,6 @@ fn insert_use_with_alias_option(
}
}
}

// either we weren't allowed to merge or there is no import that fits the merge conditions
// so look for the place we have to insert to
insert_use_(scope, use_item, cfg.group);
Expand Down Expand Up @@ -316,10 +300,10 @@ fn guess_granularity_from_scope(scope: &ImportScope) -> ImportGranularityGuess {
}
_ => None,
};
let mut use_stmts = match scope {
ImportScope::File(f) => f.items(),
ImportScope::Module(m) => m.items(),
ImportScope::Block(b) => b.items(),
let mut use_stmts = match &scope.kind {
ImportScopeKind::File(f) => f.items(),
ImportScopeKind::Module(m) => m.items(),
ImportScopeKind::Block(b) => b.items(),
}
.filter_map(use_stmt);
let mut res = ImportGranularityGuess::Unknown;
Expand Down Expand Up @@ -463,12 +447,12 @@ fn insert_use_(scope: &ImportScope, use_item: ast::Use, group_imports: bool) {
}
}

let l_curly = match scope {
ImportScope::File(_) => None,
let l_curly = match &scope.kind {
ImportScopeKind::File(_) => None,
// don't insert the imports before the item list/block expr's opening curly brace
ImportScope::Module(item_list) => item_list.l_curly_token(),
ImportScopeKind::Module(item_list) => item_list.l_curly_token(),
// don't insert the imports before the item list's opening curly brace
ImportScope::Block(block) => block.l_curly_token(),
ImportScopeKind::Block(block) => block.l_curly_token(),
};
// there are no imports in this file at all
// so put the import after all inner module attributes and possible license header comments
Expand Down
Loading