Skip to content

Commit a0bc566

Browse files
committed
fix: Fix import insertion inserting after last comment in a file
1 parent 5d5bbec commit a0bc566

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ mod tests;
55
use std::cmp::Ordering;
66

77
use hir::Semantics;
8+
use parser::SyntaxKind;
89
use syntax::{
910
algo,
1011
ast::{self, make, AstNode, HasAttrs, HasModuleItem, HasVisibility, PathSegmentKind},
@@ -397,12 +398,16 @@ fn insert_use_(
397398
}
398399

399400
// there are no imports in this file at all
401+
// so put the import after all inner module attributes and possible license header comments
400402
if let Some(last_inner_element) = scope_syntax
401403
.children_with_tokens()
402-
.filter(|child| match child {
404+
.take_while(|child| match child {
403405
NodeOrToken::Node(node) => is_inner_attribute(node.clone()),
404-
NodeOrToken::Token(token) => is_comment(token.clone()),
406+
NodeOrToken::Token(token) => {
407+
[SyntaxKind::WHITESPACE, SyntaxKind::COMMENT].contains(&token.kind())
408+
}
405409
})
410+
.filter(|child| child.as_token().map_or(true, |t| t.kind() != SyntaxKind::WHITESPACE))
406411
.last()
407412
{
408413
cov_mark::hit!(insert_empty_inner_attr);
@@ -439,7 +444,3 @@ fn insert_use_(
439444
fn is_inner_attribute(node: SyntaxNode) -> bool {
440445
ast::Attr::cast(node).map(|attr| attr.kind()) == Some(ast::AttrKind::Inner)
441446
}
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

Lines changed: 18 additions & 0 deletions
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)