diff --git a/crates/ide-db/src/imports/insert_use.rs b/crates/ide-db/src/imports/insert_use.rs index a19969ecc4a..66d0b2ee82c 100644 --- a/crates/ide-db/src/imports/insert_use.rs +++ b/crates/ide-db/src/imports/insert_use.rs @@ -8,7 +8,7 @@ use syntax::{ algo, ast::{self, make, AstNode, HasAttrs, HasModuleItem, HasVisibility, PathSegmentKind}, - ted, AstToken, Direction, NodeOrToken, SyntaxNode, SyntaxToken, + ted, Direction, NodeOrToken, SyntaxKind, SyntaxNode, }; use crate::{ @@ -397,12 +397,16 @@ fn insert_use_( } // there are no imports in this file at all + // so put the import after all inner module attributes and possible license header comments if let Some(last_inner_element) = scope_syntax .children_with_tokens() - .filter(|child| match child { + .take_while(|child| match child { NodeOrToken::Node(node) => is_inner_attribute(node.clone()), - NodeOrToken::Token(token) => is_comment(token.clone()), + NodeOrToken::Token(token) => { + [SyntaxKind::WHITESPACE, SyntaxKind::COMMENT].contains(&token.kind()) + } }) + .filter(|child| child.as_token().map_or(true, |t| t.kind() != SyntaxKind::WHITESPACE)) .last() { cov_mark::hit!(insert_empty_inner_attr); @@ -439,7 +443,3 @@ fn insert_use_( fn is_inner_attribute(node: SyntaxNode) -> bool { ast::Attr::cast(node).map(|attr| attr.kind()) == Some(ast::AttrKind::Inner) } - -fn is_comment(token: SyntaxToken) -> bool { - ast::Comment::cast(token).is_some() -} diff --git a/crates/ide-db/src/imports/insert_use/tests.rs b/crates/ide-db/src/imports/insert_use/tests.rs index acadb353b6a..6569e4ed8c6 100644 --- a/crates/ide-db/src/imports/insert_use/tests.rs +++ b/crates/ide-db/src/imports/insert_use/tests.rs @@ -5,6 +5,24 @@ use super::*; +#[test] +fn trailing_comment_in_empty_file() { + check( + "foo::bar", + r#" +struct Struct; +// 0 = 1 +"#, + r#" +use foo::bar; + +struct Struct; +// 0 = 1 +"#, + ImportGranularity::Crate, + ); +} + #[test] fn respects_cfg_attr_fn() { check(