Skip to content

Commit c42cb9a

Browse files
committed
Auto merge of #12197 - Veykril:insert-use-fix, r=Veykril
fix: Fix import insertion inserting after last comment in a file
2 parents 3d2d209 + c0feb38 commit c42cb9a

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

crates/ide-db/src/imports/insert_use.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use hir::Semantics;
88
use syntax::{
99
algo,
1010
ast::{self, make, AstNode, HasAttrs, HasModuleItem, HasVisibility, PathSegmentKind},
11-
ted, AstToken, Direction, NodeOrToken, SyntaxNode, SyntaxToken,
11+
ted, Direction, NodeOrToken, SyntaxKind, SyntaxNode,
1212
};
1313

1414
use crate::{
@@ -397,12 +397,16 @@ fn insert_use_(
397397
}
398398

399399
// there are no imports in this file at all
400+
// so put the import after all inner module attributes and possible license header comments
400401
if let Some(last_inner_element) = scope_syntax
401402
.children_with_tokens()
402-
.filter(|child| match child {
403+
.take_while(|child| match child {
403404
NodeOrToken::Node(node) => is_inner_attribute(node.clone()),
404-
NodeOrToken::Token(token) => is_comment(token.clone()),
405+
NodeOrToken::Token(token) => {
406+
[SyntaxKind::WHITESPACE, SyntaxKind::COMMENT].contains(&token.kind())
407+
}
405408
})
409+
.filter(|child| child.as_token().map_or(true, |t| t.kind() != SyntaxKind::WHITESPACE))
406410
.last()
407411
{
408412
cov_mark::hit!(insert_empty_inner_attr);
@@ -439,7 +443,3 @@ fn insert_use_(
439443
fn is_inner_attribute(node: SyntaxNode) -> bool {
440444
ast::Attr::cast(node).map(|attr| attr.kind()) == Some(ast::AttrKind::Inner)
441445
}
442-
443-
fn is_comment(token: SyntaxToken) -> bool {
444-
ast::Comment::cast(token).is_some()
445-
}

crates/ide-db/src/imports/insert_use/tests.rs

+18
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,24 @@ use test_utils::{assert_eq_text, CURSOR_MARKER};
55

66
use super::*;
77

8+
#[test]
9+
fn trailing_comment_in_empty_file() {
10+
check(
11+
"foo::bar",
12+
r#"
13+
struct Struct;
14+
// 0 = 1
15+
"#,
16+
r#"
17+
use foo::bar;
18+
19+
struct Struct;
20+
// 0 = 1
21+
"#,
22+
ImportGranularity::Crate,
23+
);
24+
}
25+
826
#[test]
927
fn respects_cfg_attr_fn() {
1028
check(

0 commit comments

Comments
 (0)