Skip to content

Commit 56b5de2

Browse files
authored
Rollup merge of #76218 - petrochenkov:shebang3, r=matklad
lexer: Tiny improvement to shebang detection Lexer now discerns between regular comments and doc comments, so use that. The change only affects the choice of reported errors.
2 parents c22de44 + b1491ea commit 56b5de2

File tree

3 files changed

+14
-13
lines changed

3 files changed

+14
-13
lines changed

compiler/rustc_lexer/src/lib.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -191,12 +191,16 @@ pub fn strip_shebang(input: &str) -> Option<usize> {
191191
// For simplicity we consider any line starting with `#!` a shebang,
192192
// regardless of restrictions put on shebangs by specific platforms.
193193
if let Some(input_tail) = input.strip_prefix("#!") {
194-
// Ok, this is a shebang but if the next non-whitespace token is `[` or maybe
195-
// a doc comment (due to `TokenKind::(Line,Block)Comment` ambiguity at lexer level),
194+
// Ok, this is a shebang but if the next non-whitespace token is `[`,
196195
// then it may be valid Rust code, so consider it Rust code.
197-
let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok|
198-
!matches!(tok, TokenKind::Whitespace | TokenKind::LineComment { .. } | TokenKind::BlockComment { .. })
199-
);
196+
let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
197+
!matches!(
198+
tok,
199+
TokenKind::Whitespace
200+
| TokenKind::LineComment { doc_style: None }
201+
| TokenKind::BlockComment { doc_style: None, .. }
202+
)
203+
});
200204
if next_non_whitespace_token != Some(TokenKind::OpenBracket) {
201205
// No other choice than to consider this a shebang.
202206
return Some(2 + input_tail.lines().next().unwrap_or_default().len());
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
11
#!///bin/bash
22
[allow(unused_variables)]
3-
//~^^ ERROR expected `[`, found doc comment
4-
5-
// Doc comment is misinterpreted as a whitespace (regular comment) during shebang detection.
6-
// Even if it wasn't, it would still result in an error, just a different one.
3+
//~^ ERROR expected item, found `[`
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
error: expected `[`, found doc comment `///bin/bash`
2-
--> $DIR/shebang-doc-comment.rs:1:3
1+
error: expected item, found `[`
2+
--> $DIR/shebang-doc-comment.rs:2:1
33
|
4-
LL | #!///bin/bash
5-
| ^^^^^^^^^^^ expected `[`
4+
LL | [allow(unused_variables)]
5+
| ^ expected item
66

77
error: aborting due to previous error
88

0 commit comments

Comments
 (0)