Skip to content

Commit 519d748

Browse files
committed
Auto merge of rust-lang#12545 - jeremyBanks:shebangs, r=Veykril
fix: inserted imports must come after a shebang if present The current `insert_use` logic adds the first `use` item near the beginning of the file, only skipping past comments and whitespace. However, it does not skip leading [shebang lines](https://en.wikipedia.org/wiki/Shebang_\(Unix\)). This can produce a syntax error, as shebangs are only accepted (ignored) on the first line of the file. ### Before Insertion (valid syntax) ```rust #!/usr/bin/env rust fn main() {} ``` ### After Insertion (invalid syntax) ```rust use foo::bar::Baz; #!/usr/bin/env rust fn main() {} ``` Rust analyzer's grammar is already shebang-aware, so this PR just adds that to the array of SyntaxKinds that are skipped past when looking for an insertion location, and adds a corresponding test case.
2 parents d39d520 + c32f133 commit 519d748

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

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

+2-1
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,8 @@ fn insert_use_(
403403
.take_while(|child| match child {
404404
NodeOrToken::Node(node) => is_inner_attribute(node.clone()),
405405
NodeOrToken::Token(token) => {
406-
[SyntaxKind::WHITESPACE, SyntaxKind::COMMENT].contains(&token.kind())
406+
[SyntaxKind::WHITESPACE, SyntaxKind::COMMENT, SyntaxKind::SHEBANG]
407+
.contains(&token.kind())
407408
}
408409
})
409410
.filter(|child| child.as_token().map_or(true, |t| t.kind() != SyntaxKind::WHITESPACE))

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

+11
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,17 @@ use foo::bar::Baz;"#,
454454
);
455455
}
456456

457+
#[test]
458+
fn inserts_after_shebang() {
459+
check_none(
460+
"foo::bar::Baz",
461+
"#!/usr/bin/env rust",
462+
r#"#!/usr/bin/env rust
463+
464+
use foo::bar::Baz;"#,
465+
);
466+
}
467+
457468
#[test]
458469
fn inserts_after_multiple_single_line_comments() {
459470
check_none(

0 commit comments

Comments
 (0)