Provide helpful diagnostics for shebang lookalikes

This commit is contained in:
Pyrode 2025-02-27 12:23:47 +05:30
parent 961351c76c
commit a73e44bce1
5 changed files with 37 additions and 1 deletions

View file

@ -127,12 +127,29 @@ impl<'a> Parser<'a> {
let lo = self.token.span; let lo = self.token.span;
// Attributes can't have attributes of their own [Editor's note: not with that attitude] // Attributes can't have attributes of their own [Editor's note: not with that attitude]
self.collect_tokens_no_attrs(|this| { self.collect_tokens_no_attrs(|this| {
let pound_hi = this.token.span.hi();
assert!(this.eat(exp!(Pound)), "parse_attribute called in non-attribute position"); assert!(this.eat(exp!(Pound)), "parse_attribute called in non-attribute position");
let not_lo = this.token.span.lo();
let style = let style =
if this.eat(exp!(Bang)) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer }; if this.eat(exp!(Bang)) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
this.expect(exp!(OpenBracket))?; let mut bracket_res = this.expect(exp!(OpenBracket));
// If `#!` is not followed by `[`
if let Err(err) = &mut bracket_res
&& style == ast::AttrStyle::Inner
&& pound_hi == not_lo
{
err.note(
"the token sequence `#!` here looks like the start of \
a shebang interpreter directive but it is not",
);
err.help(
"if you meant this to be a shebang interpreter directive, \
move it to the very start of the file",
);
}
bracket_res?;
let item = this.parse_attr_item(ForceCollect::No)?; let item = this.parse_attr_item(ForceCollect::No)?;
this.expect(exp!(CloseBracket))?; this.expect(exp!(CloseBracket))?;
let attr_sp = lo.to(this.prev_token.span); let attr_sp = lo.to(this.prev_token.span);

View file

@ -3,6 +3,9 @@ error: expected `[`, found `B`
| |
LL | #!B LL | #!B
| ^ expected `[` | ^ expected `[`
|
= note: the token sequence `#!` here looks like the start of a shebang interpreter directive but it is not
= help: if you meant this to be a shebang interpreter directive, move it to the very start of the file
error: aborting due to 1 previous error error: aborting due to 1 previous error

View file

@ -3,6 +3,9 @@ error: expected `[`, found `/`
| |
LL | #!/bin/bash LL | #!/bin/bash
| ^ expected `[` | ^ expected `[`
|
= note: the token sequence `#!` here looks like the start of a shebang interpreter directive but it is not
= help: if you meant this to be a shebang interpreter directive, move it to the very start of the file
error: aborting due to 1 previous error error: aborting due to 1 previous error

View file

@ -0,0 +1,5 @@
// empty line
# !/bin/env
// checks that diagnostics for shebang lookalikes is not present
//@ error-pattern: expected `[`\n\n

View file

@ -0,0 +1,8 @@
error: expected `[`, found `/`
--> $DIR/shebang-split.rs:2:4
|
LL | # !/bin/env
| ^ expected `[`
error: aborting due to 1 previous error