Skip to content

Commit

Permalink
Auto merge of rust-lang#12197 - Veykril:insert-use-fix, r=Veykril
Browse files Browse the repository at this point in the history
fix: Fix import insertion inserting after last comment in a file
  • Loading branch information
bors committed May 9, 2022
2 parents 3d2d209 + c0feb38 commit c42cb9a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
14 changes: 7 additions & 7 deletions crates/ide-db/src/imports/insert_use.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use hir::Semantics;
use syntax::{
algo,
ast::{self, make, AstNode, HasAttrs, HasModuleItem, HasVisibility, PathSegmentKind},
ted, AstToken, Direction, NodeOrToken, SyntaxNode, SyntaxToken,
ted, Direction, NodeOrToken, SyntaxKind, SyntaxNode,
};

use crate::{
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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()
}
18 changes: 18 additions & 0 deletions crates/ide-db/src/imports/insert_use/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ use test_utils::{assert_eq_text, CURSOR_MARKER};

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(
Expand Down

0 comments on commit c42cb9a

Please sign in to comment.